@app.route()
methods:当前url地址,允许访问的请求方式
@app.route("/info", methods=["GET", "POST"]) def student_info(): stu_id = int(request.args.get("id")) return f"{stu_id}" # Python3.6的新特性 f"{变量名}"
endpoint:反向生成url地址,默认为视图函数名,导入url_for
from flask import Flask, url_for app = Flask(__name__) @app.route("/index",methods=["POST","GET"],endpoint="index_s") def index(): return url_for("index_s") #index if __name__ == ‘__main__‘: app.run(debug=True)
strict_slashes:url地址结尾符"/"的控制,默认为True:结尾不能的"/",False:无论结尾是否有"/"均可以访问
from flask import Flask, url_for app = Flask(__name__) #访问地址 /index @app.route("/index",strict_slashes=True) def index(): return url_for("index_s") #访问地址:/login 或 /login/ @app.route("/login",strict_slashes=False) def login(): return ‘欢迎‘ if __name__ == ‘__main__‘: app.run(debug=True)
defaults : 视图函数的参数默认值{"nid":1}
from flask import Flask, url_for app = Flask(__name__) @app.route("/index", defaults={"nid": 1}) def index(nid): print(nid) return "哈喽" if __name__ == ‘__main__‘: app.run(debug=True)
redirect_to:url地址重定向,301永久重定向,在进入视图函数之前跳转
from flask import Flask, url_for app = Flask(__name__) @app.route("/index", redirect_to="/login") def index(id): print(id) return "光临" @app.route("/login") def login(): return ‘欢迎‘ if __name__ == ‘__main__‘: app.run(debug=True)
动态路由参数
接受文件名,返回文件
<int:id>:只能是数字
from flask import Flask, url_for app = Flask(__name__) @app.route("/index/<int:a>",) #访问 http://127.0.0.1:5000/index/1 def index(a): print(a) # 1 return "光临" if __name__ == ‘__main__‘: app.run(debug=True)
<string:str>:可以是数字也可以是字符串
from flask import Flask, url_for app = Flask(__name__) @app.route("/index/<string:str>",) def index(str): print(str) return "光临" if __name__ == ‘__main__‘: app.run(debug=True)
也可以不用定义类型,默认接受字符串
from flask import Flask, url_for app = Flask(__name__) @app.route("/index/<name>",) def index(name): print(name) return "光临" if __name__ == ‘__main__‘: app.run(debug=True)
原文地址:https://www.cnblogs.com/wanglan/p/10559314.html
时间: 2024-10-30 05:12:42