From d174917a0789c9deb8c4c4d0cb7209b9f9625d6e Mon Sep 17 00:00:00 2001 From: messense Date: Sun, 12 Mar 2017 14:17:41 +0800 Subject: [PATCH] Add response documentation --- docs/index.rst | 1 + docs/sanic/response.md | 99 ++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 100 insertions(+) create mode 100644 docs/sanic/response.md diff --git a/docs/index.rst b/docs/index.rst index 44d0299c..43cd0ba2 100644 --- a/docs/index.rst +++ b/docs/index.rst @@ -9,6 +9,7 @@ Guides sanic/getting_started sanic/routing sanic/request_data + sanic/response sanic/static_files sanic/exceptions sanic/middleware diff --git a/docs/sanic/response.md b/docs/sanic/response.md new file mode 100644 index 00000000..627fbc7e --- /dev/null +++ b/docs/sanic/response.md @@ -0,0 +1,99 @@ +# Response + +Use functions in `sanic.response` module to create responses. + +- `text` - Plain text response + +```python +from sanic import response + + +@app.route('/text') +def handle_request(request): + return response.text('Hello world!') +``` + +- `html` - HTML response + +```python +from sanic import response + + +@app.route('/html') +def handle_request(request): + return response.html('

Hello world!

') +``` + +- `json` - JSON response + + +```python +from sanic import response + + +@app.route('/json') +def handle_request(request): + return response.json({'message': 'Hello world!'}) +``` + +- `file` - File response + +```python +from sanic import response + + +@app.route('/file') +async def handle_request(request): + return await response.file('/srv/www/whatever.png') +``` + +- `stream` - Streaming response + +```python +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') +``` + +- `redirect` - Redirect response + +```python +from sanic import response + + +@app.route('/redirect') +def handle_request(request): + return response.redirect('/json') +``` + +- `raw` - Raw response, response without encoding the body + +```python +from sanic import response + + +@app.route('/raw') +def handle_request(request): + return response.raw('raw data') +``` + + +To modify headers or status code, pass the `headers` or `status` argument to those functions: + +```python +from sanic import response + + +@app.route('/json') +def handle_request(request): + return response.json( + {'message': 'Hello world!'}, + headers={'X-Served-By': 'sanic'}, + status=200 + ) +```