sanic/examples/request_stream/server.py

78 lines
1.9 KiB
Python
Raw Normal View History

2017-05-05 12:09:32 +01:00
from sanic import Sanic
2017-05-07 10:33:47 +01:00
from sanic.views import CompositionView
from sanic.views import HTTPMethodView
from sanic.views import stream as stream_decorator
2017-05-05 12:09:32 +01:00
from sanic.blueprints import Blueprint
from sanic.response import stream, text
bp = Blueprint('blueprint_request_stream')
app = Sanic('request_stream')
2017-06-06 13:07:32 +01:00
@app.post('/cancel_stream', stream=True)
async def cancel_stream(request):
request.cancel_stream()
result = ''
while True:
body = await request.stream.get()
if body is None:
break
result += body.decode('utf-8')
return text(result)
class SimpleView(HTTPMethodView):
@stream_decorator
async def post(self, request):
result = ''
while True:
body = await request.stream.get()
if body is None:
break
result += body.decode('utf-8')
return text(result)
@app.post('/stream', stream=True)
2017-05-05 12:09:32 +01:00
async def handler(request):
async def streaming(response):
while True:
body = await request.stream.get()
if body is None:
break
body = body.decode('utf-8').replace('1', 'A')
response.write(body)
return stream(streaming)
@bp.put('/bp_stream', stream=True)
2017-05-05 12:09:32 +01:00
async def bp_handler(request):
result = ''
while True:
body = await request.stream.get()
if body is None:
break
result += body.decode('utf-8').replace('1', 'A')
return text(result)
2017-05-07 10:33:47 +01:00
async def post_handler(request):
result = ''
while True:
body = await request.stream.get()
if body is None:
break
result += body.decode('utf-8')
return text(result)
2017-05-05 12:09:32 +01:00
app.blueprint(bp)
app.add_route(SimpleView.as_view(), '/method_view')
2017-05-07 10:33:47 +01:00
view = CompositionView()
view.add(['POST'], post_handler, stream=True)
app.add_route(view, '/composition_view')
2017-05-05 12:09:32 +01:00
if __name__ == '__main__':
app.run(host='127.0.0.1', port=8000)