sanic/docs/sanic/response.md

103 lines
1.6 KiB
Markdown
Raw Normal View History

2017-03-12 14:17:41 +08:00
# Response
Use functions in `sanic.response` module to create responses.
## Plain Text
2017-03-12 14:17:41 +08:00
```python
from sanic import response
@app.route('/text')
def handle_request(request):
return response.text('Hello world!')
```
## HTML
2017-03-12 14:17:41 +08:00
```python
from sanic import response
@app.route('/html')
def handle_request(request):
return response.html('<p>Hello world!</p>')
```
## JSON
2017-03-12 14:17:41 +08:00
```python
from sanic import response
@app.route('/json')
def handle_request(request):
return response.json({'message': 'Hello world!'})
```
## File
2017-03-12 14:17:41 +08:00
```python
from sanic import response
@app.route('/file')
async def handle_request(request):
return await response.file('/srv/www/whatever.png')
```
## Streaming
2017-03-12 14:17:41 +08:00
```python
from sanic import response
@app.route("/streaming")
async def index(request):
async def streaming_fn(response):
response.write('foo')
response.write('bar')
2017-03-12 14:17:41 +08:00
return response.stream(streaming_fn, content_type='text/plain')
```
## Redirect
2017-03-12 14:17:41 +08:00
```python
from sanic import response
@app.route('/redirect')
def handle_request(request):
return response.redirect('/json')
```
## Raw
Response without encoding the body
2017-03-12 14:17:41 +08:00
```python
from sanic import response
@app.route('/raw')
def handle_request(request):
return response.raw('raw data')
```
## Modify headers or status
2017-03-12 14:17:41 +08:00
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
)
```