环境安装:

sudo pip install flask

Flask 是一个Python的微服务的框架,基于Werkzeug, 一个 WSGI 类库。

Flask 优点:

  • Written in Python (that can be an advantage);
  • Simple to use;
  • Flexible;
  • Multiple good deployment options;
  • RESTful request dispatching

RESOURCES

一个响应 /articles 和 /articles/:id的 API 服务:

from flask import Flask, url_for
app = Flask(__name__) @app.route('/')
def api_root():
return 'Welcome' @app.route('/articles')
def api_articles():
return 'List of ' + url_for('api_articles') @app.route('/articles/<articleid>')
def api_article(articleid):
return 'You are reading ' + articleid if __name__ == '__main__':
app.run()

请求:

curl http://127.0.0.1:5000/

响应:

GET /
Welcome GET /articles
List of /articles GET /articles/123
You are reading 123

REQUESTS

GET Parameters
from flask import request

@app.route('/hello')
def api_hello():
if 'name' in request.args:
return 'Hello ' + request.args['name']
else:
return 'Hello John Doe'

请求:

GET /hello
Hello John Doe GET /hello?name=Luis
Hello Luis
Request Methods (HTTP Verbs)
@app.route('/echo', methods = ['GET', 'POST', 'PATCH', 'PUT', 'DELETE'])
def api_echo():
if request.method == 'GET':
return "ECHO: GET\n" elif request.method == 'POST':
return "ECHO: POST\n" elif request.method == 'PATCH':
return "ECHO: PACTH\n" elif request.method == 'PUT':
return "ECHO: PUT\n" elif request.method == 'DELETE':
return "ECHO: DELETE"

请求指定request type:

curl -X PATCH http://127.0.0.1:5000/echo
GET /echo
ECHO: GET POST /ECHO
ECHO: POST
Request Data & Headers
from flask import json

@app.route('/messages', methods = ['POST'])
def api_message(): if request.headers['Content-Type'] == 'text/plain':
return "Text Message: " + request.data elif request.headers['Content-Type'] == 'application/json':
return "JSON Message: " + json.dumps(request.json) elif request.headers['Content-Type'] == 'application/octet-stream':
f = open('./binary', 'wb')
f.write(request.data)
f.close()
return "Binary message written!" else:
return "415 Unsupported Media Type ;)"

请求指定content type:

curl -H "Content-type: application/json" \
-X POST http://127.0.0.1:5000/messages -d '{"message":"Hello Data"}'
curl -H "Content-type: application/octet-stream" \
-X POST http://127.0.0.1:5000/messages --data-binary @message.bin

RESPONSES

from flask import Response

@app.route('/hello', methods = ['GET'])
def api_hello():
data = {
'hello' : 'world',
'number' : 3
}
js = json.dumps(data) resp = Response(js, status=200, mimetype='application/json')
resp.headers['Link'] = 'http://luisrei.com' return resp

查看response HTTP headers:

curl -i http://127.0.0.1:5000/hello

优化代码:

from flask import jsonify

使用

resp = jsonify(data)
resp.status_code = 200

替换

resp = Response(js, status=200, mimetype='application/json')

Status Codes & Errors

@app.errorhandler(404)
def not_found(error=None):
message = {
'status': 404,
'message': 'Not Found: ' + request.url,
}
resp = jsonify(message)
resp.status_code = 404 return resp @app.route('/users/<userid>', methods = ['GET'])
def api_users(userid):
users = {'':'john', '':'steve', '':'bill'} if userid in users:
return jsonify({userid:users[userid]})
else:
return not_found()

请求:

GET /users/2
HTTP/1.0 200 OK
{
"2": "steve"
} GET /users/4
HTTP/1.0 404 NOT FOUND
{
"status": 404,
"message": "Not Found: http://127.0.0.1:5000/users/4"
}

AUTHORIZATION

from functools import wraps

def check_auth(username, password):
return username == 'admin' and password == 'secret' def authenticate():
message = {'message': "Authenticate."}
resp = jsonify(message) resp.status_code = 401
resp.headers['WWW-Authenticate'] = 'Basic realm="Example"' return resp def requires_auth(f):
@wraps(f)
def decorated(*args, **kwargs):
auth = request.authorization
if not auth:
return authenticate() elif not check_auth(auth.username, auth.password):
return authenticate()
return f(*args, **kwargs) return decorated

replacing the check_auth function and using the requires_auth decorator:

@app.route('/secrets')
@requires_auth
def api_hello():
return "Shhh this is top secret spy stuff!"

HTTP basic authentication:

curl -v -u "admin:secret" http://127.0.0.1:5000/secrets

SIMPLE DEBUG & LOGGING

Debug:

app.run(debug=True)

Logging:

import logging
file_handler = logging.FileHandler('app.log')
app.logger.addHandler(file_handler)
app.logger.setLevel(logging.INFO) @app.route('/hello', methods = ['GET'])
def api_hello():
app.logger.info('informing')
app.logger.warning('warning')
app.logger.error('screaming bloody murder!') return "check your logs\n"

参考:

Flask documentation

Flask snippets

Werkzeug documentation

curl manual

使用 Python & Flask 实现 RESTful Web API的更多相关文章

  1. 我所理解的RESTful Web API [Web标准篇]

    REST不是一个标准,而是一种软件应用架构风格.基于SOAP的Web服务采用RPC架构,如果说RPC是一种面向操作的架构风格,而REST则是一种面向资源的架构风格.REST是目前业界更为推崇的构建新一 ...

  2. 我所理解的RESTful Web API [设计篇]

    <我所理解的RESTful Web API [Web标准篇]>Web服务已经成为了异质系统之间的互联与集成的主要手段,在过去一段不短的时间里,Web服务几乎清一水地采用SOAP来构建.构建 ...

  3. 对RESTful Web API的理解与设计思路

    距离上一篇关于Web API的文章(如何实现RESTful Web API的身份验证)有好些时间了,在那篇文章中提到的方法是非常简单而有效的,我在实际的项目中就这么用了,代码经过一段时间的磨合,已经很 ...

  4. About Restful Web Api Something.

    这种轻量级的服务架构目前来说还是比较流行的,比如微信的公众平台的接口开发就是一个很好的案例,提到restful那么他到底是一个什么样的东西? REST(Representational State T ...

  5. 【ASP.NET MVC 学习笔记】- 19 REST和RESTful Web API

    本文参考:http://www.cnblogs.com/willick/p/3441432.html 1.目前使用Web服务的三种主流的方式是:远程过程调用(RPC),面向服务架构(SOA)以及表征性 ...

  6. RESTful Web API 理解

    REST 是一种应用架构风格,不是一种标准,是面向资源架构(ROA)风格,与具体技术平台无关,REST架构的应用未必建立在Web之上,与之对应的是传统的Web Service 采用的面向操作的RPC架 ...

  7. 个人学期总结及Python+Flask+MysqL的web建设技术过程

    一个学期即将过去,我们也迎来了2018年.这个学期,首次接触了web网站开发建设,不仅是这门课程,还有另外一门用idea的gradle框架来制作网页. 很显然,用python语言的flask框架更加简 ...

  8. RESTful Web API 实践

    REST 概念来源 网络应用程序,分为前端和后端两个部分.当前的发展趋势,就是前端设备层出不穷(手机.平板.桌面电脑.其他专用设备...). 因此,必须有一种统一的机制,方便不同的前端设备与后端进行通 ...

  9. Python+Flask+MysqL的web建设技术过程

    一.前言(个人学期总结) 个人总结一下这学期对于Python+Flask+MysqL的web建设技术过程的学习体会,Flask小辣椒框架相对于其他框架而言,更加稳定,不会有莫名其妙的错误,容错性强,运 ...

随机推荐

  1. 设计模式,Let's Go! (上)

    * { color: #3e3e3e } body { font-family: "Helvetica Neue", Helvetica, "Hiragino Sans ...

  2. [js高手之路] dom常用节点属性兼容性详解与应用

    一.每个DOM节点都有一个nodeType属性,表示节点类型, NodeType一共有12种类型,我们可以通过遍历内置的Node构造函数获取 window.onload = function(){ v ...

  3. Java 中判断 JSONObject 对应的 VALUE 为空

    目前发现有两种包.两种不一样的json包. 第一种情况是: json包是json-lib包是net.sf.json 怎样判断JSONObject返回的是字符串null还是null值. 研究源码发现.J ...

  4. VS2015 安装nuget离线包nupkg文件

    最近在做项目进度管理时,想通过安装net.sf.mpxj-for-csharp包读取.mpp格式文件,通过Nuget在线安装时,出现以下情况,无法安装,故开启离线安装道路. 离线安装步骤如下: 一.下 ...

  5. SpringMVC(二)--处理数据模型、ModelAndView、Model、Map、重定向、@ModelAttribute、

    1.处理模型数据 Spring MVC 提供了以下几种途径输出模型数据:      – ModelAndView:处理方法返回值类型为 ModelAndView 时, 方法体即可通过该对象添加模型数据 ...

  6. 线性代数-矩阵-【2】矩阵生成 C和C++实现

    矩阵的知识点之多足以写成一本线性代数. 所以我们把矩阵的运算封装成矩阵类.以C++为主进行详解. 点击这里可以跳转至 [1]矩阵汇总:http://www.cnblogs.com/HongYi-Lia ...

  7. Struts:文件上传下载

  8. LeetCode315—Count of Smaller Numbers After Self—Java版归并算法

    这是我在研究leetcode的solution第一个解决算法时,自己做出的理解,并且为了大家能看懂,做出了详细的注释. 此算法算是剑指Offer36的升级版,都使用的归并算法,但是此处的算法,难度更高 ...

  9. [2017-05-31]Abp介绍和经验分享-目录

    很久没动博客了,人比较懒. 最近想写点啥,主要就介绍下ABP框架和我这两年的使用经验. 文档翻译之类的工作就算了,需要的请参考: 官方文档 PS:官方文档末尾有中文文档的链接,这里就不贴了 先列个提纲 ...

  10. JDBCTemplate

    1.Spring提供的一个操作数据库的技术JdbcTemplate,是对Jdbc的封装.语法风格非常接近DBUtils. JdbcTemplate可以直接操作数据库,加快效率,而且学这个JdbcTem ...