4

【Python Web实战】Python Flask的静态路由和动态路由

 3 years ago
source link: https://blog.csdn.net/nokiaguy/article/details/115107385
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

【Python Web实战】Python Flask的静态路由和动态路由

路由分为静态和动态两种,静态路由就是在上一节使用的路由,直接使用@app.route定义,route的参数值就是路由,也就是在浏览器地址栏中输入Url的路径。例如,@app.route('/greet/abc')表示访问该路由的Url是http://localhost:5000/greet/abc。

尽管静态路由可以解决大多数问题,但如果有多个类似的路由要使用同一个路由函数处理,或想通过Url的路径传递一些参数,就要用到动态路由。先看下面几个Url。

上面5个Url只有路径的最后部分不同(xyz、abc、what、test、geekori),前面的都相同。如果要想让着5个Url都是用同一个路由函数处理,就要用到动态路由。

动态路由的解决方案是将Url中不同的部分作为变量处理,也就是说,需要将xyz、abc、what、test、geekori这5个值映射到服务端的一个变量中。这个变量也需要定义在路由中定义。需要使用一对尖括号(<...>)将变量括起来。假设保存这5个值的变量名为name(也可以将name称为动态路由的参数),那么动态路由的定义代码如下:

@ap

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK