赞
踩
入门指南
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 对象。
Request parameters (请求参数)
要指定一个参数,可以用像这样的角引号包围它。请求参数将作为关键字参数传递给路线处理程序函数。
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 request types(请求类型)
路由装饰器接受一个可选的参数,方法,它允许处理程序函数与列表中的任何 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))
add_route method(增加路由)
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))
注意:
给 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
)
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。