指定HTTP方法
@app.route("路由", methods=["请求方法"])
GET请求
request.args.get("xx")
POST请求
request.form.get("xxx")
from flask import Flask, request
app = Flask(__name__)
# 默认都是接受GET请求
@app.route("/login/", methods=['GET', 'POST'])
def login():
# GET 参数直接在URL中
# POST 参数没有直接体现在URL地址中
print(request.args)
# GET请求接受参数
# print(request.args.get('username'))
# POST请求接受参数
# print(request.form.get("name"))
return "login"
重定向
return redirect(url_for("函数名字"))
- 301 永久
- 302 暂时 ```python from flask import Flask, request, redirect app = Flask(name)
@app.route(“/profile/“) def profile(): name = request.args.get(“name”)
if name:
return name
else:
# 重定向到登陆页面
return redirect(url_for("login"), code=301)
<a name="0IvpL"></a>
## 函数的返回值
字符串<br />`return "字符串" `<br />元组<br />`return "字符串", 状态码 `<br />Response<br />`return Response("字符串", "状态码", mimetype="") `<br />make_response<br />`make_response("字符串")`<br />可以使⽤make_response函数来创建Response对象,这个⽅法可以设置额外的 <br />数据,⽐如设置cookie,header信息
```python
from flask import Flask, redirect, Response, make_response
app = Flask(__name__)
@app.route("/about/")
def about():
# return "juran"
# return ['123']
# return {"name": "juran"}
# return ('name', "python")[1]
# return (["python"], "java")
return Response("关于我们", status=200, mimetype="text/html")
# return "关于我们", 200
# return make_response("关于我们")
add_url_rule
from flask import Flask, render_template, url_for
app = Flask(__name__)
@app.route('/')
def index():
print(url_for('profilePage')) # /profile/
return '首页'
def profile():
print(url_for('FirstPage'))
return render_template("profile/user.html")
# 添加URL规则
app.add_url_rule("/profile/", endpoint='profilePage', view_func=profile) # endpoint别名