sanic入门

说在前面的话

1、有Flask的基础学习该模块会很容易上手

2、该web框架基于python的asyncio异步模块,需要对该模块提前了解

一、快速开始

1、创建一个最简单的web应用main.py

from sanic import Sanic # 提前自行下载该模块
from sanic.response import jsonapp = Sanic()@app.route("/")
async def test(request):return json({"hello": "world"})if __name__ == "__main__":app.run(host="0.0.0.0", port=8000)

2、运行

python3 main.py

3、查看浏览器

浏览器打开 0.0.0.0:8000,就成看到json格式的hello world

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-pQoAFl5N-1584971894667)(/Users/bobwang/Library/Application Support/typora-user-images/image-20200323093726836.png)]

二、路由

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

from sanic.response import json@app.route("/")
async def test(request):return json({ "hello": "world" })'''当访问URL http://server.url/(服务器的基本URL)时,路由器将最后一个/与处理函数test匹配,然后返回JSON对象。'''

Sanic处理程序函数必须使用async def语法定义,因为它们是异步函数。

1、路由带参数

Sanic带有支持请求参数的基本路由器。

要指定参数,请在其周围加上如下的引号:。请求参数将作为关键字参数传递给路由处理程序函数。

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

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-xWjD98gN-1584971894673)(/Users/bobwang/Library/Application Support/typora-user-images/截屏2020-03-23上午11.43.34.png)]

如果没有匹配上,则会返回如下信息

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-LGw6toQK-1584971894676)(/Users/bobwang/Library/Application Support/typora-user-images/截屏2020-03-23上午11.44.28.png)]

支持的类型

    • string

      “Bob”“Python 3”

    • int

      102030-10(No floats work here)

    • number

      11.510-10

    • alpha

      “Bob”“Python”(If it contains a symbol or a non alphanumeric character it will fail)

    • path

      “hello”“hello.text”“hello world”

    • uuid

      123a123a-a12a-1a1a-a1a1-1a12a1a12345 (UUIDv4 Support)

  • 正则表达式

如果未设置任何类型,则应为字符串。赋予函数的参数将始终是字符串,与类型无关。

@app.route('/string/<string_arg:string>')
async def string_handler(request, string_arg):return text('String - {}'.format(string_arg))@app.route('/int/<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('/alpha/<alpha_arg:alpha>')
async def number_handler(request, alpha_arg):return text('Alpha - {}'.format(alpha_arg))@app.route('/path/<path_arg:path>')
async def number_handler(request, path_arg):return text('Path - {}'.format(path_arg))@app.route('/uuid/<uuid_arg:uuid>')
async def number_handler(request, uuid_arg):return text('Uuid - {}'.format(uuid_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))

2、HTTP请求类型

默认情况下,URL上定义的路由仅可用于对该URL的GET请求。但是,@ app.route装饰器接受可选参数methods,该参数允许处理程序函数与列表中的任何HTTP方法一起使用。

@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))

Shorthand速记方法

@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))

限制host参数,非该host的其他ip将不能访问

@app.route('/get', methods=['GET'], host='example.com')
async def get_handler(request):return text('GET request - {}'.format(request.args))

3、统一添加路由

# 先定义处理函数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'])

4、重定向url_for

from sanic.response import redirect@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 itreturn redirect(url)@app.route('/posts/<post_id>')
async def post_handler(request, post_id):return text('Post - {}'.format(post_id))

运行结果,会先302重定向

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-ZW0R5cWC-1584971894680)(/Users/bobwang/Library/Application Support/typora-user-images/image-20200323121217055.png)]

另外:

还可以在url_for中携带不是请求参数的关键字参数,并将其包含在URL的查询字符串中

url = app.url_for('post_handler', post_id=5, arg_one='one', arg_two='two')
# 等价于
/posts/5?arg_one=one&arg_two=two# 参数获取
arg = request.args.get('arg_one')

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-4Xck1Pa0-1584971894689)(/Users/bobwang/Library/Application Support/typora-user-images/image-20200323121625820.png)]

5、websocket

from sanic import Sanic
from sanic.response import fileapp = Sanic(__name__)@app.route('/')
async def index(request):return await file('websocket.html')@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)if __name__ == '__main__':app.run(host="0.0.0.0", port=8000, debug=True)

html

<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>WebSocket demo</title>
</head>
<body>
<script>var ws = new WebSocket('ws://' + document.domain + ':' + location.port + '/feed'),messages = document.createElement('ul');ws.onmessage = function (event) {var messages = document.getElementsByTagName('ul')[0],message = document.createElement('li'),content = document.createTextNode('Received: ' + event.data);message.appendChild(content);messages.appendChild(message);};document.body.appendChild(messages);window.setInterval(function() {data = 'bye!'ws.send(data);var messages = document.getElementsByTagName('ul')[0],message = document.createElement('li'),content = document.createTextNode('Sent: ' + data);message.appendChild(content);messages.appendChild(message);}, 1000);</script>
</body>
</html>

三、响应

当端点接收到HTTP请求时,将向路由功能传递一个 Request对象。

1、纯文本Plain Text

from sanic import response@app.route('/text')
def handle_request(request):return response.text('Hello world!')

2、HTML

from sanic import response@app.route('/html')
def handle_request(request):return response.html('<p>Hello world!</p>')

3、JSON

from sanic import response@app.route('/json')
def handle_request(request):return response.json({'message': 'Hello world!'})

4、文件File

from sanic import response@app.route('/file')
async def handle_request(request):return await response.file('/srv/www/whatever.png')

5、流,Streaming

from sanic import response@app.route("/streaming")
async def index(request):async def streaming_fn(response):await response.write('foo')await response.write('bar')return response.stream(streaming_fn, content_type='text/plain')

See Streaming for more information.

6、文件流File Streaming

For large files, a combination of File and Streaming above

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

7、重定向Redirect

from sanic import response@app.route('/redirect')
def handle_request(request):return response.redirect('/json')

8、原始数据Raw

Response without encoding the body

from sanic import response@app.route('/raw')
def handle_request(request):return response.raw(b'raw data')

9、空 Empty

For responding with an empty message as defined by RFC 2616

from sanic import response@app.route('/empty')
async def handle_request(request):return response.empty()

四、并发支持

asyncio参看https://www.cnblogs.com/shenh/p/9090586.html

from sanic import Sanic
from sanic.response import jsonimport asyncio
import aiohttpapp = Sanic(__name__)sem = None@app.listener('before_server_start')
def init(sanic, loop):global semconcurrency_per_worker = 4sem = asyncio.Semaphore(concurrency_per_worker, loop=loop)  # 限制并发数,不超过linux默认的1024和windows默认的509async def bounded_fetch(session, url):"""Use session object to perform 'get' request on url"""async with sem, session.get(url) as response:return await response.json()@app.route("/")
async def test(request):"""Download and serve example JSON"""url = "https://api.github.com/repos/channelcat/sanic"async with aiohttp.ClientSession() as session:response = await bounded_fetch(session, url)return json(response)if __name__ == '__main__':app.run(host="0.0.0.0", port=8000, workers=2)

sanic入门(一)相关推荐

  1. 它号称 Python 中性能最高的异步 Web 框架:超详细 Sanic 入门指南!

    △点击上方"Python猫"关注 ,回复"2"加入交流群 作者:古明地盆 来源:https://www.cnblogs.com/traditional/p/14 ...

  2. Linux之nginx入门

    nginx入门 详见可参考:https://www.cnblogs.com/tiger666/p/10239307.html?tdsourcetag=s_pctim_aiomsg 1. 常用的WEB框 ...

  3. python web 框架例子_最快的 Python Web 框架入门

    原标题:最快的 Python Web 框架入门 来源:Python开发 ID:PythonPush 速度比较 框架 实现基础 每秒请求数 平均时间 Sanic Python 3.5 + uvloop ...

  4. fastapi jinja2_(入门篇)Python框架之FastAPI——一个比Flask和Tornado更高性能的API 框架

    用官方的话来说,FastAPI 是一种现代,快速(高性能)的 Web 框架,基于标准Python 类型提示使用 Python 3.6+ 构建 API FastAPI 站在巨人的肩膀上? 很大程度上来说 ...

  5. “脚踢各大Python Web框架”,Sanic真有这能耐么?

    在Github上,Sanic第一句介绍语就是: "Sanic is a Flask-like Python 3.5+ web server that's written to go fast ...

  6. python入门经典书籍知乎_知乎问题回答 - 《Python100天从新手到大师》 - 开源书籍(oscbook.com)...

    知乎问题回答 Python学习完基础语法知识后,如何进一步提高? 如果你已经完成了Python基础语法的学习,想要知道接下来如何提高,那么你得先问问自己你要用Python来做什么?目前学习Python ...

  7. python数据处理框架_python 最快 web 框架 Sanci 快速入门

    简介 Sanic 是一个和类Flask 的基于Python3.5+的web框架,它编写的代码速度特别快. 除了像Flask 以外,Sanic 还支持以异步请求的方式处理请求.这意味着你可以使用新的 a ...

  8. python比flask更好的框架_(入门篇)Python框架之FastAPI——一个比Flask和Tornado更高性能的API 框架...

    用官方的话来说,FastAPI 是一种现代,快速(高性能)的 Web 框架,基于标准Python 类型提示使用 Python 3.6+ 构建 API FastAPI 站在巨人的肩膀上? 很大程度上来说 ...

  9. 第一章:Django入门篇

    文章目录 第一章:Django入门篇 一. web应用 二.HTTP协议(重要) 请求协议 响应协议 响应状态码 URL简介 三.django简介 3.2 目录介绍 3.3 启动项目 3.4 简单示例 ...

最新文章

  1. java中友元类_友元类成员的依赖关系|循环依赖
  2. Spring Cloud Stream如何消费自己生产的消息?
  3. 三点弯曲弹性模量怎么计算公式_?怎么计算弯管的尺寸和弯管的张力
  4. 【机器学习基础】说模型过拟合的时候,说的是什么?
  5. 远程接入-天翼5系统让ERP穿越时空!
  6. es文件浏览器怎么用_es文件浏览器电视版下载-es文件浏览器电视tv版下载v4.2.3.4 安卓最新版...
  7. npm如何设置淘宝镜像
  8. 每行代码都有注释释的java面向对象代码_每行代码都有注释释的java面向对象代码...
  9. HDOJ:1533-Going Home(最小费用流)
  10. WPS删除多余空白页
  11. PyQt(Python+Qt)学习随笔:clicked和clicked(bool)信号连接同名函数出现的问题
  12. Java实现腾讯云发送短信
  13. 植物大战僵尸 php,植物大战僵尸修改器使用方法 php 函数使用方法与函数定义方法...
  14. APS Interview - Digital Circuit and Digital Logic I
  15. PMIC驱动之—PMIC硬件相关知识
  16. 第一章:基本概念(博弈论、纳什均衡、维克瑞拍卖、POA、赞助搜索拍卖)
  17. 数据交换技术(*):电路交换,报文交换,分组交换的概念,特点和优缺点以及存储转发技术概念
  18. 华为硬件逻辑岗笔试题(一)
  19. iOS在UIButton中换行
  20. 使用Postman调试API遇到“400 Bad Request”问题

热门文章

  1. 如何用ARIMA模型做预测?
  2. CDSN文章下载代码
  3. win10安装.NET Framework 3.5的方法
  4. java web孤傲苍狼,JavaWeb学习笔记
  5. 尚学堂python线上培训多少钱
  6. Markdown编辑器模式使用LaTex编辑数学公式入门
  7. 基于交替迭代法的交直流混合系统潮流计算matlab程序iEEE9节点系统算例
  8. 旅游地如何搭好影视剧“顺风车”
  9. 2021香港排名前十的现货伦敦金正规平台排行榜
  10. 数模美赛如何找数据 | 2023年美赛数学建模必备数据库