iis服务器助手广告广告
返回顶部
首页 > 资讯 > 后端开发 > Python >sanic中文文档
  • 321
分享到

sanic中文文档

中文文档sanic 2023-01-31 08:01:11 321人浏览 八月长安

Python 官方文档:入门教程 => 点击学习

摘要

入门指南 Install Sanic:python3 -m pip install sanicexample from sanic import Sanic from sanic.response import text app = Sa

入门指南

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对象。

请求参数

请求参数

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

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

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

from sanic.response import text
@app.route('/number/<integer_arg:int>')
async def integer_handler(request, integer_arg):
    return text('Integer - {}'.format(integer_arg))
@app.route('/number/<number_arg:number>')
async def number_handler(request, number_arg):
    return text('Number - {}'.format(number_arg))
@app.route('/person/<name:[A-z]+>')
async def person_handler(request, name):
    return text('Person - {}'.format(name))
@app.route('/folder/<folder_id:[A-z0-9]{0,4}>')
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/<name>')
app.add_route(person_handler2, '/person/<name:[A-z]>', 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/<post_id>')
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('<p>Hello world!</p>')

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 中文文档

  • 静态文件
  • 异常处理
  • 中间件和监听
  • 蓝图
  • 配置
  • 装饰器
  • 请求数据
  • 试图类

--结束END--

本文标题: sanic中文文档

本文链接: http://www.lsjlt.com/news/192518.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • sanic中文文档
    入门指南 Install Sanic:python3 -m pip install sanicexample from sanic import Sanic from sanic.response import text app = Sa...
    99+
    2023-01-31
    中文 文档 sanic
  • sanic异步框架之中文文档
    typora-copy-images-to: ipic [TOC] 在安装Sanic之前,让我们一起来看看Python在支持异步的过程中,都经历了哪些比较重大的更新。 首先是Python3.4版本引入了asyncio,这让Pytho...
    99+
    2023-01-31
    中文 框架 文档
  • bcprov-jdk15on 简介、中文文档、中英对照文档 下载
    bcprov-jdk15on 文档 下载链接(含jar包、源码、pom) 组件名称中英对照-文档-下载链接中文-文档-下载链接bcprov-jdk15on-1.68.jarbcprov-jdk15on...
    99+
    2023-09-24
    java bcprov-jdk15on 中文文档 中英对照文档
  • Python3.2.3官方文档(中文版)
    所属网站分类: 资源下载 > python电子书 作者:熊猫烧香 链接:http://www.pythonheidong.com/blog/article/66/ 来源:python黑洞网,专注python资源,pytho...
    99+
    2023-01-31
    中文版 文档 官方
  • 【Python】官方文档中文版
    Python官方文档中文版应该是正在翻译中,现在官网貌似找不到入口,但是可以通过访问进入。 在文档url后面加上zh-cn即可。https://docs.python.org/zh-cn/,里面还有很多内容是英文的。     直接找找不到...
    99+
    2023-01-31
    中文版 文档 官方
  • Golang 函数文档中应包括哪些文档标签?
    go 函数文档必需的文档标签:描述标签(用法:提供函数目的和功能的描述)参数标签(用法:为函数参数提供名称和描述)返回值标签(用法:描述函数返回值的类型和含义)错误标签(用法:描述函数返...
    99+
    2024-05-01
    关键词 生成主题摘要 golang
  • python全系列官方中文文档
    https://docs.python.org/zh-cn/3.7/index.html PS:用的时候,修改url上对应的版本,点击左侧导航栏会跳转到对应的原版(英文版)文档 ...
    99+
    2023-01-31
    全系列 中文 文档
  • Numba 0.44 中文文档校对活动
    整体进度:https://github.com/apachecn/n... 贡献指南:https://github.com/apachecn/n... 项目仓库:https://github.com/apachecn/n... 请您勇...
    99+
    2023-01-31
    中文 文档 Numba
  • python文档
    #形式 # 角色 #抓取对象内可用的所有属性列表的简单方式 import random print(dir(random)) #['BPF', 'LOG4',...
    99+
    2023-01-31
    文档 python
  • python文档之查看帮助文档方法
    准备 使用time模块,使用time模块的localtime函数,使用range类 在已经分清模块,函数,类的情况下开始测试 方法一 在python命令行输入以下内容 help(time) ...
    99+
    2023-01-31
    帮助文档 文档 方法
  • word文档中怎么嵌入excel文件
    您可以按照以下步骤将Excel文件嵌入到Word文档中:1. 打开Word文档,将光标定位到您想要插入Excel文件的位置。2. 在...
    99+
    2023-09-29
    word excel
  • html5文档申明是什么文档模式?
    ...
    99+
    2024-04-02
  • Java实现向Word文档添加文档属性
    目录程序环境:方法1:手动引入。方法2: 如果您想通过 ​​Maven​​安装,则可以在 pom.xml 文件中添加以下代码导入 JAR 文件。将内置文档属性添加到 Word 文档完...
    99+
    2023-01-29
    java如何设置word文档属性 Java 将文档属性添加到 Word 文档 Java 设置Word文档属性
  • html5中怎么描述文档
    这篇文章主要讲解了“html5中怎么描述文档”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“html5中怎么描述文档”吧! htm...
    99+
    2024-04-02
  • Go语言中文文档及教程大全
    有志者,事竟成!如果你在学习Golang,那么本文《Go语言中文文档及教程大全》,就很适合你!文章讲解的知识点主要包括,若是你对本文感兴趣,或者是想搞懂其中某个知识点,就请你继续往下看吧~Go语言的...
    99+
    2024-04-04
  • word只读文档如何改成可编辑文档
    小编给大家分享一下word只读文档如何改成可编辑文档,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获,下面让我们一起去了解一下吧!方法:1、点击文件右击选择“属性”;在“常规”选项卡中查看是否被...
    99+
    2023-06-13
  • ASP Swagger 文档:API 文档的艺术与科学
    ASP Swagger 文档是一个用于生成 API 文档的框架,它基于 OpenAPI 规范(以前称为 Swagger 规范)构建。OpenAPI 规范是一种 JSON 格式的文档规范,用于描述 RESTful API 的结构和行为。A...
    99+
    2024-02-05
    ASP Swagger ASP.NET Core API 文档 RESTful API
  • github中如何上传项目和文本文档
    这篇文章主要介绍了github中如何上传项目和文本文档的相关知识,内容详细易懂,操作简单快捷,具有一定借鉴价值,相信大家阅读完这篇github中如何上传项目和文本文档文章都会有所收获,下面我们一起来看看吧。首先,GitHub是一个面向程序员...
    99+
    2023-07-05
  • Java 文档注释
    Java 文档注释 目录 Java 文档注释 javadoc 标签   文档注释 javadoc输出什么 实例   Java只是三种注释方式。前两种分别是// 和,第三种被称作说明注释,它以结束。 说明注释允许你在程序中嵌入关于程序的信息...
    99+
    2023-10-05
    前端
  • html文档转换
    HTML文档转换HTML(Hypertext Markup Language)是一种用于创建网页的标准标记语言。通过编写HTML代码,可以创建出漂亮的网页,并可以在网页中添加各种元素,如文本、图像、链接等等。然而,有时候我们需要将HTML文...
    99+
    2023-05-15
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作