Flask之路由(app.route)详解

目录

创建路由的两种方式

方式一

方式二

 反向生成URL

 注意事项 !!!

原因 :

解决 :

总结 :

自定义路由转换器

重定向


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

在 route 源码中

    def route(self, rule: str, **options: t.Any) -> t.Callable:
        """Decorate a view function to register it with the given URL
        rule and options. Calls :meth:`add_url_rule`, which has more
        details about the implementation.

        .. code-block:: python

            @app.route("/")
            def index():
                return "Hello, World!"

        See :ref:`url-route-registrations`.

        The endpoint name for the route defaults to the name of the view
        function if the ``endpoint`` parameter isn't passed.

        The ``methods`` parameter defaults to ``["GET"]``. ``HEAD`` and
        ``OPTIONS`` are added automatically.

        :param rule: The URL rule string.
        :param options: Extra options passed to the
            :class:`~werkzeug.routing.Rule` object.
        """

        def decorator(f: t.Callable) -> t.Callable:
            endpoint = options.pop("endpoint", None)
            self.add_url_rule(rule, endpoint, f, **options)
            return f

        return decorator

这一部分

 解释一下就是

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

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

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

 @decorator

– decoratoe ( 函数名 )

创建路由的两种方式

方式一

别忘了 导包创建一个实例

from flask import Flask

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

 运行 :

方式二

使用 add_url_rule  

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

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

运行 : 

 反向生成URL

endpoint 相当于创建了一个别名 

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

from flask import url_for

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

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

@app.route('/index',methods=['GET','POST'],endpoint="first")
def index():
    h1 = url_for("first")
    h2 = url_for("login")       # 不起别名 使用默认名
    h3 = url_for("logout")      # 不起别名 使用默认名
    print(h1,h2,h3)
    return "index"

@app.route('/login',methods=['GET','POST'])
def login():
    return "login"

@app.route('/logout',methods=['GET','POST'])
def logout():
    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

在你的终端命令行输入

netstat -ano|findstr “5000”

然后杀掉对应 pid  

结束进程

taskkill /pid 52824 /f

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

总结 :

在运行 flask 程序时

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

右击run程序出来的结果

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

有一种改进方式

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

 用终端去运行,点击它

 Ctrl + C 快捷键结束

自定义路由转换器

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

 运行 :

重定向

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

打个比方

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

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

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

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

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

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

@app.route('/old',methods=['GET','POST'],redirect_to='/new')
def old():
    return "老功能"

@app.route('/new',methods=['GET','POST'])
def new():
    return "新功能"

运行 :

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

来源:KEE_YiM

物联沃分享整理
物联沃-IOTWORD物联网 » Flask之路由(app.route)详解

发表评论