您好,欢迎访问一九零五行业门户网

实例讲解使用Python & Flask 实现RESTful Web API

下面小编就为大家带来一篇使用python & flask 实现restful web api的实例。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧
环境安装:
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 = {'1':'john', '2':'steve', '3':'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"
以上就是实例讲解使用python & flask 实现restful web api的详细内容。
其它类似信息

推荐信息