资讯专栏INFORMATION COLUMN

sanic中文文档

琛h。 / 1596人阅读

摘要:入门指南路由路由允许用户为不同的端点指定处理程序函数。被访问服务器的基本,最终被路由器匹配到处理程序函数,测试,然后返回一个对象。请求参数将作为关键字参数传递给路线处理程序函数。例如所有有效的参数必须传递给以便构建一个。

入门指南

Install Sanic:python3 -m pip install sanic
example

from sanic import Sanic
from sanic.response import text
app = Sanic(__name__)
@app.route("/")
async def test(request):
    return text("Hello world!")
app.run(host="0.0.0.0", port=8000, debug=True)
路由

路由允许用户为不同的URL端点指定处理程序函数。

demo:

from sanic.response import json
@app.route("/")
async def test(request):
    return json({ "hello": "world" })

url http://server.url/ 被访问(服务器的基本url),最终"/"被路由器匹配到处理程序函数,测试,然后返回一个JSON对象。

请求参数 请求参数

要指定一个参数,可以用像这样的角引号包围它。请求参数将作为关键字参数传递给路线处理程序函数。
demo

from sanic.response import text
@app.route("/tag/")
async def tag_handler(request, tag):
    return text("Tag - {}".format(tag))

为参数指定类型,在参数名后面添加(:类型)。如果参数不匹配指定的类型,Sanic将抛出一个不存在的异常,导致一个404页面
demo:

from sanic.response import text
@app.route("/number/")
async def integer_handler(request, integer_arg):
    return text("Integer - {}".format(integer_arg))
@app.route("/number/")
async def number_handler(request, number_arg):
    return text("Number - {}".format(number_arg))
@app.route("/person/")
async def person_handler(request, name):
    return text("Person - {}".format(name))
@app.route("/folder/")
async def folder_handler(request, folder_id):
    return text("Folder - {}".format(folder_id))
请求类型
路由装饰器接受一个可选的参数,方法,它允许处理程序函数与列表中的任何HTTP方法一起工作。
demo_1
from sanic.response import text
@app.route("/post", methods=["POST"])
async def post_handler(request):
    return text("POST request - {}".format(request.json))
@app.route("/get", methods=["GET"])
async def get_handler(request):
    return text("GET request - {}".format(request.args))
demo_2
from sanic.response import text
@app.post("/post")
async def post_handler(request):
    return text("POST request - {}".format(request.json))
@app.get("/get")
async def get_handler(request):
    return text("GET request - {}".format(request.args))
增加路由
from sanic.response import text
# Define the handler functions
async def handler1(request):
    return text("OK")
async def handler2(request, name):
    return text("Folder - {}".format(name))
async def person_handler2(request, name):
    return text("Person - {}".format(name))
# Add each handler function as a route
app.add_route(handler1, "/test")
app.add_route(handler2, "/folder/")
app.add_route(person_handler2, "/person/", methods=["GET"])
url_for

Sanic提供了一个urlfor方法,根据处理程序方法名生成url。避免硬编码url路径到您的应用程序
demo

@app.route("/")
async def index(request):
    # generate a URL for the endpoint `post_handler`
    url = app.url_for("post_handler", post_id=5)
    # the URL is `/posts/5`, redirect to it
    return redirect(url)
@app.route("/posts/")
async def post_handler(request, post_id):
    return text("Post - {}".format(post_id))

Notice:

给url equest的关键字参数不是请求参数,它将包含在URL的查询字符串中。例如:

url = app.url_for("post_handler", post_id=5, arg_one="one", arg_two="two")
# /posts/5?arg_one=one&arg_two=two

所有有效的参数必须传递给url以便构建一个URL。如果没有提供一个参数,或者一个参数与指定的类型不匹配,就会抛出一个URLBuildError
可以将多值参数传递给url

url = app.url_for("post_handler", post_id=5, arg_one=["one", "two"])
# /posts/5?arg_one=one&arg_one=two
WebSocket routes(网络套接字路由)

websocket 可以通过装饰路由实现
demo:

@app.websocket("/feed")
async def feed(request, ws):
    while True:
        data = "hello!"
        print("Sending: " + data)
        await ws.send(data)
        data = await ws.recv()
        print("Received: " + data)
        
另外,添加 websocket 路由方法可以代替装饰器

async def feed(request, ws):
    pass
app.add_websocket_route(my_websocket_handler, "/feed")
响应( response ) text
from sanic import response
@app.route("/text")
def handle_request(request):
    return response.text("Hello world!")
HTML
from sanic import response
@app.route("/html")
def handle_request(request):
    return response.html("

Hello world!

")
JSON
from sanic import response
@app.route("/json")
def handle_request(request):
    return response.json({"message": "Hello world!"})
File
from sanic import response
@app.route("/file")
async def handle_request(request):
    return await response.file("/srv/www/whatever.png")
Streaming
from sanic import response
@app.route("/streaming")
async def index(request):
    async def streaming_fn(response):
        response.write("foo")
        response.write("bar")
    return response.stream(streaming_fn, content_type="text/plain")
File Streaming

对于大文件,文件和流的组合

from sanic import response
@app.route("/big_file.png")
async def handle_request(request):
    return await response.file_stream("/srv/www/whatever.png")
Redirect
from sanic import response
@app.route("/redirect")
def handle_request(request):
    return response.redirect("/json")
Raw

没有进行编码的响应

from sanic import response
@app.route(‘/raw ’)
def handle_request(request):
return response.raw(‘ raw data ’)
Modify headers or status

要修改头或状态代码,将标题或状态参数传递给这些函数

from sanic import response
@app.route(‘/json ’)
def handle_request(request):
return response.json(
{‘ message ’: ‘ Hello world!’},
headers={‘ X-Served-By ’: ‘ sanic ’},
status=200
)

更多的内容:Sanic 中文文档

静态文件

异常处理

中间件和监听

蓝图

配置

装饰器

请求数据

试图类

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/41000.html

相关文章

  • 基于python3.5+的web框架sanic中文入门教程

    摘要:简介是一款用写的,用法和类似,的特点是非常快官网速度比较框架实现基础每秒请求数平均时间安装环境创建文件,写入下面的内容运行是不是看起来和一样属性上传文件列表数据数据表单数据例子路由和差不多,一看就懂注册中间件异常处 简介 sanic是一款用python3.5+写的web framework,用法和flask类似,sanic的特点是非常快github官网:https://github.c...

    booster 评论0 收藏0
  • sanic异步框架之中文文档

    摘要:实例实例测试结果增加路由实例测试结果提供了一个方法,根据处理程序方法名生成。异常抛出异常要抛出异常,只需从异常模块中提出相应的异常。 typora-copy-images-to: ipic [TOC] 快速开始 在安装Sanic之前,让我们一起来看看Python在支持异步的过程中,都经历了哪些比较重大的更新。 首先是Python3.4版本引入了asyncio,这让Python有了支...

    elliott_hu 评论0 收藏0
  • 微信公号DIY:一小时搭建微信聊天机器人

    摘要:最近借用了女朋友的公号,感觉如果只是用来发文章,太浪费微信给提供的这些功能了。想了想,先从最简单的开始,做一个聊天机器人吧。是一款接口的,基于一系列规则和机器学习算法完成的聊天机器人。 最近借用了女朋友的公号,感觉如果只是用来发文章,太浪费微信给提供的这些功能了。想了想,先从最简单的开始,做一个聊天机器人吧。 使用Python实现聊天机器人的方案有多种:AIML、chatterBot以...

    source 评论0 收藏0
  • python 最快 web 框架 Sanci 快速入门

    摘要:详细信息可以看下这个问题先在说下我的部署方式使用部署配置文件启动方式总结试用了下,把之前的一个聊天机器人从改成了。预告下一篇将介绍如何使用一步一步创建一个聊天机器人。 简介 Sanic 是一个和类Flask 的基于Python3.5+的web框架,它编写的代码速度特别快。除了像Flask 以外,Sanic 还支持以异步请求的方式处理请求。这意味着你可以使用新的 async/await ...

    snifes 评论0 收藏0
  • 使用Sanic开发快速异步响应的Web程序

    摘要:在类似的基础上,支持异步请求处理,也就是说,你可以使用中全新而又亮眼的语法,使你的代码非阻塞且快速。就是基于实现的异步读写的数据库模块,同样有模块为因一波封装了,使得读写更加方便,它就是 Sanic是一个类似Flask、仅仅支持Python 3.5+ 版本的web 服务器,旨在运行速度更快。在类似Flask的基础上,Sanic支持异步请求处理,也就是说,你可以使用Python 3.5 ...

    clasnake 评论0 收藏0

发表评论

0条评论

琛h。

|高级讲师

TA的文章

阅读更多
最新活动
阅读需要支付1元查看
<