Flask

Flask

Structure of Flask App

https://www.digitalocean.com/community/tutorials/how-to-structure-large-flask-applications

https://github.com/pallets/flask/wiki/Large-app-how-to

https://github.com/Robpol86/Flask-Large-Application-Example


Make RESTful API with Flask

http://blog.luisrei.com/articles/flaskrest.html

  • Create proper url (principle: everything is resource, Noun, not Verb)
  • Define proper HTTP method
  • Flask Request (handle client input)
    • Define header
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 ;)"
  • Flask Response (use to return result)
    • Return response according to HTTP standard
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
  • Error handling
  • Authorization

Flask-Restful

Request Parsing

Flask-RESTful’s request parsing interface, reqparse, is modeled after the argparse interface. It’s designed to provide simple and uniform access to any variable on the flask.request object in Flask.

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容