侯体宗的博客
  • 首页
  • Hyperf版
  • beego仿版
  • 人生(杂谈)
  • 技术
  • 关于我
  • 更多分类
    • 文件下载
    • 文字修仙
    • 中国象棋ai
    • 群聊
    • 九宫格抽奖
    • 拼图
    • 消消乐
    • 相册

Sanic框架路由用法实例分析

技术  /  管理员 发布于 7年前   197

本文实例讲述了Sanic框架路由用法。分享给大家供大家参考,具体如下:

前面一篇《Sanic框架安装与简单入门》简单介绍了Sanic框架的安装与基本用法,这里进一步学习Sanic框架的路由。

简介

Sanic是一个类似Flask的Python 3.5+ Web服务器,它的写入速度非常快。除了Flask之外,Sanic还支持异步请求处理程序。这意味着你可以使用Python 3.5中新的闪亮的异步/等待语法,使你的代码非阻塞和快速。

前言:Sanic最低支持Python 3.5,如果需要学习Sanic,请先下载版本不低于3.5的Python包

路由

路由允许用户为不同的URL端点指定不同的处理函数,我们取出上一篇《Sanic框架安装与简单入门》的路由为例:

from sanic.response import [email protected]("/")async def hello_sanic(request):  data = json({"code":0})  return data

当我们在浏览器输入http://localhost:5000/时,根据路由匹配到处理函数hello_sanic,最终返回JSON对象。Sanic处理函数必须使用语法async def来定义,因为它们是异步行数。

请求参数

Sanic处理函数带有一个支持请求的参数,即上面的request参数。如果需要制定一个参数,我们可以使用尖角括号将其括起来,如下所示:

from sanic.response import [email protected]("/hello/<name>")async def hello(request,name):  return json({"name":name})

此时我们再浏览器输入:http://localhost:5000/hello/laowang时,Sanic将会根据路由匹配处理函数,从而返回数据。此时,我们需要对参数进行指定类型,可以在路由中的参数后面加上:type,假设传入一个age参数,为int类型,路由可以这么写:/hello/<age:int>。代码如下:

from sanic.response import [email protected]("/hello/<age:int>")async def hello_age(request,age):  return json({"age":age})

此时就可以指定用户传入指定类型的参数了,如果类型不对,将报404错误。

请求类型

对于Sanic处理网络请求,也举了不少例子,可是这些都是GET请求,那我们该如何定义一个POST请求呢?与Flask相同,@app.route支持一个可选参数methods,methods可传入一个列表类型,如此,它将允许处理函数使用列表中的任何HTTP方法。

from sanic.response import [email protected]("/post/json_data",methods=["POST"])async def post_json(request):  """  POST请求 json数据  """  return json(request.json)@app.route("/post/form_data",methods=["POST"])async def post_form(request):  """  POST请求 form表单数据  """  return json(request.form)@app.route("/get/data",methods=["GET"])async def get_data(request):  """  GET请求  """  return json(request.args)

因为GET请求时默认的,所以,如果需要定义一个GET请求,那么methods参数可以无需传递。@app.route还支持另一个可选参数host,这限制了一条到所提供的主机或主机的路由。

from sanic.response import [email protected]("/hello/host",host="abc.com")async def hello_host(request):  return text("hello host")

在浏览器中访问此路由,如果主机头不匹配abc.com,那么将会报404错误。

路由的装饰器写法除了上面介绍的那种,还可以将其简写,如下所示:

from sanic.response import [email protected]("/short/get")async def short_get(request):  return json(request.args)@app.post("/short/post")async def short_post(request):  return json(request.json)

add_route方法

通常我们指定一个路由,都是通过@app.route装饰器,然而,这个装饰器实际上只是这个add_route方法的一个包装器,使用方法如下:

async def add_get_route(request):  """  添加GET请求  """  return json(request.args)async def add_get_type_route(request,age):  """  添加带指定类型的参数的GET请求  """  return json({"age":age})async def add_post_route(request):  """  添加POST请求  """  return json(request.json)app.add_route(add_get_route,"/add_get_route")app.add_route(add_get_type_route,"/add_get_type_route/<age:int>")app.add_route(add_post_route,"/add_post_route",methods=["POST"])

重定向

Sanic提供了一个url_for基于处理程序方法名称生成URL的方法。如果你想要避免将URL路径硬编码到你的应用程序当中,这很有用。例如:

from sanic.response import text,[email protected]("/url_info")async def url_info(request):  url = app.url_for('post_handler',name="laozhang",arg_one="one",arg_two="two")  print(url)  return redirect(url)@app.route("/post_handler/<name>")async def post_handler(request,name):  print(request.args)  return text("name:{}".format(name))

url_for使用注意:第一个参数为重定向URL的路由名称(默认为函数名称),并非URL名称。另外我们可以将一些请求参数指派到url_for方法中,上面例子重定向后的url将会是:

/post_handler/laozhang?arg_one=one&arg_two=two

也可以传递多值参数:

app.url_for("post_handler",favorite=["football","bastketball"])# /post_handler?favorite=football&favorite=bastketball

唯一URL

在Flask中,我们顶一个一个URL为/get,此时我们访问/get将可以访问成功,如果输入/get/将会返回404错误,这就是唯一URL。在Sanic中同样拥有此功能,我们可以通过配置strict_slashes参数来实现:

from sanic.response import [email protected]("/get",strict_slashes=True)async def get(request):  return text("it is ok!")

注意:strict_slashes默认值为None,如果不设置的话,访问/get或/get/都将可以访问成功,那么这就不是唯一URL了。在上面的例子中,我们将此值设置为True,此时我们输入/get/,将会返回一个404错误,这样就完成了一个唯一URL的实现。

如果我们需要将所有的URL都设置成为唯一URL,我们可以这样:

from sanic import Sanicfrom sanic.response import textapp = Sanic(strict_slashes=True)@app.route("/hello")async def hello(request):  return text("it is ok!")@app.route("/world")async def world(request):  return text("it is ok!")

/hello和world都变成了唯一URL。

如果我们只需要部分URL设置成唯一URL,我们可以在@app.route装饰器中传入strict_slashes,并设置为Flase,那么此URL将不是唯一URL。或者我们也可以定义一个蓝图,如下:

from sanic import Blueprintss_bp = Blueprint("aaa",strict_slashes=False)@ss_bp.route("/world")async def world(request):  return text("it is ok!")app.blueprint(ss_bp)

即使你在app中传递了参数strict_slashes=True,那么也没有用,所有通过此蓝图定义的URL都将不是唯一URL。

自定义路由名称

通常一个路由的名称为程序处理方法名称,即函数.__name__生成的,用于可以传递一个name参数到装饰器中来修改它的名称,如下:

from sanic.response import [email protected]("/get",name="get_info")async def get(request):  return text("it is ok!")

此时url_for中传递的将不是函数名称,而是name的值:

print(app.url_for("get_info"))   # /get

同样,也适用于蓝图:

from sanic import Blueprintss_bp = Blueprint("test_bp")@ss_bp.route("/get",name="get_info")async def get(request):  return text("it is ok!")app.blueprint(ss_bp)print(app.url_for("test_bp.get_info"))

静态文件的URL

我们需要构建一个特定的URL来访问我们需要的HTML,此时我们可以这样:

from sanic import Sanic,Blueprintapp = Sanic()app.static("/home","./static/home.html")

此时我们在访问/home就可以链接到我们指定的HTML中了,此方法同样适用于蓝图。

CompositionView

除了上面那几种定义路由的方法之外,Sanic还提供了CompositionView来动态添加路由:

from sanic.views import CompositionViewfrom sanic.response import textasync def post_handler(request):  print(request.json)  return text('it is ok!')view = CompositionView()view.add(["POST"],post_handler)app.add_route(view,"/post_info")

如此,就构造了一个POST请求的接口

处理器装饰器

由于Sanic处理程序是简单的Python函数,因此可以用与Flask类似的修饰符应用于它们。一个典型的用例就是当一些代码想要在处理程序的代码执行之前执行:

from sanic.response import textdef is_authorized():  return Truedef authorized(func):  async def wrapper(request,*args,**kwargs):    is_auth = is_authorized()    if is_auth:      response = await func(request,*args,**kwargs)      return response    else:      return text("it is not authorized")  return [email protected]("/get_user_info")@authorizedasync def get_user_info(request):  return text("get_user_info")

更多关于Python相关内容可查看本站专题:《Python入门与进阶经典教程》、《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》及《Python文件与目录操作技巧汇总》

希望本文所述对大家Python程序设计有所帮助。


  • 上一条:
    Sanic框架请求与响应实例分析
    下一条:
    Sanic框架安装与简单入门示例
  • 昵称:

    邮箱:

    0条评论 (评论内容有缓存机制,请悉知!)
    最新最热
    • 分类目录
    • 人生(杂谈)
    • 技术
    • linux
    • Java
    • php
    • 框架(架构)
    • 前端
    • ThinkPHP
    • 数据库
    • 微信(小程序)
    • Laravel
    • Redis
    • Docker
    • Go
    • swoole
    • Windows
    • Python
    • 苹果(mac/ios)
    • 相关文章
    • gmail发邮件报错:534 5.7.9 Application-specific password required...解决方案(0个评论)
    • 2024.07.09日OpenAI将终止对中国等国家和地区API服务(0个评论)
    • 2024/6/9最新免费公益节点SSR/V2ray/Shadowrocket/Clash节点分享|科学上网|免费梯子(1个评论)
    • 国外服务器实现api.openai.com反代nginx配置(0个评论)
    • 2024/4/28最新免费公益节点SSR/V2ray/Shadowrocket/Clash节点分享|科学上网|免费梯子(1个评论)
    • 近期文章
    • 在go中实现一个常用的先进先出的缓存淘汰算法示例代码(0个评论)
    • 在go+gin中使用"github.com/skip2/go-qrcode"实现url转二维码功能(0个评论)
    • 在go语言中使用api.geonames.org接口实现根据国际邮政编码获取地址信息功能(1个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf分页文件功能(0个评论)
    • gmail发邮件报错:534 5.7.9 Application-specific password required...解决方案(0个评论)
    • 欧盟关于强迫劳动的规定的官方举报渠道及官方举报网站(0个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf文件功能(0个评论)
    • Laravel从Accel获得5700万美元A轮融资(0个评论)
    • 在go + gin中gorm实现指定搜索/区间搜索分页列表功能接口实例(0个评论)
    • 在go语言中实现IP/CIDR的ip和netmask互转及IP段形式互转及ip是否存在IP/CIDR(0个评论)
    • 近期评论
    • 122 在

      学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..
    • 123 在

      Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..
    • 原梓番博客 在

      在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..
    • 博主 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..
    • 1111 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
    • 2016-10
    • 2016-11
    • 2017-07
    • 2017-08
    • 2017-09
    • 2018-01
    • 2018-07
    • 2018-08
    • 2018-09
    • 2018-12
    • 2019-01
    • 2019-02
    • 2019-03
    • 2019-04
    • 2019-05
    • 2019-06
    • 2019-07
    • 2019-08
    • 2019-09
    • 2019-10
    • 2019-11
    • 2019-12
    • 2020-01
    • 2020-03
    • 2020-04
    • 2020-05
    • 2020-06
    • 2020-07
    • 2020-08
    • 2020-09
    • 2020-10
    • 2020-11
    • 2021-04
    • 2021-05
    • 2021-06
    • 2021-07
    • 2021-08
    • 2021-09
    • 2021-10
    • 2021-12
    • 2022-01
    • 2022-02
    • 2022-03
    • 2022-04
    • 2022-05
    • 2022-06
    • 2022-07
    • 2022-08
    • 2022-09
    • 2022-10
    • 2022-11
    • 2022-12
    • 2023-01
    • 2023-02
    • 2023-03
    • 2023-04
    • 2023-05
    • 2023-06
    • 2023-07
    • 2023-08
    • 2023-09
    • 2023-10
    • 2023-12
    • 2024-02
    • 2024-04
    • 2024-05
    • 2024-06
    • 2025-02
    Top

    Copyright·© 2019 侯体宗版权所有· 粤ICP备20027696号 PHP交流群

    侯体宗的博客