当前位置:Gxlcms > Python > 实例讲解使用Python&Flask实现RESTfulWebAPI

实例讲解使用Python&Flask实现RESTfulWebAPI

时间:2021-07-01 10:21:17 帮助过:108人阅读

下面小编就为大家带来一篇使用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 服务:


  1. from flask import Flask, url_for
  2. app = Flask(__name__)
  3. @app.route('/')
  4. def api_root():
  5. return 'Welcome'
  6. @app.route('/articles')
  7. def api_articles():
  8. return 'List of ' + url_for('api_articles')
  9. @app.route('/articles/<articleid>')
  10. def api_article(articleid):
  11. return 'You are reading ' + articleid
  12. if __name__ == '__main__':
  13. 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


  1. from flask import request
  2. @app.route('/hello')
  3. def api_hello():
  4. if 'name' in request.args:
  5. return 'Hello ' + request.args['name']
  6. else:
  7. return 'Hello John Doe'

请求:

GET /hello
Hello John Doe

GET /hello?name=Luis
Hello Luis

Request Methods (HTTP Verbs)


  1. @app.route('/echo', methods = ['GET', 'POST', 'PATCH', 'PUT', 'DELETE'])
  2. def api_echo():
  3. if request.method == 'GET':
  4. return "ECHO: GET\n"
  5. elif request.method == 'POST':
  6. return "ECHO: POST\n"
  7. elif request.method == 'PATCH':
  8. return "ECHO: PACTH\n"
  9. elif request.method == 'PUT':
  10. return "ECHO: PUT\n"
  11. elif request.method == 'DELETE':
  12. 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


  1. from flask import json
  2. @app.route('/messages', methods = ['POST'])
  3. def api_message():
  4. if request.headers['Content-Type'] == 'text/plain':
  5. return "Text Message: " + request.data
  6. elif request.headers['Content-Type'] == 'application/json':
  7. return "JSON Message: " + json.dumps(request.json)
  8. elif request.headers['Content-Type'] == 'application/octet-stream':
  9. f = open('./binary', 'wb')
  10. f.write(request.data)
  11. f.close()
  12. return "Binary message written!"
  13. else:
  14. 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


  1. from flask import Response
  2. @app.route('/hello', methods = ['GET'])
  3. def api_hello():
  4. data = {
  5. 'hello' : 'world',
  6. 'number' : 3
  7. }
  8. js = json.dumps(data)
  9. resp = Response(js, status=200, mimetype='application/json')
  10. resp.headers['Link'] = 'http://luisrei.com'
  11. return resp

查看response HTTP headers:

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

优化代码:

from flask import jsonify

使用


  1. resp = jsonify(data)
  2. resp.status_code = 200

替换


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

Status Codes & Errors


  1. @app.errorhandler(404)
  2. def not_found(error=None):
  3. message = {
  4. 'status': 404,
  5. 'message': 'Not Found: ' + request.url,
  6. }
  7. resp = jsonify(message)
  8. resp.status_code = 404
  9. return resp
  10. @app.route('/users/<userid>', methods = ['GET'])
  11. def api_users(userid):
  12. users = {'1':'john', '2':'steve', '3':'bill'}
  13. if userid in users:
  14. return jsonify({userid:users[userid]})
  15. else:
  16. 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


  1. from functools import wraps
  2. def check_auth(username, password):
  3. return username == 'admin' and password == 'secret'
  4. def authenticate():
  5. message = {'message': "Authenticate."}
  6. resp = jsonify(message)
  7. resp.status_code = 401
  8. resp.headers['WWW-Authenticate'] = 'Basic realm="Example"'
  9. return resp
  10. def requires_auth(f):
  11. @wraps(f)
  12. def decorated(*args, **kwargs):
  13. auth = request.authorization
  14. if not auth:
  15. return authenticate()
  16. elif not check_auth(auth.username, auth.password):
  17. return authenticate()
  18. return f(*args, **kwargs)
  19. 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:


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

以上就是实例讲解使用Python & Flask 实现RESTful Web API的详细内容,更多请关注Gxl网其它相关文章!

人气教程排行