Flask支持FBV、CBV两种模式,这里先聊FBV

指定HTTP方法

  1. @app.route("路由", methods=["请求方法"])
  2. GET请求
  3. request.args.get("xx")
  4. POST请求
  5. request.form.get("xxx")
  1. from flask import Flask, request
  2. app = Flask(__name__)
  3. # 默认都是接受GET请求
  4. @app.route("/login/", methods=['GET', 'POST'])
  5. def login():
  6. # GET 参数直接在URL中
  7. # POST 参数没有直接体现在URL地址中
  8. print(request.args)
  9. # GET请求接受参数
  10. # print(request.args.get('username'))
  11. # POST请求接受参数
  12. # print(request.form.get("name"))
  13. 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”)

  1. if name:
  2. return name
  3. else:
  4. # 重定向到登陆页面
  5. return redirect(url_for("login"), code=301)
  1. <a name="0IvpL"></a>
  2. ## 函数的返回值
  3. 字符串<br />`return "字符串" `<br />元组<br />`return "字符串", 状态码 `<br />Response<br />`return Response("字符串", "状态码", mimetype="") `<br />make_response<br />`make_response("字符串")`<br />可以使⽤make_response函数来创建Response对象,这个⽅法可以设置额外的 <br />数据,⽐如设置cookie,header信息
  4. ```python
  5. from flask import Flask, redirect, Response, make_response
  6. app = Flask(__name__)
  7. @app.route("/about/")
  8. def about():
  9. # return "juran"
  10. # return ['123']
  11. # return {"name": "juran"}
  12. # return ('name', "python")[1]
  13. # return (["python"], "java")
  14. return Response("关于我们", status=200, mimetype="text/html")
  15. # return "关于我们", 200
  16. # return make_response("关于我们")

add_url_rule

  1. from flask import Flask, render_template, url_for
  2. app = Flask(__name__)
  3. @app.route('/')
  4. def index():
  5. print(url_for('profilePage')) # /profile/
  6. return '首页'
  7. def profile():
  8. print(url_for('FirstPage'))
  9. return render_template("profile/user.html")
  10. # 添加URL规则
  11. app.add_url_rule("/profile/", endpoint='profilePage', view_func=profile) # endpoint别名