from sanic import Sanic
from sanic import response
from signal import signal, SIGINT
import asyncio
import uvloop
app = Sanic(__name__)
@app.route("/")
async def test(request):
return response.json({"answer": "42"})
asyncio.set_event_loop(uvloop.new_event_loop())
server = app.create_server(host="0.0.0.0", port=8000)
loop = asyncio.get_event_loop()
task = asyncio.ensure_future(server)
signal(SIGINT, lambda s, f: loop.stop())
try:
loop.run_forever()
except:
loop.stop()
in this example,I want to set workers=4. just like "app.run(host="0.0.0.0", port=5000, workers=4)",but app.create_server() not support workers
If I understand this correctly, you want to have an option to add signal handlers? Unless you have some specific logic that needs to be added (though I don't see what could that be) you should just rely on run.
The example you're trying to achieve is already handled for you within sanic's run. https://github.com/channelcat/sanic/blob/master/sanic/server.py#L590-L597
Any reason you can't just use app.run?
It literally does all of that for you.
app.run support async? i don't know hao to do it.
Im not entirely sure what you're asking, but yes,app.run() supports async route handlers, and async middleware.
Read the README file for a small example.
Read the documentation for more examples:
http://sanic.readthedocs.io/en/latest/
This is a very minimal example:
from sanic import Sanic
from sanic.response import text
app = Sanic()
@app.route("/")
async def index(request):
return text("hello world")
if __name__ == "__main__":
app.run(host="0.0.0.0", port=8000)
If you want to use the workers feature, you'll have to use app.run. To add other async tasks to the same loop, you can use app.add_task before calling app.run:
async def notify_server_started_after_five_seconds():
await asyncio.sleep(5)
print('Server successfully started!')
app.add_task(notify_server_started_after_five_seconds())
Or use the listeners to start your task at the appropriate time. There's more info here: http://sanic.readthedocs.io/en/latest/sanic/middleware.html?highlight=add_task.
I'm going to close this, since running multiple workers isn't supported with app.create_server, and it's a known limitation. However feel free to reopen and/or reploy if you would like to discuss it further.
Most helpful comment
If you want to use the workers feature, you'll have to use
app.run. To add other async tasks to the same loop, you can useapp.add_taskbefore callingapp.run:Or use the listeners to start your task at the appropriate time. There's more info here: http://sanic.readthedocs.io/en/latest/sanic/middleware.html?highlight=add_task.
I'm going to close this, since running multiple workers isn't supported with
app.create_server, and it's a known limitation. However feel free to reopen and/or reploy if you would like to discuss it further.