当前位置:   article > 正文

sanic中文文档

sanic 中文

入门指南

Install Sanic:python3 -m pip install sanic
example

  1. from sanic import Sanic
  2. from sanic.response import text
  3. app = Sanic(__name__)
  4. @app.route("/")
  5. async def test(request):
  6. return text('Hello world!')
  7. app.run(host="0.0.0.0", port=8000, debug=True)

路由

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

demo:

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

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

请求参数

请求参数

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

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

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

  1. from sanic.response import text
  2. @app.route('/number/<integer_arg:int>')
  3. async def integer_handler(request, integer_arg):
  4. return text('Integer - {}'.format(integer_arg))
  5. @app.route('/number/<number_arg:number>')
  6. async def number_handler(request, number_arg):
  7. return text('Number - {}'.format(number_arg))
  8. @app.route('/person/<name:[A-z]+>')
  9. async def person_handler(request, name):
  10. return text('Person - {}'.format(name))
  11. @app.route('/folder/<folder_id:[A-z0-9]{0,4}>')
  12. async def folder_handler(request, folder_id):
  13. return text('Folder - {}'.format(folder_id))

请求类型

  1. 路由装饰器接受一个可选的参数,方法,它允许处理程序函数与列表中的任何HTTP方法一起工作。
  2. demo_1
  3. from sanic.response import text
  4. @app.route('/post', methods=['POST'])
  5. async def post_handler(request):
  6. return text('POST request - {}'.format(request.json))
  7. @app.route('/get', methods=['GET'])
  8. async def get_handler(request):
  9. return text('GET request - {}'.format(request.args))
  10. demo_2
  11. from sanic.response import text
  12. @app.post('/post')
  13. async def post_handler(request):
  14. return text('POST request - {}'.format(request.json))
  15. @app.get('/get')
  16. async def get_handler(request):
  17. return text('GET request - {}'.format(request.args))

增加路由

  1. from sanic.response import text
  2. # Define the handler functions
  3. async def handler1(request):
  4. return text('OK')
  5. async def handler2(request, name):
  6. return text('Folder - {}'.format(name))
  7. async def person_handler2(request, name):
  8. return text('Person - {}'.format(name))
  9. # Add each handler function as a route
  10. app.add_route(handler1, '/test')
  11. app.add_route(handler2, '/folder/<name>')
  12. app.add_route(person_handler2, '/person/<name:[A-z]>', methods=['GET'])

url_for

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

  1. @app.route('/')
  2. async def index(request):
  3. # generate a URL for the endpoint `post_handler`
  4. url = app.url_for('post_handler', post_id=5)
  5. # the URL is `/posts/5`, redirect to it
  6. return redirect(url)
  7. @app.route('/posts/<post_id>')
  8. async def post_handler(request, post_id):
  9. return text('Post - {}'.format(post_id))

Notice:

  • 给url equest的关键字参数不是请求参数,它将包含在URL的查询字符串中。例如:
  1. url = app.url_for('post_handler', post_id=5, arg_one='one', arg_two='two')
  2. # /posts/5?arg_one=one&arg_two=two
  • 所有有效的参数必须传递给url以便构建一个URL。如果没有提供一个参数,或者一个参数与指定的类型不匹配,就会抛出一个URLBuildError
    可以将多值参数传递给url
  1. url = app.url_for('post_handler', post_id=5, arg_one=['one', 'two'])
  2. # /posts/5?arg_one=one&arg_one=two

WebSocket routes(网络套接字路由)

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

  1. @app.websocket('/feed')
  2. async def feed(request, ws):
  3. while True:
  4. data = 'hello!'
  5. print('Sending: ' + data)
  6. await ws.send(data)
  7. data = await ws.recv()
  8. print('Received: ' + data)
  9. 另外,添加 websocket 路由方法可以代替装饰器
  10. async def feed(request, ws):
  11. pass
  12. app.add_websocket_route(my_websocket_handler, '/feed')

响应( response )

text

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

HTML

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

JSON

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

File

  1. from sanic import response
  2. @app.route('/file')
  3. async def handle_request(request):
  4. return await response.file('/srv/www/whatever.png')
Streaming
  1. from sanic import response
  2. @app.route("/streaming")
  3. async def index(request):
  4. async def streaming_fn(response):
  5. response.write('foo')
  6. response.write('bar')
  7. return response.stream(streaming_fn, content_type='text/plain')

File Streaming

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

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

Redirect

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

Raw

没有进行编码的响应

  1. from sanic import response
  2. @app.route(‘/raw ’)
  3. def handle_request(request):
  4. return response.raw(‘ raw data ’)

Modify headers or status

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

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

更多的内容:Sanic 中文文档

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小丑西瓜9/article/detail/136823
推荐阅读
相关标签
  

闽ICP备14008679号