当前位置:网站首页>Flask之路由(app.route)详解
Flask之路由(app.route)详解
2022-07-30 14:55:00 【segegefe】
目录
在讲创建路由之前先了解大致流程,工作本质
在 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 网页上

先自我介绍一下,小编13年上师交大毕业,曾经在小公司待过,去过华为OPPO等大厂,18年进入阿里,直到现在。深知大多数初中级java工程师,想要升技能,往往是需要自己摸索成长或是报班学习,但对于培训机构动则近万元的学费,着实压力不小。自己不成体系的自学效率很低又漫长,而且容易碰到天花板技术停止不前。因此我收集了一份《java开发全套学习资料》送给大家,初衷也很简单,就是希望帮助到想自学又不知道该从何学起的朋友,同时减轻大家的负担。添加下方名片,即可获取全套学习资料哦
边栏推荐
- Sleuth+Zipkin (visualization) service link tracking
- JHM:芳环羟化双加氧酶数据库DARHD建立及相关引物评价
- JUC common thread pool source learning 02 ( ThreadPoolExecutor thread pool )
- 华为云重磅发布开源软件治理服务——软件成分分析
- websocket flv 客户端解封包
- 嵌入式开发:嵌入式基础知识——正确启动固件项目的 10 条建议
- ECCV2022 | FPN错位对齐,实现高效半监督目标检测 (PseCo)
- Mysql database query is very slow. Besides the index, what else can be caused?
- 元宇宙的前景及四大赛道
- HUAWEI CLOUD Releases Open Source Software Governance Service - Software Component Analysis
猜你喜欢

481-82(105、24、82、34、153)

Mysql database query is very slow. Besides the index, what else can be caused?

视频切换播放的例子(视频切换范例)代码

timed task corn

Installing and Uninstalling MySQL on Mac

Huawei issues another summoning order for "Genius Boys"!He, who had given up an annual salary of 3.6 million, also made his debut

This editor actually claims to be as fast as lightning!

GeoServer + openlayers

哨兵

nodejs环境变量设置
随机推荐
What is Ts?
【喂到嘴边了的模块】准备徒手撸GUI?用Arm-2D三分钟就够了
Load Base Split 使用文档
【嵌入式】适用于Cortex-M3(STM32F10x)的IQmath库
定时任务 corn
极验深知v2分析
tiup list
Office Automation | Office Software and Edraw MindMaster Shortcuts
Mysql database query is very slow. Besides the index, what else can be caused?
Normal and escaped strings for postgresql
71-page comprehensive overall solution for global tourism 2021 ppt
Lock wait timeout exceeded解决方案
[Enlightenment by Opportunity-53]: "Sushu"-3- Self-cultivation and Self-cultivation
4 senior experts share the insider architecture design and implementation principles of Flink technology with years of experience in large factories
【云原生】阿里云ARMS业务实时监控
Sentinel
关于MySQL主从复制的数据同步延迟问题
工具| execsnoop 短时进程追踪工具
CMake库搜索函数居然不搜索LD_LIBRARY_PATH
如何做好技术选型