对endpoint的理解

观察以下:print(app.url_map) 的输出可知,url_map输出的是url与endpoint的映射
可以理解为每个视图函数都有一个endpoint, 通过端点找到具体调用的是哪个试图函数

  1. from flask import Flask
  2. app = Flask(__name__)
  3. @app.route('/test', endpoint='Test')
  4. def test():
  5. pass
  6. @app.route('/', endpoint='index')
  7. def hello_world():
  8. return 'Hello World!'
  9. if __name__ == '__main__':
  10. print(app.url_map)
  11. app.run()
  12. """
  13. Map([<Rule '/test2' (OPTIONS, GET, HEAD) -> test2>,
  14. <Rule '/test' (OPTIONS, GET, HEAD) -> Test>,
  15. <Rule '/' (OPTIONS, GET, HEAD) -> index>,
  16. <Rule '/static/<filename>' (OPTIONS, GET, HEAD) -> static>])
  17. * Serving Flask app 'endpoint' (lazy loading)
  18. * Environment: production
  19. * Serving Flask app 'endpoint' (lazy loading)
  20. * Environment: production
  21. WARNING: This is a development server. Do not use it in a production deployment.
  22. Use a production WSGI server instead.
  23. * Debug mode: off
  24. * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
  25. """

对蓝图的理解

Flask蓝图的理解

对命名空间的理解

url_for

url_for()函数最简单的就是以视图函数名作为函数,返回对应的URL
源码注释该函数用法为:使用提供的方法生成给定端点的URL

  1. @api.route("/hello", "/world", endpoint='mutil_endpoint')
  2. class MonogoTest(Resource):
  3. @api.doc("这是一个多url的")
  4. def get(self):
  5. """多url接口"""
  6. return "hello world!"
  7. 如上调用url_for("mutil_endpoint"), 得到的结果就是"/hello"或者"/world"

⚠️tips:当使用蓝图时,使用url_for()函数需要指定具体使用哪个蓝图下的endpoint

  1. eg:
  2. # blueprint = Blueprint("api", __name__, url_prefix="/api/v1")
  3. url_for("blueprint.mutil_endpoint")