0


Flask之路由(app.route)详解

在讲创建路由之前先了解大致流程,工作本质

在 route 源码中

  1. def route(self, rule: str, **options: t.Any) -> t.Callable:
  2. """Decorate a view function to register it with the given URL
  3. rule and options. Calls :meth:`add_url_rule`, which has more
  4. details about the implementation.
  5. .. code-block:: python
  6. @app.route("/")
  7. def index():
  8. return "Hello, World!"
  9. See :ref:`url-route-registrations`.
  10. The endpoint name for the route defaults to the name of the view
  11. function if the ``endpoint`` parameter isn't passed.
  12. The ``methods`` parameter defaults to ``["GET"]``. ``HEAD`` and
  13. ``OPTIONS`` are added automatically.
  14. :param rule: The URL rule string.
  15. :param options: Extra options passed to the
  16. :class:`~werkzeug.routing.Rule` object.
  17. """
  18. def decorator(f: t.Callable) -> t.Callable:
  19. endpoint = options.pop("endpoint", None)
  20. self.add_url_rule(rule, endpoint, f, **options)
  21. return f
  22. return decorator

这一部分

解释一下就是

程序从上往下 首先进入app.route路由部分然后 执行了 decorator

这里的 def decorator() 就相当于将 app.route赋给 decorator

  1. decorator = app.route('/index',methods=['GET','POST'])

@decorator

  • decoratoe ( 函数名 )

创建路由的两种方式

方式一

别忘了 导包创建一个实例

  1. from flask import Flask
  2. app = Flask(__name__)
  1. @app.route('/one',methods=['GET','POST'])
  2. def one():
  3. return "创建路由的方法一,返回值为: one"

运行 :

方式二

**使用 add_url_rule **

同样别忘记了导包和创建实例

  1. def two():
  2. return "创建路由的方法二,返回值为: two"
  3. app.add_url_rule('/two',view_func=two)

运行 :

反向生成URL

endpoint 相当于创建了一个别名

在反向生成的时候** 需要从 flask 里面导入 url_for**

  1. from flask import url_for

用于反向生成的时候才写别名

如果不起别名,则 默认是其函数名

  1. @app.route('/index',methods=['GET','POST'],endpoint="first")
  2. def index():
  3. h1 = url_for("first")
  4. h2 = url_for("login") # 不起别名 使用默认名
  5. h3 = url_for("logout") # 不起别名 使用默认名
  6. print(h1,h2,h3)
  7. return "index"
  8. @app.route('/login',methods=['GET','POST'])
  9. def login():
  10. return "login"
  11. @app.route('/logout',methods=['GET','POST'])
  12. def logout():
  13. return "logout"

注意事项 !!!

在我第一遍做简单flask的时候出现的一个问题

做到第二个项目的时候页面出现的却是第一个项目的结果

也就是在我想运行** 反向生成URL.py **文件的时候 输入了我设置的新rule 可是网页一直显示 Not Found 并且输入第一个项目的rule可以正常显示

原因 :

  1. 要么是你的上一个项目运行没有终止

2.要么是端口(12.0.0.1:5000)被占用了

解决 :

如果是你上一项目没有终止,正常情况下可以点击红色方块结束程序运行,终止掉程序运行

当建立多个项目时,127.0.0.1:5000这个端口被反复占用,导致pycharm无法杀掉上一个项目的进程,这时需要手动杀死进程

快捷键 Win + R 打开 cmd

在你的终端命令行输入

  1. netstat -ano|findstr 5000

然后杀掉对应 pid

结束进程

  1. taskkill /pid 52824 /f

再次运行你的 .py 文件就可以正常显示了

总结 :

在运行 flask 程序时

通常大部分人操作时和python文件一样运行 右击然后run

右击run程序出来的结果

容易忘记停止并且可能会出现端口堵塞等问题

有一种改进方式

在下方有一个 Terminal (终端) 的标识

用终端去运行,点击它

Ctrl + C 快捷键结束

自定义路由转换器

  1. @app.route('/index/<int:nid>',methods=['GET','POST'])
  2. def index(nid):
  3. print("int类型: ", nid)
  4. return "返回结果是: int类型的nid"

运行 :

重定向

这个在很多场景都可以使用

打个比方

现在公司里有了一个用了很久的一个网站,

然后让公司里的程序员去对这个网站做一个优化改进

可是原来的网站网址被公司员工已经用了N多边了,网址都已经刻入DNA里了

现在优化好的新的网站网址告诉公司员工们,

为了避免一些员工习惯性的登入旧网站网址,

程序员要对旧网站网址增添一个重定向,也就是说 如果有员工习惯性的登入旧网站网址,那么这个重定向就起作用了,它会跳转到i新网站网址上去

  1. @app.route('/old',methods=['GET','POST'],redirect_to='/new')
  2. def old():
  3. return "老功能"
  4. @app.route('/new',methods=['GET','POST'])
  5. def new():
  6. return "新功能"

运行 :

输入 old 会自动跳转到 new 网页上

标签: flask python pycharm

本文转载自: https://blog.csdn.net/weixin_57871623/article/details/121576995
版权归原作者 KEE_YiM 所有, 如有侵权,请联系我们删除。

“Flask之路由(app.route)详解”的评论:

还没有评论