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