tiangolo / full-stack

Full stack, modern web application generator. Using Flask, PostgreSQL DB, Docker, Swagger, automatic HTTPS and more.
MIT License
523 stars 81 forks source link

How to add Websockets #24

Closed thewhipster closed 5 years ago

thewhipster commented 5 years ago

Hi Sebastian, thank you for all your work on full-stack! Curious if you have any pointers around adding flask-socketio to add websockets alongside the API on the backend? Hit numerous issues in trying this myself, particularly as i don't think it will work in dev with the werkzerg server (tried adding --no-reload and no debug as socketio has to run in the main thread. And i'm trying to stack deploy to staging to observe if it's just a case of not being able to run in dev but would work in other environments. Any guidance you could offer would be greatly appreciated as I'm looking to blend my Vue.js app to work both with the backend API but also leverage websockets instead of aweful chatty API polling. THANKS!

thewhipster commented 5 years ago

I suspect the answer to this comes along with a ASGI/FastAPI setup. Ready to tackle that down the road as i wrangle a SQLalchemy backend onto it.

tiangolo commented 5 years ago

Hi @thewhipster !

Yep, my suggestion goes around FastAPI.

There's a new section in the docs about using WebSockets: https://fastapi.tiangolo.com/tutorial/websockets/

There's an equivalent full-stack project generator to this one, everything is equivalent except for being FastAPI instead of Flask (with a lot of plug-ins): https://github.com/tiangolo/full-stack-fastapi-postgresql

If you need specifically SocketIO, you probably can try https://python-socketio.readthedocs.io, and add it to your FastAPI app mounting it as an "ASGI" application: https://python-socketio.readthedocs.io/en/latest/server.html#uvicorn-daphne-and-other-asgi-servers

Let's say you have a SocketIO app:

sio = socketio.AsyncServer(async_mode='asgi')
sio_app = socketio.ASGIApp(sio)

You should be able to mount it in FastAPI with:

app.mount("/socket.io", sio_app)
thewhipster commented 5 years ago

Thanks Sebastian. I moved to your new FastAPI/Postgress stack and starlette's websockets are much more elegant to quickly leverage. That is awesome! Thank you for all the sharing you do, and effort in documentation. Maybe less obvious is how valuable working of your design patterns with the stacks are. I hadn't tackled Vue.JS before and extending from your patterns made it a piece of cake to learn!

tiangolo commented 5 years ago

Thank you! That's great to hear! :smile: :blush:

I'm glad it's been helpful.