PYTHON-ENGINEIO(1)

✨ NAME ✨

python-engineio(1) β€” python-engineio Documentation πŸ’–

okay bestie, this project implements Python based Engine.IO client and server that can run standalone or integrated with a variety of Python web frameworks and applications. it's lowkey versatile fr fr 🫢


🌈 GETTING STARTED 🌈

πŸ¦‹ What is Engine.IO? πŸ¦‹

okay so Engine.IO is a lightweight transport protocol that enables real-time bidirectional event-based communication between clients (typically, though not always, web browsers) and a server. the official implementations of the client and server components are written in JavaScript. this package provides Python implementations of both, each with standard and asyncio variants πŸ’…

the Engine.IO protocol is extremely simple, bestie. once a connection between a client and a server is established, either side can send "messages" to the other side. event handlers provided by the applications on both ends are invoked when a message is received, or when a connection is established or dropped. periodt. ✨


🌸 Client Examples 🌸

the example that follows shows a simple Python client:

import engineio

eio = engineio.Client()

@eio.on('connect')
def on_connect():
    print('connection established')

@eio.on('message')
def on_message(data):
    print('message received with ', data)
    eio.send({'response': 'my response'})

@eio.on('disconnect')
def on_disconnect():
    print('disconnected from server')

eio.connect('http://localhost:5000')
eio.wait()

and here is a similar client written using the official Engine.IO Javascript client:

<script src="/path/to/engine.io.js"></script>
<script>
    var socket = eio('http://localhost:5000');
    socket.on('open', function() { console.log('connection established'); });
    socket.on('message', function(data) {
        console.log('message received with ' + data);
        socket.send({response: 'my response'});
    });
    socket.on('close', function() { console.log('disconnected from server'); });
</script>

πŸ’… Client Features πŸ’…

  • can connect to other Engine.IO compliant servers besides the one in this package πŸ’–
  • compatible with Python 3.6+ ⭐
  • two versions of the client: one for standard Python and another for asyncio πŸ¦‹
  • uses an event-based architecture implemented with decorators that hides the details of the protocol ✨
  • implements HTTP long-polling and WebSocket transports πŸ”₯

πŸŽ€ Server Examples πŸŽ€

the following application is a basic example that uses the Eventlet asynchronous server:

import engineio
import eventlet

eio = engineio.Server()
app = engineio.WSGIApp(eio, static_files={
    '/': {'content_type': 'text/html', 'filename': 'index.html'}
})

@eio.on('connect')
def connect(sid, environ):
    print("connect ", sid)

@eio.on('message')
def message(sid, data):
    print("message ", data)
    eio.send(sid, 'reply')

@eio.on('disconnect')
def disconnect(sid):
    print('disconnect ', sid)

if __name__ == '__main__':
    eventlet.wsgi.server(eventlet.listen(('', 5000)), app)

below is a similar application, coded for asyncio and the Uvicorn web server:

import engineio
import uvicorn

eio = engineio.AsyncServer()
app = engineio.ASGIApp(eio, static_files={
    '/': {'content_type': 'text/html', 'filename': 'index.html'}
})

@eio.on('connect')
def connect(sid, environ):
    print("connect ", sid)

@eio.on('message')
async def message(sid, data):
    print("message ", data)
    await eio.send(sid, 'reply')

@eio.on('disconnect')
def disconnect(sid):
    print('disconnect ', sid)

if __name__ == '__main__':
    uvicorn.run('127.0.0.1', 5000)

πŸ‘‘ Server Features πŸ‘‘

πŸ’– THE ENGINE.IO CLIENT πŸ’–

okay so this package ships with two Engine.IO clients, bestie, and you get to pick your fighter:

  • The engineio.Client() class creates a client compatible with the standard Python library.
  • The engineio.AsyncClient() class creates a client compatible with the asyncio package.

The methods in the two clients are the same, the only glow-up difference being that in the asyncio client most methods are implemented as coroutines. that's it. that's the whole plot. ✨

πŸŽ€ Installation πŸŽ€

To install the standard Python client along with its dependencies, use the following command:

pip install "python-engineio[client]"

If instead you plan on using the asyncio client, then use this:

pip install "python-engineio[asyncio_client]"

pick your lane, queen πŸ‘‘

πŸ¦‹ Creating a Client Instance πŸ¦‹

To instantiate an Engine.IO client, simply create an instance of the appropriate client class:

import engineio

# standard Python
eio = engineio.Client()

# asyncio
eio = engineio.AsyncClient()

literally that easy. no cap. 🫢

🌸 Defining Event Handlers 🌸

To responds to events triggered by the connection or the server, event Handler functions must be defined using the on decorator:

@eio.on('connect')
def on_connect():
    print('I'm connected!')

@eio.on('message')
def on_message(data):
    print('I received a message!')

@eio.on('disconnect')
def on_disconnect(reason):
    print('I'm disconnected! reason:', reason)

For the asyncio server, event handlers can be regular functions as above, or can also be coroutines:

@eio.on('message')
async def on_message(data):
    print('I received a message!')

The argument given to the on decorator is the event name. The events that are supported are connect, message and disconnect. those three. the holy trinity. πŸ‘‘

The data argument passed to the 'message' event handler contains application-specific data provided by the server with the event.

The disconnect handler is invoked for client initiated disconnects, server initiated disconnects, or accidental disconnects, for example due to networking failures. The argument passed to this handler provides the disconnect reason. Example:

@eio.on('disconnect')
def on_disconnect(reason):
    if reason == eio.reason.CLIENT_DISCONNECT:
        print('client disconnection')
    elif reason == eio.reason.SERVER_DISCONNECT:
        print('the server kicked me out')
    else:
        print(f'disconnect reason: {reason}')

see how you can tell WHO ended things? communication skills, we love to see it πŸ’…

πŸ’œ Connecting to a Server πŸ’œ

The connection to a server is established by calling the connect() method:

eio.connect('http://localhost:5000')

In the case of the asyncio client, the method is a coroutine:

await eio.connect('http://localhost:5000')

Upon connection, the server assigns the client a unique session identifier. The applicaction can find this identifier in the sid attribute:

print('my sid is', eio.sid)

you got an id, you got a whole identity now. main character energy fr fr 🌟

πŸ“ Sending Messages πŸ“

The client can send a message to the server using the send() method:

eio.send({'foo': 'bar'})

Or in the case of asyncio, as a coroutine:

await eio.send({'foo': 'bar'})

The single argument provided to the method is the data that is passed on to the server. The data can be of type str, bytes, dict or list. The data included inside dictionaries and lists is also constrained to these types.

The send() method can be invoked inside an event handler as a response to a server event, or in any other part of the application, including in background tasks. send from anywhere, no rules, we're feral like that 😌

✨ Disconnecting from the Server ✨

At any time the client can request to be disconnected from the server by invoking the disconnect() method:

eio.disconnect()

For the asyncio client this is a coroutine:

await eio.disconnect()

it's giving "I'm not mad I'm just done". graceful exit, iconic behaviour πŸŽ€

🌈 Managing Background Tasks 🌈

When a client connection to the server is established, a few background tasks will be spawned to keep the connection alive and handle incoming events. The application running on the main thread is free to do any work, as this is not going to prevent the functioning of the Engine.IO client.

If the application does not have anything to do in the main thread and just wants to wait until the connection ends, it can call the wait() method:

eio.wait()

Or in the asyncio version:

await eio.wait()

For the convenience of the application, a helper function is provided to start a custom background task:

def my_background_task(my_argument)
    # do some background work here!
    pass

eio.start_background_task(my_background_task, 123)

The arguments passed to this method are the background function and any positional or keyword arguments to invoke the function with.

Here is the asyncio version:

async def my_background_task(my_argument)
    # do some background work here!
    pass

eio.start_background_task(my_background_task, 123)
Note that this function is not a coroutine, since it does not wait for the background function to end, but the background function is.

The sleep() method is a second convenience function that is provided for the benefit of applications working with background tasks of their own:

eio.sleep(2)

Or for asyncio:

await eio.sleep(2)

The single argument passed to the method is the number of seconds to sleep for. go take a nap bestie, you earned it 😴

πŸ”₯ Debugging and Troubleshooting πŸ”₯

To help you debug issues, the client can be configured to output logs to the terminal:

import engineio

# standard Python
eio = engineio.Client(logger=True)

# asyncio
eio = engineio.AsyncClient(logger=True)

The logger argument controls logging behavior:

  • True: Enables log output to stderr at the INFO level.
  • False: Enables log output to stderr at the ERROR level. This is the default.
  • A logging.Logger instance: Uses the provided logger without additional configuration.

Logging can help identify the cause of connection problems, unexpected disconnections and other issues. when in doubt, turn the logs on and let them yap πŸ’€


πŸ‘‘ THE ENGINE.IO SERVER πŸ‘‘

This package contains two Engine.IO servers:

  • The engineio.Server() class creates a server compatible with the standard Python library.
  • The engineio.AsyncServer() class creates a server compatible with the asyncio package.

The methods in the two servers are the same, with the only difference that in the asyncio server most methods are implemented as coroutines. twin behaviour, different fonts πŸ’…

πŸŽ€ Installation πŸŽ€

To install the Python Engine.IO server use the following command:

pip install "python-engineio"

In addition to the server, you will need to select an asynchronous framework or server to use along with it. The list of supported packages is covered in the Deployment Strategies section. (that's coming, don't worry, we're getting there 🌸)

πŸ¦‹ Creating a Server Instance πŸ¦‹

An Engine.IO server is an instance of class engineio.Server. This instance can be transformed into a standard WSGI application by wrapping it with the engineio.WSGIApp class:

import engineio

# create a Engine.IO server
eio = engineio.Server()

# wrap with a WSGI application
app = engineio.WSGIApp(eio)

For asyncio based servers, the engineio.AsyncServer class provides the same functionality, but in a coroutine friendly format. If desired, The engineio.ASGIApp class can transform the server into a standard ASGI application:

# create a Engine.IO server
eio = engineio.AsyncServer()

# wrap with ASGI application
app = engineio.ASGIApp(eio)

These two wrappers can also act as middlewares, forwarding any traffic that is not intended to the Engine.IO server to another application. This allows Engine.IO servers to integrate easily into existing WSGI or ASGI applications:

from wsgi import app  # a Flask, Django, etc. application
app = engineio.WSGIApp(eio, app)

not me sliding my Engine.IO server into your existing app like it was always there 😌✨

πŸ’œ Serving Static Files πŸ’œ

The Engine.IO server can be configured to serve static files to clients. This is particularly useful to deliver HTML, CSS and JavaScript files to clients when this package is used without a companion web framework.

Static files are configured with a Python dictionary in which each key/value pair is a static file mapping rule. In its simplest form, this dictionary has one or more static file URLs as keys, and the corresponding files in the server as values:

static_files = {
    '/': 'latency.html',
    '/static/engine.io.js': 'static/engine.io.js',
    '/static/style.css': 'static/style.css',
}

With this example configuration, when the server receives a request for / (the root URL) it will return the contents of the file latency.html in the current directory, and will assign a content type based on the file extension, in this case text/html.

Files with the .html, .css, .js, .json, .jpg, .png, .gif and .txt file extensions are automatically recognized and assigned the correct content type. For files with other file extensions or with no file extension, the application/octet-stream content type is used as a default.

If desired, an explicit content type for a static file can be given as follows:

static_files = {
    '/': {'filename': 'latency.html', 'content_type': 'text/plain'},
}

It is also possible to configure an entire directory in a single rule, so that all the files in it are served as static files:

static_files = {
    '/static': './public',
}

In this example any files with URLs starting with /static will be served directly from the public folder in the current directory, so for example, the URL /static/index.html will return local file ./public/index.html and the URL /static/css/styles.css will return local file ./public/css/styles.css.

If a URL that ends in a / is requested, then a default filename of index.html is appended to it. In the previous example, a request for the /static/ URL would return local file ./public/index.html. The default filename to serve for slash-ending URLs can be set in the static files dictionary with an empty key:

static_files = {
    '/static': './public',
    '': 'image.gif',
}

With this configuration, a request for /static/ would return local file ./public/image.gif. A non-standard content type can also be specified if needed:

static_files = {
    '/static': './public',
    '': {'filename': 'image.gif', 'content_type': 'text/plain'},
}

The static file configuration dictionary is given as the static_files argument to the engineio.WSGIApp or engineio.ASGIApp classes:

# for standard WSGI applications
eio = engineio.Server()
app = engineio.WSGIApp(eio, static_files=static_files)

# for asyncio-based ASGI applications
eio = engineio.AsyncServer()
app = engineio.ASGIApp(eio, static_files=static_files)

The routing precedence in these two classes is as follows:

  • First up, the path gets checked against the Engine.IO path.
  • Next, the path gets checked against the static file configuration, if there even is one.
  • If the path matched neither the Engine.IO path nor any static file, control gets handed off to the secondary application if one's configured β€” and if it isn't, you're getting a 404 error. πŸ’€
Note: static file serving is for development use only, bestie. It literally lacks important features like caching because of that. Do not use it in a production environment. 🚫

✨ Defining Event Handlers ✨

So to respond to events that the connection or the client fires off, you define event Handler functions with the on decorator:

@eio.on('connect')
def on_connect(sid):
    print('A client connected!')

@eio.on('message')
def on_message(sid, data):
    print('I received a message!')

@eio.on('disconnect')
def on_disconnect(sid, reason):
    print('Client disconnected! reason:', reason)

For the asyncio server, event handlers can be regular functions like the ones above, or they can be coroutines too:

@eio.on('message')
async def on_message(sid, data):
    print('I received a message!')

The argument you hand to the on decorator is the event name. The events that are supported are connect, message and disconnect. That's the whole menu, no secret extras. πŸŽ€

The sid argument that gets passed into all the event handlers is a connection identifier for the client. Every single event from one client will use the same sid value, so you can always tell who's who. 🫢

The connect handler is the spot where the server does authentication. Whatever value this handler returns decides if the connection is accepted or rejected. When the handler doesn't return anything (which is the same thing as returning None), or when it returns True, the connection is accepted. If the handler returns False, or any JSON compatible data type (string, integer, list or dictionary), the connection is rejected. And a rejected connection triggers a response with a 401 status code. periodt.

The data argument passed to the 'message' event handler holds application-specific data that the client sent along with the event. πŸ“¦

The disconnect handler gets invoked for client initiated disconnects, server initiated disconnects, or accidental disconnects β€” like when networking just fails on you. 😭 The second argument passed to this handler gives you the disconnect reason. Example:

@eio.on('disconnect')
def on_disconnect(sid, reason):
    if reason == eio.reason.CLIENT_DISCONNECT:
        print('the client went away')
    elif reason == eio.reason.SERVER_DISCONNECT:
        print('the client was kicked out')
    else:
        print(f'disconnect reason: {reason}')

πŸ’Œ Sending Messages πŸ’Œ

The server can send a message to any client using the send() method:

eio.send(sid, {'foo': 'bar'})

Or, in the case of asyncio, as a coroutine:

await eio.send(sid, {'foo': 'bar'})

The first argument you give the method is the connection identifier for the recipient client. The second argument is the data that's passed on to the server. That data can be of type str, bytes, dict or list. And the data tucked inside dictionaries and lists is also constrained to those same types β€” no sneaking in anything else. πŸ‘‘

You can invoke the send() method inside an event handler as a response to a client event, or literally anywhere else in the application, background tasks included. 🌈


🌸 User Sessions 🌸

The server can keep application-specific info in a user session dedicated to each connected client. Apps can use the user session to write any details about the user that need to be preserved for the whole life of the connection β€” usernames, user ids, that kind of thing.

The save_session() and get_session() methods are what you use to store and retrieve info in the user session:

@eio.on('connect')
def on_connect(sid, environ):
    username = authenticate_user(environ)
    eio.save_session(sid, {'username': username})

@eio.on('message')
def on_message(sid, data):
    session = eio.get_session(sid)
    print('message from ', session['username'])

For the asyncio server, these methods are coroutines:

@eio.on('connect')
async def on_connect(sid, environ):
    username = authenticate_user(environ)
    await eio.save_session(sid, {'username': username})

@eio.on('message')
async def on_message(sid, data):
    session = await eio.get_session(sid)
    print('message from ', session['username'])

The session can also be manipulated with the session() context manager:

@eio.on('connect')
def on_connect(sid, environ):
    username = authenticate_user(environ)
    with eio.session(sid) as session:
        session['username'] = username

@eio.on('message')
def on_message(sid, data):
    with eio.session(sid) as session:
        print('message from ', session['username'])

For the asyncio server, you use an asynchronous context manager instead:

@eio.on('connect')
def on_connect(sid, environ):
    username = authenticate_user(environ)
    async with eio.session(sid) as session:
        session['username'] = username

@eio.on('message')
def on_message(sid, data):
    async with eio.session(sid) as session:
        print('message from ', session['username'])
Note: the contents of the user session get destroyed when the client disconnects. Gone. Poof. πŸ’€

πŸšͺ Disconnecting a Client πŸšͺ

At any time the server can disconnect a client from the server by invoking the disconnect() method and passing the sid value assigned to that client:

eio.disconnect(sid)

For asyncio this one is a coroutine:

await eio.disconnect(sid)

🧚 Managing Background Tasks 🧚

For the convenience of the application, there's a helper function provided to start a custom background task:

def my_background_task(my_argument)
    # do some background work here!
    pass

eio.start_background_task(my_background_task, 123)

The arguments you pass to this method are the background function, plus any positional or keyword arguments to invoke that function with.

Here's the asyncio version:

async def my_background_task(my_argument)
    # do some background work here!
    pass

eio.start_background_task(my_background_task, 123)
Note: this function is not a coroutine, since it doesn't wait for the background function to finish β€” but the background function itself is. 🫠

The sleep() method is a second convenience function, provided for the benefit of applications working with background tasks of their own:

eio.sleep(2)

Or for asyncio:

await eio.sleep(2)

The single argument passed to the method is the number of seconds to sleep for. 😴


πŸ” Debugging and Troubleshooting πŸ”

To help you debug issues, the server can be configured to output logs to the terminal:

import engineio

# standard Python
eio = engineio.Server(logger=True)

# asyncio
eio = engineio.AsyncServer(logger=True)

The logger argument controls the logging behavior:

  • True β€” enables log output to stderr at the INFO level.
  • False β€” enables log output to stderr at the ERROR level. This is the default.
  • A logging.Logger instance β€” uses the logger you provided, with no additional configuration.

Logging can help you figure out the cause of connection problems, 400 responses, bad performance, and other issues. it's giving detective energy πŸ”Ž


πŸš€ Deployment Strategies πŸš€

The following sections describe a variety of deployment strategies for Engine.IO servers.


☁️ Uvicorn, Daphne, and other ASGI servers ☁️

The engineio.ASGIApp class is an ASGI compatible application that can forward Engine.IO traffic to an engineio.AsyncServer instance:

eio = engineio.AsyncServer(async_mode='asgi')
app = engineio.ASGIApp(eio)

If you want, the engineio.ASGIApp class can forward any traffic that isn't Engine.IO to another ASGI application β€” which makes it possible to deploy a standard ASGI web app and the Engine.IO server as a bundle. 🎁

eio = engineio.AsyncServer(async_mode='asgi')
app = engineio.ASGIApp(eio, other_app)

The ASGIApp instance is a fully compliant ASGI instance that can be deployed with an ASGI compatible web server. slay ✨


🌊 Aiohttp 🌊

aiohttp (http://aiohttp.readthedocs.io/) provides a framework with support for HTTP and WebSocket, based on asyncio.

Instances of class engineio.AsyncServer will automatically use aiohttp for asynchronous operations if the library is installed. To request its use explicitly, you can give the async_mode option in the constructor:

eio = engineio.AsyncServer(async_mode='aiohttp')

A server configured for aiohttp must be attached to an existing application:

app = web.Application()
eio.attach(app)

The aiohttp application can define regular routes that will coexist with the Engine.IO server. A typical pattern is to add routes that serve a client application and any associated static files. πŸ“

The aiohttp application is then executed in the usual manner:

if __name__ == '__main__':
    web.run_app(app)

πŸŒͺ️ Tornado πŸŒͺ️

Tornado (http://www.tornadoweb.org//) is a web framework with support for HTTP and WebSocket. Only Tornado version 5 and newer are supported, thanks to its tight integration with asyncio.

Instances of class engineio.AsyncServer will automatically use tornado for asynchronous operations if the library is installed. To request its use explicitly, you can give the async_mode option in the constructor:

eio = engineio.AsyncServer(async_mode='tornado')

A server configured for tornado must include a request handler for Engine.IO:

app = tornado.web.Application(
    [
        (r"/engine.io/", engineio.get_tornado_handler(eio)),
    ],
    # ... other application options
)

The tornado application can define other routes that will coexist with the Engine.IO server. A typical pattern is to add routes that serve a client application and any associated static files. 🌈

The tornado application is then executed in the usual manner:

app.listen(port)
tornado.ioloop.IOLoop.current().start()

πŸ“ Sanic πŸ“

Note: due to some backward incompatible changes introduced in recent versions of Sanic, it is currently recommended that a Sanic application is deployed with the ASGI integration instead. πŸ‘€

Sanic (http://sanic.readthedocs.io/) is a very efficient asynchronous web server for Python.

Instances of class engineio.AsyncServer will automatically use Sanic for asynchronous operations if the framework is installed. To request its use explicitly, you can give the async_mode option in the constructor:

eio = engineio.AsyncServer(async_mode='sanic')

A server configured for Sanic must be attached to an existing application:

app = Sanic()
eio.attach(app)

bestie your Sanic app can totally define its own regular routes and they'll just coexist with the Engine.IO server, no drama πŸ’… the classic move is adding routes that serve up your client application plus whatever static files it needs.

Then you run that Sanic app the normal way, like:

if __name__ == '__main__':
    app.run()

okay so ⚠️ it has been reported that the CORS support from the Sanic extension sanic-cors (that's https://github.com/ashleysommer/sanic-cors) is incompatible with this package's own support for this protocol 😭 so if you want to shut off this package's CORS handling and let Sanic be the main character and take full control, you initialize the server like this:

eio = engineio.AsyncServer(async_mode='sanic', cors_allowed_origins=[])

and on the Sanic side you ALSO need to turn on the CORS_SUPPORTS_CREDENTIALS setting, on top of whatever other config you're running:

app.config['CORS_SUPPORTS_CREDENTIALS'] = True

🌿 Eventlet 🌿

Eventlet (http://eventlet.net/) is a high performance concurrent networking library for Python 2 and 3 that runs on coroutines, so you get to write your code in the exact same style you'd use with the blocking standard library functions ✨ an Engine.IO server deployed with eventlet gets access to both the long-polling and WebSocket transports, no cap.

Instances of the class engineio.Server will automatically reach for eventlet for asynchronous operations if the library is installed. And if you wanna be explicit about it, you can pass the async_mode option in the constructor:

eio = engineio.Server(async_mode='eventlet')

a server configured for eventlet gets deployed as a regular WSGI application using the provided engineio.WSGIApp:

app = engineio.WSGIApp(eio)
import eventlet
eventlet.wsgi.server(eventlet.listen(('', 8000)), app)

🌿 Eventlet with Gunicorn πŸ¦„

another way to do it instead of running the eventlet WSGI server like above is to use gunicorn (gunicorn.org), a fully featured pure Python web server 🫢 here's the command to launch the application under gunicorn:

$ gunicorn -k eventlet -w 1 module:app
⚠️ because of limitations in its load balancing algorithm, gunicorn can only be used with one worker process, so the -w 1 option is required. and no, that's not a vibe killer β€” a single eventlet worker can handle a large number of concurrent clients πŸ’ͺ

another gunicorn limitation: the WebSocket transport is not available with it, because that transport requires extensions to the WSGI standard 😭

πŸ“ Note: Eventlet provides a monkey_patch() function that swaps out all the blocking functions in the standard library for equivalent asynchronous versions. python-engineio does not require monkey patching, but other libraries β€” database drivers, for example β€” very likely do.

🌊 Gevent 🌊

Gevent (http://gevent.org) is another coroutine-based asynchronous framework, super similar to eventlet. an Engine.IO server deployed with gevent gets the long-polling and websocket transports 🌈

Instances of the class engineio.Server will automatically use gevent for asynchronous operations if the library is installed and eventlet is not installed. To request gevent explicitly, pass the async_mode option in the constructor:

eio = engineio.Server(async_mode='gevent')

a server configured for gevent is deployed as a regular WSGI application using the provided engineio.WSGIApp:

from gevent import pywsgi
app = engineio.WSGIApp(eio)
pywsgi.WSGIServer(('', 8000), app).serve_forever()

🌊 Gevent with Gunicorn πŸ¦„

instead of running the gevent WSGI server as above, you can use gunicorn (gunicorn.org), that same fully featured pure Python web server. the launch command:

$ gunicorn -k gevent -w 1 module:app

same situation as with eventlet: thanks to limitations in its load balancing algorithm, gunicorn can only be used with one worker process, so -w 1 is required. and same as before β€” a single gevent worker can handle a large number of concurrent clients πŸ’–

πŸ“ Note: Gevent provides a monkey_patch() function that replaces all the blocking functions in the standard library with equivalent asynchronous versions. python-engineio does not require monkey patching, but other libraries β€” database drivers, say β€” are likely to require it.

🧡 uWSGI 🧡

when you use the uWSGI server together with gevent, the Engine.IO server can take advantage of uWSGI's native WebSocket support πŸ”₯

Instances of the class engineio.Server will automatically use this option for asynchronous operations if both gevent and uWSGI are installed and eventlet is not installed. to request this asynchronous mode explicitly, give the async_mode option in the constructor:

# gevent with uWSGI
eio = engineio.Server(async_mode='gevent_uwsgi')

okay a complete explanation of uWSGI configuration and usage is honestly beyond the scope of this documentation πŸ™ˆ the uWSGI server is a fairly complex package with a huge and comprehensive set of options. and heads up: it must be compiled with WebSocket and SSL support for the WebSocket transport to be available. but as a lil intro, this command starts a uWSGI server for the latency.py example on port 5000:

$ uwsgi --http :5000 --gevent 1000 --http-websockets --master --wsgi-file latency.py --callable app

🧢 Standard Threads 🧢

not comparable to eventlet and gevent on performance, obviously, but the Engine.IO server can also be configured to work with multi-threaded web servers that use standard Python threads. this setup is ideal for development servers like Werkzeug (http://werkzeug.pocoo.org) πŸŽ€

Instances of the class engineio.Server will automatically use the threading mode if neither eventlet nor gevent are installed. to request threading mode explicitly, pass the async_mode option in the constructor:

eio = engineio.Server(async_mode='threading')

a server configured for threading gets deployed as a regular web application, using any WSGI compliant multi-threaded server. this example deploys an Engine.IO application combined with a Flask web application, using Flask's development web server based on Werkzeug:

eio = engineio.Server(async_mode='threading')
app = Flask(__name__)
app.wsgi_app = engineio.WSGIApp(eio, app.wsgi_app)

# ... Engine.IO and Flask handler functions ...

if __name__ == '__main__':
    app.run()

and here's how you start an Engine.IO application using Gunicorn's threaded worker class:

$ gunicorn -w 1 --threads 100 module:app

with that config the server can handle up to 100 concurrent clients ✨

when you're using standard threads, WebSocket is supported through the simple-websocket package (https://github.com/miguelgrinberg/simple-websocket), which must be installed separately. this package provides a multi-threaded WebSocket server that's compatible with Werkzeug and Gunicorn's threaded worker. other multi-threaded web servers are not supported and will not enable the WebSocket transport πŸ’€

πŸ“ˆ Scalability Notes πŸ“ˆ

Engine.IO is a stateful protocol, which is exactly what makes horizontal scaling harder 😭 to deploy a cluster of Engine.IO processes spread over one or more servers, these conditions must be met:

  • each Engine.IO server process must be able to handle multiple requests concurrently. this is required because long-polling clients send two requests in parallel. worker processes that can only handle one request at a time are not supported.
  • the load balancer must be configured to always forward requests from a client to the same process. load balancers call this sticky sessions, or session affinity.

πŸ›‘οΈ Cross-Origin Controls πŸ›‘οΈ

for security reasons, this server enforces a same-origin policy by default. in practical terms that means:

  • if an incoming HTTP or WebSocket request includes the Origin header, that header must match the scheme and host of the connection URL. on a mismatch, a 400 status code response is returned and the connection is rejected.
  • no restrictions are imposed on incoming requests that do not include the Origin header.

if you need to, the cors_allowed_origins option can be used to allow other origins. you can set this argument to a string to allow a single origin, or to a list to allow multiple origins. there's also a special value of '*' that tells the server to allow all origins β€” but please do that with care, because it could make your server vulnerable to Cross-Site Request Forgery (CSRF) attacks 😬


πŸ“š API REFERENCE πŸ“š

  • Index
  • Module Index
  • Search Page

πŸ‘‘ Author πŸ‘‘

Miguel Grinberg

2018, Miguel Grinberg


okay bestie that's the whole page, we ate and left no crumbs πŸ“πŸ’… this was python-engineio(1), dated Dec 29, 2025 β€” go build something iconic with it, mwah 🫢✨

πŸ“¦ where this page comes from