windows python web route 路由

简介: windows python web route 路由

windows python web route 路由

tags: flask

文章目录

1. 路由介绍

路由是指用户请求的URL与视图函数之间的映射。Flask框架 根据HTTP请求的URL在路由表中匹配预定义的URL规则,找到对应的视图函数, 并将视图函数的执行结果返回WSGI服务器。

可见路由表在Flask应用中处于相当核心的位置。路由表的内容是由应用开发者填充。


route装饰器 :可以使用Flask应用实例的route装饰器将一个URL规则绑定到 一个视图函数上。

2. 路由类型

2.1 一般路由url

第一种:没有名字的路由

@app.route('/')
def hello_world():
    return 'Welcome to Hello World !'

访问:http://127.0.0.1:5000/

第二种,定义一个名字

@app.route('/hello')
def hello_world():
    return 'Welcome to Hello World !'

访问:http://127.0.0.1:5000/hello

第三种:一个函数多个url路由规则

@app.route('/')
@app.route('/hello')
@app.route('/hello/<name>')
def hello(name=None):
    if name is None:
        name = 'World'
    return 'Hello %s' % name

访问:http://127.0.0.1:5000/

访问:http://127.0.0.1:5000/hello

访问:http://127.0.0.1:5000/hello/xiaoaming

访问:http://127.0.0.1:5000/ligang


第四种:add_url_rule()定义一个路由url

route装饰器内部也是通过调用add_url_rule()方法实现的路由注册

def hello():
  return 'Welcome to Hello World !'
app.add_url_rule('/hello',view_func=hello)

访问:http://127.0.0.1:5000/hello

2.2 带参数的路由url

@app.route('/hello/<name>')
def hello(name):
    return 'Hello %s' % name

name为随意字符串,结果输出:

1832b220aa754cd18c504acc7686a560.png

除了界面验证,我们也可以用命令行工具ipython测试:

pip install ipython  #安装
ipython   #进入ipython
In [1]: import requests
In [2]: r = requests.get("http://192.168.1.4:5000/hello/zong")
In [3]: r.text
Out[3]: u'Hello zong'

参数是有类型的。默认是string

传递参数的语法是/<参数类型:参数名称>/,然后在视图函数中也要定义同名的参数


string:只接受字符串,没有任何“/或者”的文本

int:只接受整数

float:只接受浮点数,整数都不行哈

path:和string类似,但是接受斜杠

uuid:只有接受符合uuid的字符赤岸,一般用作表的主键

any:可以指定多种路径

示例:

rom flask import Flask,request
app = Flask(__name__)
@app.route('/')
def hello_world():
    return 'Hello World!'
@app.route('/list/')
def article_list():
    return 'article list!'
@app.route('/p1/<article_id1>')
def article_detail(article_id1):
    return "请求的文章是:%s" %article_id1
@app.route('/p2/<string:article_id2>')
def article_detail2(article_id2):
    return "请求的文章是:%s" %article_id2
@app.route('/p3/<int:article_id3>')
def article_detail3(article_id3):
    return "请求的文章是:%s" %article_id3
@app.route('/p4/<path:article_id4>')
def article_detail4(article_id4):
    return "请求的文章是:%s" %article_id4
# import uuid
# print(uuid.uuid4())
@app.route('/p5/<uuid:article_id5>') #数据的唯一性,长度较长,有损效率(一般在用户表中使用)6a9221f6-afea-424a-a324-8ceaa5bdfc98
def article_detail5(article_id5):
    return "请求的文章是:%s" %article_id5
@app.route('/p6/<any(blog,user):url_path>/<id>/')
def detail(url_path,id):
    if url_path == "blog":
        return "博客详情 %s" %id
    else:
        return "用户详情 %s" %id
#通过问号形式传递参数
@app.route('/d/')
def d():
    wd = request.args.get('wd') #获取浏览器传递参数
    return '通过查询字符串的方式传递的参数是,%s'%wd #请求http://127.0.0.1:8080/d/?wd=php
if __name__ == '__main__':
    app.run()

2.3 带url_for传参的路由url

对url再次包装处理。


url_for的第一个参数是视图函数的函数名对应的字符串(endpoint),后面的参数就是你传递给url;如果传递的参数在url中已经定义了,那么这个参数就会被当成path的值传递给url;如果这个参数没有在url中定义,那么将变成查询字符串的形式。

语法格式:

url_for('login')    # 返回/login
url_for('login', id='1')    # 将id作为URL参数,返回/login?id=1
url_for('hello', name='man')    # 适配hello函数的name参数,返回/hello/man
url_for('static', filename='style.css')    # 静态文件地址,返回/static/style.css

示例1

from flask import Flask,url_for,request
@app.route('/')
    return url_for('my_list',page=1,count=2) #这样的话就会在页面上构建出/post/list/1/?count=2的信息
@app.route('/post/list/<page>/')
def my_list():
    return 'my list'

示例2:

from flask import Flask,url_for,request
@app.route('/')
def hello_world():
    return url_for('login',next='/current') #页面返回/login/?next=%2Fcurrent登录前的信息
    # print(url_for('my_list',page=1,count=200))
    # return 'hello world'
@app.route('/login/')
def login():
    # next = request.args.get('next') #登录前的信息,在登陆之后仍旧保持
    return 'login'
@app.route('/list/<page>')
def my_list():
    return 'my list'
@app.route('/detail/<id>/')
def detail():
    return 'detail'
if __name__ == '__main__':
    app.run(debug=True)

2.4 不同http方法的路由url

当设置请求方式只能是POST时,GET就会报错。

@app.route('/hello/<name>',methods=["POST"])
def hello(name):
    return 'Hello %s' % name

测试:

In [1]: import requests
In [2]: r = requests.get("http://192.168.1.4:5000/hello/zong")
In [3]: r.text
Out[6]: u'<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">\n<title>405 Method Not Allowed</title>\n<h1>Method Not Allowed</h1>\n<p>The method is not allowed for the requested URL.</p>\n'
In [7]: r.status_code
Out[7]: 405
In [8]: r = requests.post("http://192.168.1.4:5000/hello/zong")
In [9]: r.text
Out[9]: u'Hello zong'
In [10]: r.status_code
Out[10]: 200

如何想两种http方法都支持。

from flask import request
@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        return 'This is a POST request'
    else:
        return 'This is a GET request'

参考:

相关文章
|
9天前
|
前端开发 JavaScript 安全
深入理解Python Web开发中的前后端分离与WebSocket实时通信技术
在现代Web开发中,前后端分离已成为主流架构,通过解耦前端(用户界面)与后端(服务逻辑),提升了开发效率和团队协作。前端使用Vue.js、React等框架与后端通过HTTP/HTTPS通信,而WebSocket则实现了低延迟的全双工实时通信。本文结合Python框架如Flask和Django,探讨了前后端分离与WebSocket的最佳实践,包括明确接口规范、安全性考虑、性能优化及错误处理等方面,助力构建高效、实时且安全的Web应用。
26 2
|
9天前
|
前端开发 Python
前后端分离的进化:Python Web项目中的WebSocket实时通信解决方案
在现代Web开发领域,前后端分离已成为一种主流架构模式,它促进了开发效率、提升了应用的可维护性和可扩展性。随着实时数据交互需求的日益增长,WebSocket作为一种在单个长连接上进行全双工通讯的协议,成为了实现前后端实时通信的理想选择。在Python Web项目中,结合Flask框架与Flask-SocketIO库,我们可以轻松实现WebSocket的实时通信功能。
23 2
|
10天前
|
JavaScript 前端开发 UED
WebSocket在Python Web开发中的革新应用:解锁实时通信的新可能
在快速发展的Web应用领域中,实时通信已成为许多现代应用不可或缺的功能。传统的HTTP请求/响应模式在处理实时数据时显得力不从心,而WebSocket技术的出现,为Python Web开发带来了革命性的变化,它允许服务器与客户端之间建立持久的连接,从而实现了数据的即时传输与交换。本文将通过问题解答的形式,深入探讨WebSocket在Python Web开发中的革新应用及其实现方法。
23 3
|
10天前
|
前端开发 开发者 Python
从零到一:Python Web框架中的模板引擎入门与进阶
在Web开发的广阔世界里,模板引擎是连接后端逻辑与前端展示的重要桥梁。对于Python Web开发者而言,掌握模板引擎的使用是从零到一构建动态网站或应用不可或缺的一步。本文将带你从基础入门到进阶应用,深入了解Python Web框架中的模板引擎。
14 3
|
9天前
|
数据库 开发者 Python
实战指南:用Python协程与异步函数优化高性能Web应用
在快速发展的Web开发领域,高性能与高效响应是衡量应用质量的重要标准。随着Python在Web开发中的广泛应用,如何利用Python的协程(Coroutine)与异步函数(Async Functions)特性来优化Web应用的性能,成为了许多开发者关注的焦点。本文将从实战角度出发,通过具体案例展示如何运用这些技术来提升Web应用的响应速度和吞吐量。
12 1
|
11天前
|
缓存 中间件 网络架构
Python Web开发实战:高效利用路由与中间件提升应用性能
在Python Web开发中,路由和中间件是构建高效、可扩展应用的核心组件。路由通过装饰器如`@app.route()`将HTTP请求映射到处理函数;中间件则在请求处理流程中插入自定义逻辑,如日志记录和验证。合理设计路由和中间件能显著提升应用性能和可维护性。本文以Flask为例,详细介绍如何优化路由、避免冲突、使用蓝图管理大型应用,并通过中间件实现缓存、请求验证及异常处理等功能,帮助你构建快速且健壮的Web应用。
12 1
|
5月前
|
5G Python
Windows11搭建Python环境(Anaconda安装与使用)
Windows11搭建Python环境(Anaconda安装与使用)
226 0
|
5月前
|
网络安全 Python Windows
windows上python3.8安装virtualenv遇到的一些问题
windows上python3.8安装virtualenv遇到的一些问题
|
Python Windows
六、【windows】更改 Python 的 pip install 默认安装依赖路径,及cmd下pip安装成功的包,pycharm却找不到
六、【windows】更改 Python 的 pip install 默认安装依赖路径,及cmd下pip安装成功的包,pycharm却找不到
2218 0
六、【windows】更改 Python 的 pip install 默认安装依赖路径,及cmd下pip安装成功的包,pycharm却找不到
|
编译器 Python Windows
简单详细 Windows Python的下载与安装
简单详细 Windows Python的下载与安装
简单详细 Windows Python的下载与安装
下一篇
无影云桌面