FLASK总结
FLASK是一个简单易用且扩展性极强的python实现的web开发微框架
Flask安装
第一个Flask程序
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello_world():
return 'Hello, World!'
So what did that code do?
First we imported the Flask class. An instance of this class will be our WSGI application.
Next we create an instance of this class. The first argument is the name of the application’s module or package. If you are using a single module (as in this example), you should use name because depending on if it’s started as application or imported as module the name will be different (‘main’ versus the actual import name). This is needed so that Flask knows where to look for templates, static files, and so on. For more information have a look at the Flask documentation.
We then use the route() decorator to tell Flask what URL should trigger our function.
The function is given a name which is also used to generate URLs for that particular function, and returns the message we want to display in the user’s browser.
MTV模型
启动及调试
开启调试模式方式二
URL配置及路由
URL配置
请求与响应
上下文
在处理请求之前,FLlask application会先激活请求上下文和应用上下文,当请求处理完成后先删除应用上下文再删除请求上下文。
请求上下文对象
If you have set Flask.secret_key (or configured it from SECRET_KEY) you can use sessions in Flask applications. A session makes it possible to remember information from one request to another. The way Flask does this is by using a signed cookie. The user can look at the session contents, but can’t modify it unless they know the secret key, so make sure to set that to something complex and unguessable. session可以用于在各请求之间传递数据。
应用上下文对象
Application Globals: To share data that is valid for one request only from one function to another, a global variable is not good enough because it would break in threaded environments. Flask provides you with a special object that ensures it is only valid for the active request and that will return different values for each request. g的生命周期是一个请求,在请求内部可以传递数据,不能跨请求传递数据。
请求报文
请求钩子
使用钩子函数可以减少重复代码的编写,便于维护。
响应报文
其他视图
ORM
flask-sqlalchemy介绍及安装
Flask-SQLAlchemy配置
数据库模型设计及创建表
数据增删改查
分页