sanic/examples/request_stream/server.py

63 lines
1.5 KiB
Python
Raw Normal View History

2017-06-02 00:52:56 +01:00
from sanic import Sanic
from sanic.blueprints import Blueprint
from sanic.response import stream, text
from sanic.views import HTTPMethodView
from sanic.views import stream as stream_decorator
2017-06-02 00:52:56 +01:00
bp = Blueprint("bp_example")
app = Sanic("Example")
2017-06-02 00:52:56 +01:00
class SimpleView(HTTPMethodView):
2017-06-02 00:52:56 +01:00
@stream_decorator
async def post(self, request):
result = ""
2017-06-02 00:52:56 +01:00
while True:
body = await request.stream.get()
if body is None:
break
result += body.decode("utf-8")
2017-06-02 00:52:56 +01:00
return text(result)
@app.post("/stream", stream=True)
2017-06-02 00:52:56 +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")
await response.write(body)
2017-06-02 00:52:56 +01:00
return stream(streaming)
@bp.put("/bp_stream", stream=True)
2017-06-02 00:52:56 +01:00
async def bp_handler(request):
result = ""
2017-06-02 00:52:56 +01:00
while True:
body = await request.stream.get()
if body is None:
break
result += body.decode("utf-8").replace("1", "A")
2017-06-02 00:52:56 +01:00
return text(result)
async def post_handler(request):
result = ""
2017-06-02 00:52:56 +01:00
while True:
body = await request.stream.get()
if body is None:
break
result += body.decode("utf-8")
2017-06-02 00:52:56 +01:00
return text(result)
2017-06-02 00:52:56 +01:00
app.blueprint(bp)
app.add_route(SimpleView.as_view(), "/method_view")
2017-06-02 00:52:56 +01:00
if __name__ == "__main__":
app.run(host="0.0.0.0", port=8000)