Flask路由与请求对象
什么是路由?
在web开发中,“route”是指根据url分配到对应的处理程序。——来源知乎-贺师俊
路由注册
from flask import Flask #从flask包中引入Flask类
app = Flask(__name__)
@app.route("/")
def hello():
return "Hello test"
@app.route("/my/<user_name>")
def my(user_name):
return "my pages:%s"%user_name
if __name__ == "__main__":
app.run(host = "0.0.0.0",debug=True)
def hello():
return "Hello test"
app.add_url_rule(rule = "/test",view_func= hello)
蓝图:
可以分成两个文件,一个里面放主函数,为程序运行入口,还有flask对象注册,将蓝图注册到flask对象中,url_prefix参数可以理解为注册根目录,另一个文件中通过route装饰器来创建子目录响应。详情见获取请求对象和POST参数。
from flask import Flask,Blueprint
app = Flask(__name__)
index_page = Blueprint("index_page",__name__)
@index_page.route("/")
def index_page_index():
return "index_page"
app.register_blueprint(index_page,url_prefix = "/test")
@app.route("/")
def hello():
return "hello test"
if __name__ == "__main__":
app.run(host = "0.0.0.0",debug=True)
解读HTTP请求流程
获取请求对象的GET和POST参数
main.py
# -*- coding: utf-8 -*-
from flask import Flask
from page1 import index_page
app = Flask( __name__ )
app.register_blueprint( index_page,url_prefix ="/test" )
if __name__ == "__main__":
app.run( host = "0.0.0.0",debug=True )
page1.py
# -*- coding: utf-8 -*-
from flask import Flask,Blueprint,request
index_page = Blueprint( "index_page",__name__)
@index_page.route( "/" )
def index_page_index():
return "index page1"
@index_page.route( "/me" )
def hello():
return "hello ,I Love Imooc"
@index_page.route("/get")
def get():
# var_a = request.args.get( "a","i love imooc" )
req = request.values
var_a = req["a"] if "a" in req else 'i am test' #三元运算式
return "request:%s,params:%s,var_a:%s"%(request.method,request.args,var_a )
# @index_page.route("/post",methods = ["POST"])
# def post():
# var_a = request.form['a']
# return "request:%s,params:%s,var_a:%s"%(request.method,request.form,var_a)
@index_page.route("/post",methods = [ "POST" ])
def post():
# var_a = request.form['a'] if 'a' in request.form else ''
# var_a = ""
# if 'a' in request.form:
# var_a = request.form["a"]
req = request.values
var_a = req["a"] if "a" in req else 'i am test'
return "request:%s,params:%s,var_a:%s"%( request.method,request.form,var_a )
@index_page.route("/upload",methods = ["POST"])
def upload():
f = request.files['file'] if "file" in request.files else None
return "request:%s,params:%s,file:%s"%( request.method,request.files,f)