High-performance WebSockets for your Flask apps powered by uWSGI. Low-level uWSGI WebSocket APIaccess and flexible high-level abstractions for building complex WebSocketapplications with Flask. Supports several different concurrency modelsincluding Gevent. Inspired by Flask-Sockets.
Installation
Preferred method of installation is via pip:
Installing uWSGI
Of course you'll also need uWSGI (with SSL support, at minimum). It can also beinstalled with pip:
Conda build uwsgi -no-test # This will build the recipe but not run the tests (which break here). UWSGI embeds python and how it finds the libpython it needs is getting confused is my guess. Building the conda package with conda build will fix the bad linking step that is happening by using pip install to build.
If that fails or you need to enable the asyncio plugin, read on.
Not Mac, Ubuntu 18.04. Ok so I've just made the app container run as root, it starts using port 80 properly. However it does not seem to expose port 5555 I've set it to? A web server faces the outside world. It can serve files (HTML, images, CSS, etc) directly from the file system. However, it can’t talk directly to Django applications; it needs something that will run the application, feed it requests from web clients (such as browsers) and return responses. A Web Server Gateway Interface - WSGI - does this job. Would running flask with app.run still be a problem, if it is only accessed internally via server, with localhost, and not facing the web. I mean, if I call the flask app from other server, for example nodejs via localhost:5000, or php via curl. I am having trouble running my application on a new DigitalOcean droplet. The machine runs CentOS 6.5 My /etc/nginx/nginx.conf user nginx www-data; workerprocesses 1; errorlog /var/log/nginx/.
uWSGI on Mac OS X
On some versions of Mac OS X, OpenSSL headers are no longer included. If youuse Homebrew, install OpenSSL and ensure they are available:
This should ensure pip can install uWSGI:
If you plan to use the asyncio plugin, you'll need to ensure that it's enabledwhen uWSGI is compiled. You can use
UWSGI_PROFILE
to do this. With Homebrew Python 3.5 installed:uWSGI on Linux
If your Linux distribution includes uWSGI with specific plugins, that is manytimes your best bet. If that fails or you'd prefer to compile uWSGI yourself,you'll need to ensure that the requisite build tools, OpenSSL headers, etc areinstalled:
According to the uWSGI asyncio docs,
UWSGI_PROFILE
and greenlet.h
location should be specified.If you are installing uWSGI into a virtualenv, the process is:
Now,
greenlet.h
should be available at $VIRTUAL_ENV/include/site/python3.5
. To build with pip:Deployment
You can use uWSGI's built-in HTTP router to get up and running quickly:
..which is what
app.run
does after wrapping your Flask app:uWSGI supports several concurrency models, in particular it has nice supportfor Gevent. If you want to use Gevent, import
flask.ext.uwsgi_websocket.GeventWebSocket
and configure uWSGI to use thegevent loop engine:..or:
Note that you cannot use multiple threads with gevent loop engine.
To enable asyncio instead:
..or:
For production you'll probably want to run uWSGI behind Haproxy or Nginx,instead of using the built-int HTTP router. Explore the uWSGI documentation to learn moreabout the various concurrency and deployment options.
Development
It's possible to take advantage of Flask's interactive debugger by installingWerkzeug's
DebuggedApplication
middleware:..and running uWSGI with only a single worker:
If you use
app.run(debug=True)
or export FLASK_UWSGI_DEBUG
,Flask-uWSGI-Websocket will do this automatically for you.Examples
There are several examples available here.
API
WebSocket
Applies
WebSocketMiddleware
to your Flask App, allowing you to decorateroutes with the route
method, turning them into WebSocket handlers.Additionally monkey-patches
app.run
, to run your app directly in uWSGI.route(url)
run(debug, host, port, **kwargs)
**kwargs
are passed to uWSGI as command line arguments.WebSocketMiddleware
WebSocket Middleware which automatically performs WebSocket handshake andpasses
WebSocketClient
instances to your route.WebSocketClient
Exposes the uWSGI WebSocket API.
recv()
(alias WebSocket.receive()
)recv_nb()
send(msg)
send_binary(msg)
recv_nb()
send_from_sharedarea(id, pos)
send_binary_from_sharedarea(id, pos)
GeventWebSocket
Fancier WebSocket abstraction that takes advantage of Gevent loop engine.Requires uWSGI to be run with
--uwsgi
option.GeventWebSocketMiddleware
Automatically performs WebSocket handshake and passes a
GeventWebSocketClient
instance to your route.GeventWebSocketClient
WebSocket client abstraction with fully non-blocking methods.
receive()
send(msg)
close()
connected
AsyncioWebSocket
Fancier WebSocket abstraction that takes advantage of Asyncio loop engine.Requires uWSGI to be run with
--asyncio
and --greenlet
option.AsyncioWebSocketMiddleware
Automatically performs WebSocket handshake and passes a
AsyncioWebSocketClient
instance to your route.AsyncioWebSocketClient
WebSocket client abstraction with asyncio coroutines. Mac storage cleaner app.
Running Uwsgi App On Macbook
coroutine a_recv()
(alias receive()
, recv()
)coroutine a_send(msg)
(alias send()
)recv_nb()
(should be useless)send_nb()
(should be useless)close()
connected
Advanced Usage
Normally websocket routes happen outside of the normal request context. You canget a request context in your websocket handler by using
app.request_context
:uWSGI can be configured using several different methods. All configuration methods may be mixed and matched in the same invocation of uWSGI.
Note
Some of the configuration methods may require a specific plugin (ie. sqlite and ldap).
The configuration system is unified, so each command line option maps 1:1 with entries in the config files.
Example:
can be written as
Loading configuration files¶
uWSGI supports loading configuration files over several methods other than simple disk files:
Note
More esoteric file sources, such as the Emperor, embeddedconfiguration (in two flavors), dynamic library symbols and ELF sectionscould also be used.
Magic variables¶
uWSGI configuration files can include “magic” variables, prefixed with apercent sign. Currently the following magic variables (you can access them inPython via
uwsgi.magic_table
) are defined.%v | the vassals directory (pwd) |
%V | the uWSGI version |
%h | the hostname |
%o | the original config filename, as specified on the command line |
%O | same as %o but refer to the first non-template config file(version 1.9.18) |
%p | the absolute path of the configuration file |
%P | same as %p but refer to the first non-template config file(version 1.9.18) |
%s | the filename of the configuration file |
%S | same as %s but refer to the first non-template config file(version 1.9.18) |
%d | the absolute path of the directory containing the configuration file |
%D | same as %d but refer to the first non-template config file(version 1.9.18) |
%e | the extension of the configuration file |
%E | same as %e but refer to the first non-template config file(version 1.9.18) |
%n | the filename without extension |
%N | same as %n but refer to the first non-template config file(version 1.9.18) |
%c | the name of the directory containing the config file (version 1.3+) |
%C | same as %c but refer to the first non-template config file(version 1.9.18) |
%t | unix time (in seconds, gathered at instance startup) (version 1.9.20-dev+) |
%T | unix time (in microseconds, gathered at instance startup) (version 1.9.20-dev+) |
%x | the current section identifier, eg. config.ini:section (version 1.9-dev+) |
%X | same as %x but refer to the first non-template config file(version 1.9.18) |
%i | inode number of the file (version 2.0.1) |
%I | same as %i but refer to the first non-template config file |
%0.%9 | a specific component of the full path of the directory containing the config file (version 1.3+) |
%[ | ANSI escape “033” (useful for printing colors) |
%k | detected cpu cores (version 1.9.20-dev+) |
%u | uid of the user running the process (version 2.0) |
%U | username (if available, otherwise fallback to uid) of the user running the process (version 2.0) |
%g | gid of the user running the process (version 2.0) |
%G | group name (if available, otherwise fallback to gid) of the user running the process (version 2.0) |
%j | HEX representation of the djb33x hash of the full config path |
%J | same as %j but refer to the first non-template config file |
Note that most of these refer to the file they appear in, even if thatfile is included from another file.
An exception are most of the uppercase versions, which refer to thefirst non-template config file loaded. This means the first config filenot loaded through
--include
or --inherit
, but through forexample --ini
, --yaml
or --config
. These are intended to usewith the emperor, to refer to the actual vassal config file instead oftemplates included with --vassals-include
or --vassals-inherit
.For example, here’s
funnyapp.ini
.%n
will be replaced with the name of the config file, without extension, so the result in this case will bePlaceholders¶
Placeholders are custom magic variables defined during configuration time bysetting a new configuration variable of your own devising.
Placeholders can be assigned directly, or using the
set-placeholder
/ set-ph
option. These latter options can be useful to:- Make it more explicit that you’re setting placeholders instead ofregular options.
- Set options on the commandline, since unknown options like
--foo=bar
are rejected but--set-placeholderfoo=bar
is ok. - Set placeholders when strict mode is enabled.
Placeholders are accessible, like any uWSGI option, in your application codevia
uwsgi.opt
.This feature can be (ab)used to reduce the number of configuration filesrequired by your application.
Similarly, contents of environment variables and external text files canbe included using the $(ENV_VAR) and @(file_name) syntax. See alsoHow uWSGI parses config files.
Placeholders math (from uWSGI 1.9.20-dev)¶
You can apply math formulas to placeholders using this special syntax:
Running Uwsgi App On Mac Os
Remember to not miss spaces between operations.
Operations are executed in a pipeline (not in common math style):
‘total’ will be evaluated as 100:
(((foo + bar) + 3) * 2)
Incremental and decremental shortcuts are available
bar will be 30
If you do not specify an operation between two items, ‘string concatenation’ is assumed:
the first two items will be evaluated as ‘29’ (not 11 as no math operation has been specified)
The ‘@’ magic¶
We have already seen we can use the form @(filename) to include the contents of a file
the truth is that ‘@’ can read from all of the supported uwsgi schemes
Command line arguments¶
Example:
Environment variables¶
When passed as environment variables, options are capitalized and prefixed withUWSGI_, and dashes are substituted with underscores.
Note
Several values for the same configuration variable are not supported withthis method.
Running Uwsgi App On Mac Windows 10
Example:
INI files¶
.INI files are a de facto standard configuration format used by manyapplications. It consists of
[section]
s and key=value
pairs.An example uWSGI INI configuration:
Running Uwsgi App On Mac Download
By default, uWSGI uses the
[uwsgi]
section, but you can specify anothersection name while loading the INI file with the syntax filename:section
,that is:Alternatively, you can load another section from the same file byomitting the filename and specifying just the section name. Note thattechnically, this loads the named section from the last .ini file loadedinstead of the current one, so be careful when including other files.
- Whitespace is insignificant within lines.
- Lines starting with a semicolon (
;
) or a hash/octothorpe (#
) are ignored as comments. - Boolean values may be set without the value part. Simply
master
is thus equivalent tomaster=true
. This may not be compatible with other INI parsers such aspaste.deploy
. - For convenience, uWSGI recognizes bare
.ini
arguments specially, so the invocationuwsgimyconf.ini
is equal touwsgi--inimyconf.ini
.
XML files¶
The root node should be
<uwsgi>
and option values text nodes.An example:
You can also have multiple
<uwsgi>
stanzas in your file, marked withdifferent id
attributes. To choose the stanza to use, specify its id afterthe filename in the xml
option, using a colon as a separator. When usingthis id mode, the root node of the file may be anything you like. This willallow you to embed uwsgi
configuration nodes in other XML files.- Boolean values may be set without a text value.
- For convenience, uWSGI recognizes bare
.xml
arguments specially, so the invocationuwsgimyconf.xml
is equal touwsgi--xmlmyconf.xml
.
JSON files¶
The JSON file should represent an object with one key-value pair, the key being“uwsgi” and the value an object of configuration variables. Native JSONlists, booleans and numbers are supported.
An example:
How do i redownload photos app on mac. Again, a named section can be loaded using a colon after the filename.
And then load this using:
Note
The Jansson library is required during uWSGI build time to enable JSONsupport. By default the presence of the library will be auto-detected andJSON support will be automatically enabled, but you can force JSON supportto be enabled or disabled by editing your build configuration.
YAML files¶
The root element should be uwsgi. Boolean options may be set as true or 1.
An example:
Again, a named section can be loaded using a colon after the filename.
And then load this using:
SQLite configuration¶
LDAP configuration¶
LDAP is a flexible way to centralize configuration of large clusters of uWSGIservers. Configuring it is a complex topic. See Configuring uWSGI with LDAP for moreinformation.