Flask开发API 笔记

771 阅读3分钟

Flask 是一个轻量级的 WSGI web 应用框架。 它的设计目的是使入门快速和容易,能够扩展到复杂的应用程序。 它最初只是一个围绕 Werkzeug 和 Jinja 的简单包装器,现在已经成为最流行的 Python web 应用框架之一。

Flask 提供建议,但并不强制任何依赖项或项目布局。 开发者选择他们想要使用的工具和库。 社区也提供了许多扩展,使得添加新功能变得容易。

参考文档 flask.palletsprojects.com/en/1.1.x/

优点:上手简单,定制化,WSGI兼容

缺点:没有数据库帮助

从使用PyCharm新建 Flask 项目开始,新项目初始化完成了

from flask import Flask

app = Flask(__name__)


@app.route('/')
def hello_world():
    return 'Hello World!'


if __name__ == '__main__':
    app.run()

在文件顶部,引入第三方库

接着我们定义一个变量app,赋值为Flask的构造函数,这表示这个app会接收来自脚本的name,这里可以改成任意字符值

@装饰器,这里用来定义路由(类似JS里的高阶函数?)
接下来一个hello_world函数返回字符串 'Hello World!'

我们也可以新增一个路由和函数:

@app.route('/super_simple')
def super_simple():
    return 'Hello from planetary API'

现在运行服务器看看效果,执行命令python3 app.py后
打开http://127.0.0.1:5000/看到Hello World! 打开http://127.0.0.1:5000/super_simple看到 Hello from planetary API

使用Postman测试

添加自动热加载的设置(没有成功)
返回JSON格式文件,添加jsonify,并且将返回值赋值给message

from flask import Flask, jsonify

app = Flask(__name__)

@app.route('/')
def hello_world():
    return jsonify(message='Hello from planet')

if __name__ == '__main__':
    app.run()

改进返回结果

1 添加状态码

@app.route('/not_found')
def not_found():
    return jsonify(message='oops, 404'),404 

2 添加参数

from flask import Flask, jsonify, request

app = Flask(__name__)

@app.route('/parameters')
def parameters():
    name = request.args.get('name')
    age = request.args.get('age')
    if age < 18:
        return jsonify(message = 'sorry' + name + 'you are not old enough')
    else:
        return jsonify(message = 'welcome' + name + 'enough')


if __name__ == '__main__':
    app.run()

然而出现了不明不白的错误

TypeError: '<' not supported between instances of 'NoneType' and 'int'
127.0.0.1 - - [11/Jan/2020 10:57:41] "GET /parameters HTTP/1.1" 500 -
[2020-01-11 10:57:42,373] ERROR in app: Exception on /parameters [GET]
Traceback (most recent call last):
  File "/usr/local/lib/python3.7/site-packages/flask/app.py", line 2446, in wsgi_app
    response = self.full_dispatch_request()
  File "/usr/local/lib/python3.7/site-packages/flask/app.py", line 1951, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "/usr/local/lib/python3.7/site-packages/flask/app.py", line 1820, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File "/usr/local/lib/python3.7/site-packages/flask/_compat.py", line 39, in reraise
    raise value
  File "/usr/local/lib/python3.7/site-packages/flask/app.py", line 1949, in full_dispatch_request
    rv = self.dispatch_request()
  File "/usr/local/lib/python3.7/site-packages/flask/app.py", line 1935, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "app.py", line 17, in parameters
    if age < 18:
TypeError: '<' not supported between instances of 'NoneType' and 'int'
127.0.0.1 - - [11/Jan/2020 10:57:42] "GET /parameters HTTP/1.1" 500 -

数据库 ORM (SQLAlchemy)

打开设置 项目解释器
加号按钮添加

API security

There's Flask-Login, which handles logging in, logging out, and session management.
There's also Flask-User, which handles user registration, login, logout, and role based security, like the kind I mentioned earlier.

When evaluating these plugins, remember traditionally Flask is used to make traditional template based websites. I don't like the idea of storing session data in my API projects, so I don't use anything that requires session management.

flask-jwt

忘记密码使用邮件找回 flask-mail

mailtrap

WSGI is the Web Server Gateway Interface. It is a specification that describes how a web server communicates with web applications, and how web applications can be chained together to process one request.

Flask is a lightweight WSGI web application framework. It is designed to make getting started quick and easy, with the ability to scale up to complex applications. It began as a simple wrapper around Werkzeug and Jinja and has become one of the most popular Python web application frameworks.

Flask 模型选择 flask.palletsprojects.com/en/1.1.x/pa…