Install Sanic:python3 -m pip install sanic
examplehtml
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端點指定處理程序函數。python
demo:web
from sanic.response import json @app.route("/") async def test(request): return json({ "hello": "world" })
url http://server.url/ 被訪問(服務器的基本url),最終'/'被路由器匹配處處理程序函數,測試,而後返回一個JSON對象。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:websocket
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'])
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:app
url = app.url_for('post_handler', post_id=5, arg_one='one', arg_two='two') # /posts/5?arg_one=one&arg_two=two
url = app.url_for('post_handler', post_id=5, arg_one=['one', 'two']) # /posts/5?arg_one=one&arg_one=two
websocket 能夠經過裝飾路由實現
demo:socket
@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')
from sanic import response @app.route('/text') def handle_request(request): return response.text('Hello world!')
from sanic import response @app.route('/html') def handle_request(request): return response.html('<p>Hello world!</p>')
from sanic import response @app.route('/json') def handle_request(request): return response.json({'message': 'Hello world!'})
from sanic import response @app.route('/file') async def handle_request(request): return await response.file('/srv/www/whatever.png')
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')
對於大文件,文件和流的組合async
from sanic import response @app.route('/big_file.png') async def handle_request(request): return await response.file_stream('/srv/www/whatever.png')
from sanic import response @app.route('/redirect') def handle_request(request): return response.redirect('/json')
沒有進行編碼的響應
from sanic import response @app.route(‘/raw ’) def handle_request(request): return response.raw(‘ raw data ’)
要修改頭或狀態代碼,將標題或狀態參數傳遞給這些函數
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 中文文檔