Skip to content
Myr

rewrite deployment docs

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by David Lord · committed by David Lord · parent 9398630 · Browse files · 15 files+802 added−824 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

15 files+802 added−824 removed

  • other:+802 added−824 removed

15 files+802 added−824 removed

added:docs/deploying/apache-httpd.rst+66 added
1Apache httpd2============34`Apache httpd`_ is a fast, production level HTTP server. When serving5your application with one of the WSGI servers listed in :doc:`index`, it6is often good or necessary to put a dedicated HTTP server in front of7it. This "reverse proxy" can handle incoming requests, TLS, and other8security and performance concerns better than the WSGI server.910httpd can be installed using your system package manager, or a pre-built11executable for Windows. Installing and running httpd itself is outside12the scope of this doc. This page outlines the basics of configuring13httpd to proxy your application. Be sure to read its documentation to14understand what features are available.1516.. _Apache httpd: https://httpd.apache.org/171819Domain Name20-----------2122Acquiring and configuring a domain name is outside the scope of this23doc. In general, you will buy a domain name from a registrar, pay for24server space with a hosting provider, and then point your registrar25at the hosting provider's name servers.2627To simulate this, you can also edit your ``hosts`` file, located at28``/etc/hosts`` on Linux. Add a line that associates a name with the29local IP.3031Modern Linux systems may be configured to treat any domain name that32ends with ``.localhost`` like this without adding it to the ``hosts``33file.3435.. code-block:: python36 :caption: ``/etc/hosts``3738 127.0.0.1 hello.localhost394041Configuration42-------------4344The httpd configuration is located at ``/etc/httpd/conf/httpd.conf`` on45Linux. It may be different depending on your operating system. Check the46docs and look for ``httpd.conf``.4748Remove or comment out any existing ``DocumentRoot`` directive. Add the49config lines below. We'll assume the WSGI server is listening locally at50``http://127.0.0.1:8000``.5152.. code-block:: apache53 :caption: ``/etc/httpd/conf/httpd.conf``5455 LoadModule proxy_module modules/mod_proxy.so56 LoadModule proxy_http_module modules/mod_proxy_http.so57 ProxyPass / http://127.0.0.1:8000/58 RequestHeader set X-Forwarded-Proto http59 RequestHeader set X-Forwarded-Prefix /6061The ``LoadModule`` lines might already exist. If so, make sure they are62uncommented instead of adding them manually.6364Then :doc:`proxy_fix` so that your application uses the ``X-Forwarded``65headers. ``X-Forwarded-For`` and ``X-Forwarded-Host`` are automatically66set by ``ProxyPass``.
modified:docs/deploying/asgi.rst-2 removed
1.. _asgi:21ASGI2====34If you'd like to use an ASGI server you will need to utilise WSGI to
23 unmodified lines
deleted:docs/deploying/cgi.rst-61 removed
1CGI2===34If all other deployment methods do not work, CGI will work for sure.5CGI is supported by all major servers but usually has a sub-optimal6performance.78This is also the way you can use a Flask application on Google's `App9Engine`_, where execution happens in a CGI-like environment.1011.. admonition:: Watch Out1213 Please make sure in advance that any ``app.run()`` calls you might14 have in your application file are inside an ``if __name__ ==15 '__main__':`` block or moved to a separate file. Just make sure it's16 not called because this will always start a local WSGI server which17 we do not want if we deploy that application to CGI / app engine.1819 With CGI, you will also have to make sure that your code does not contain20 any ``print`` statements, or that ``sys.stdout`` is overridden by something21 that doesn't write into the HTTP response.2223Creating a `.cgi` file24----------------------2526First you need to create the CGI application file. Let's call it27:file:`yourapplication.cgi`::2829 #!/usr/bin/python30 from wsgiref.handlers import CGIHandler31 from yourapplication import app3233 CGIHandler().run(app)3435Server Setup36------------3738Usually there are two ways to configure the server. Either just copy the39``.cgi`` into a :file:`cgi-bin` (and use `mod_rewrite` or something similar to40rewrite the URL) or let the server point to the file directly.4142In Apache for example you can put something like this into the config:4344.. sourcecode:: apache4546 ScriptAlias /app /path/to/the/application.cgi4748On shared webhosting, though, you might not have access to your Apache config.49In this case, a file called ``.htaccess``, sitting in the public directory50you want your app to be available, works too but the ``ScriptAlias`` directive51won't work in that case:5253.. sourcecode:: apache5455 RewriteEngine On56 RewriteCond %{REQUEST_FILENAME} !-f # Don't interfere with static files57 RewriteRule ^(.*)$ /path/to/the/application.cgi/$1 [L]5859For more information consult the documentation of your webserver.6061.. _App Engine: https://cloud.google.com/appengine/docs/
added:docs/deploying/eventlet.rst+80 added
1eventlet2========34Prefer using :doc:`gunicorn` with eventlet workers rather than using5`eventlet`_ directly. Gunicorn provides a much more configurable and6production-tested server.78`eventlet`_ allows writing asynchronous, coroutine-based code that looks9like standard synchronous Python. It uses `greenlet`_ to enable task10switching without writing ``async/await`` or using ``asyncio``.1112:doc:`gevent` is another library that does the same thing. Certain13dependencies you have, or other considerations, may affect which of the14two you choose to use.1516eventlet provides a WSGI server that can handle many connections at once17instead of one per worker process. You must actually use eventlet in18your own code to see any benefit to using the server.1920.. _eventlet: https://eventlet.net/21.. _greenlet: https://greenlet.readthedocs.io/en/latest/222324Installing25----------2627When using eventlet, greenlet>=1.0 is required, otherwise context locals28such as ``request`` will not work as expected. When using PyPy,29PyPy>=7.3.7 is required.3031Create a virtualenv, install your application, then install32``eventlet``.3334.. code-block:: text3536 $ cd hello-app37 $ python -m venv venv38 $ . venv/bin/activate39 $ pip install . # install your application40 $ pip install eventlet414243Running44-------4546To use eventlet to serve your application, write a script that imports47its ```wsgi.server``, as well as your app or app factory.4849.. code-block:: python50 :caption: ``wsgi.py``5152 import eventlet53 from eventlet import wsgi54 from hello import create_app5556 app = create_app()57 wsgi.server(eventlet.listen(("127.0.0.1", 8000), app)5859.. code-block:: text6061 $ python wsgi.py62 (x) wsgi starting up on http://127.0.0.1:8000636465Binding Externally66------------------6768eventlet should not be run as root because it would cause your69application code to run as root, which is not secure. However, this70means it will not be possible to bind to port 80 or 443. Instead, a71reverse proxy such as :doc:`nginx` or :doc:`apache-httpd` should be used72in front of eventlet.7374You can bind to all external IPs on a non-privileged port by using75``0.0.0.0`` in the server arguments shown in the previous section.76Don't do this when using a reverse proxy setup, otherwise it will be77possible to bypass the proxy.7879``0.0.0.0`` is not a valid address to navigate to, you'd use a specific80IP address in your browser.
deleted:docs/deploying/fastcgi.rst-238 removed
1FastCGI2=======34FastCGI is a deployment option on servers like `nginx`_, `lighttpd`_, and5`cherokee`_; see :doc:`uwsgi` and :doc:`wsgi-standalone` for other options.6To use your WSGI application with any of them you will need a FastCGI7server first. The most popular one is `flup`_ which we will use for8this guide. Make sure to have it installed to follow along.910.. admonition:: Watch Out1112 Please make sure in advance that any ``app.run()`` calls you might13 have in your application file are inside an ``if __name__ ==14 '__main__':`` block or moved to a separate file. Just make sure it's15 not called because this will always start a local WSGI server which16 we do not want if we deploy that application to FastCGI.1718Creating a `.fcgi` file19-----------------------2021First you need to create the FastCGI server file. Let's call it22`yourapplication.fcgi`::2324 #!/usr/bin/python25 from flup.server.fcgi import WSGIServer26 from yourapplication import app2728 if __name__ == '__main__':29 WSGIServer(app).run()3031This is enough for Apache to work, however nginx and older versions of32lighttpd need a socket to be explicitly passed to communicate with the33FastCGI server. For that to work you need to pass the path to the34socket to the :class:`~flup.server.fcgi.WSGIServer`::3536 WSGIServer(application, bindAddress='/path/to/fcgi.sock').run()3738The path has to be the exact same path you define in the server39config.4041Save the :file:`yourapplication.fcgi` file somewhere you will find it again.42It makes sense to have that in :file:`/var/www/yourapplication` or something43similar.4445Make sure to set the executable bit on that file so that the servers46can execute it:4748.. sourcecode:: text4950 $ chmod +x /var/www/yourapplication/yourapplication.fcgi5152Configuring Apache53------------------5455The example above is good enough for a basic Apache deployment but your56`.fcgi` file will appear in your application URL e.g.57``example.com/yourapplication.fcgi/news/``. There are few ways to configure58your application so that yourapplication.fcgi does not appear in the URL.59A preferable way is to use the ScriptAlias and SetHandler configuration60directives to route requests to the FastCGI server. The following example61uses FastCgiServer to start 5 instances of the application which will62handle all incoming requests::6364 LoadModule fastcgi_module /usr/lib64/httpd/modules/mod_fastcgi.so6566 FastCgiServer /var/www/html/yourapplication/app.fcgi -idle-timeout 300 -processes 56768 <VirtualHost *>69 ServerName webapp1.mydomain.com70 DocumentRoot /var/www/html/yourapplication7172 AddHandler fastcgi-script fcgi73 ScriptAlias / /var/www/html/yourapplication/app.fcgi/7475 <Location />76 SetHandler fastcgi-script77 </Location>78 </VirtualHost>7980These processes will be managed by Apache. If you're using a standalone81FastCGI server, you can use the FastCgiExternalServer directive instead.82Note that in the following the path is not real, it's simply used as an83identifier to other84directives such as AliasMatch::8586 FastCgiServer /var/www/html/yourapplication -host 127.0.0.1:30008788If you cannot set ScriptAlias, for example on a shared web host, you can use89WSGI middleware to remove yourapplication.fcgi from the URLs. Set .htaccess::9091 <IfModule mod_fcgid.c>92 AddHandler fcgid-script .fcgi93 <Files ~ (\.fcgi)>94 SetHandler fcgid-script95 Options +FollowSymLinks +ExecCGI96 </Files>97 </IfModule>9899 <IfModule mod_rewrite.c>100 Options +FollowSymlinks101 RewriteEngine On102 RewriteBase /103 RewriteCond %{REQUEST_FILENAME} !-f104 RewriteRule ^(.*)$ yourapplication.fcgi/$1 [QSA,L]105 </IfModule>106107Set yourapplication.fcgi::108109 #!/usr/bin/python110 #: optional path to your local python site-packages folder111 import sys112 sys.path.insert(0, '<your_local_path>/lib/python<your_python_version>/site-packages')113114 from flup.server.fcgi import WSGIServer115 from yourapplication import app116117 class ScriptNameStripper(object):118 def __init__(self, app):119 self.app = app120121 def __call__(self, environ, start_response):122 environ['SCRIPT_NAME'] = ''123 return self.app(environ, start_response)124125 app = ScriptNameStripper(app)126127 if __name__ == '__main__':128 WSGIServer(app).run()129130Configuring lighttpd131--------------------132133A basic FastCGI configuration for lighttpd looks like that::134135 fastcgi.server = ("/yourapplication.fcgi" =>136 ((137 "socket" => "/tmp/yourapplication-fcgi.sock",138 "bin-path" => "/var/www/yourapplication/yourapplication.fcgi",139 "check-local" => "disable",140 "max-procs" => 1141 ))142 )143144 alias.url = (145 "/static/" => "/path/to/your/static/"146 )147148 url.rewrite-once = (149 "^(/static($|/.*))$" => "$1",150 "^(/.*)$" => "/yourapplication.fcgi$1"151 )152153Remember to enable the FastCGI, alias and rewrite modules. This configuration154binds the application to ``/yourapplication``. If you want the application to155work in the URL root you have to work around a lighttpd bug with the156:class:`~werkzeug.contrib.fixers.LighttpdCGIRootFix` middleware.157158Make sure to apply it only if you are mounting the application the URL159root. Also, see the Lighty docs for more information on `FastCGI and Python160<https://redmine.lighttpd.net/projects/lighttpd/wiki/Docs_ModFastCGI>`_ (note that161explicitly passing a socket to run() is no longer necessary).162163Configuring nginx164-----------------165166Installing FastCGI applications on nginx is a bit different because by167default no FastCGI parameters are forwarded.168169A basic Flask FastCGI configuration for nginx looks like this::170171 location = /yourapplication { rewrite ^ /yourapplication/ last; }172 location /yourapplication { try_files $uri @yourapplication; }173 location @yourapplication {174 include fastcgi_params;175 fastcgi_split_path_info ^(/yourapplication)(.*)$;176 fastcgi_param PATH_INFO $fastcgi_path_info;177 fastcgi_param SCRIPT_NAME $fastcgi_script_name;178 fastcgi_pass unix:/tmp/yourapplication-fcgi.sock;179 }180181This configuration binds the application to ``/yourapplication``. If you182want to have it in the URL root it's a bit simpler because you don't183have to figure out how to calculate ``PATH_INFO`` and ``SCRIPT_NAME``::184185 location / { try_files $uri @yourapplication; }186 location @yourapplication {187 include fastcgi_params;188 fastcgi_param PATH_INFO $fastcgi_script_name;189 fastcgi_param SCRIPT_NAME "";190 fastcgi_pass unix:/tmp/yourapplication-fcgi.sock;191 }192193Running FastCGI Processes194-------------------------195196Since nginx and others do not load FastCGI apps, you have to do it by197yourself. `Supervisor can manage FastCGI processes.198<http://supervisord.org/configuration.html#fcgi-program-x-section-settings>`_199You can look around for other FastCGI process managers or write a script200to run your `.fcgi` file at boot, e.g. using a SysV ``init.d`` script.201For a temporary solution, you can always run the ``.fcgi`` script inside202GNU screen. See ``man screen`` for details, and note that this is a203manual solution which does not persist across system restart::204205 $ screen206 $ /var/www/yourapplication/yourapplication.fcgi207208Debugging209---------210211FastCGI deployments tend to be hard to debug on most web servers. Very212often the only thing the server log tells you is something along the213lines of "premature end of headers". In order to debug the application214the only thing that can really give you ideas why it breaks is switching215to the correct user and executing the application by hand.216217This example assumes your application is called `application.fcgi` and218that your web server user is `www-data`::219220 $ su www-data221 $ cd /var/www/yourapplication222 $ python application.fcgi223 Traceback (most recent call last):224 File "yourapplication.fcgi", line 4, in <module>225 ImportError: No module named yourapplication226227In this case the error seems to be "yourapplication" not being on the228python path. Common problems are:229230- Relative paths being used. Don't rely on the current working directory.231- The code depending on environment variables that are not set by the232 web server.233- Different python interpreters being used.234235.. _nginx: https://nginx.org/236.. _lighttpd: https://www.lighttpd.net/237.. _cherokee: https://cherokee-project.com/238.. _flup: https://pypi.org/project/flup/
added:docs/deploying/gevent.rst+80 added
1gevent2======34Prefer using :doc:`gunicorn` or :doc:`uwsgi` with gevent workers rather5than using `gevent`_ directly. Gunicorn and uWSGI provide much more6configurable and production-tested servers.78`gevent`_ allows writing asynchronous, coroutine-based code that looks9like standard synchronous Python. It uses `greenlet`_ to enable task10switching without writing ``async/await`` or using ``asyncio``.1112:doc:`eventlet` is another library that does the same thing. Certain13dependencies you have, or other considerations, may affect which of the14two you choose to use.1516gevent provides a WSGI server that can handle many connections at once17instead of one per worker process. You must actually use gevent in your18own code to see any benefit to using the server.1920.. _gevent: https://www.gevent.org/21.. _greenlet: https://greenlet.readthedocs.io/en/latest/222324Installing25----------2627When using gevent, greenlet>=1.0 is required, otherwise context locals28such as ``request`` will not work as expected. When using PyPy,29PyPy>=7.3.7 is required.3031Create a virtualenv, install your application, then install ``gevent``.3233.. code-block:: text3435 $ cd hello-app36 $ python -m venv venv37 $ . venv/bin/activate38 $ pip install . # install your application39 $ pip install gevent404142Running43-------4445To use gevent to serve your application, write a script that imports its46``WSGIServer``, as well as your app or app factory.4748.. code-block:: python49 :caption: ``wsgi.py``5051 from gevent.pywsgi import WSGIServer52 from hello import create_app5354 app = create_app()55 http_server = WSGIServer(("127.0.0.1", 8000), app)56 http_server.serve_forever()5758.. code-block:: text5960 $ python wsgi.py6162No output is shown when the server starts.636465Binding Externally66------------------6768gevent should not be run as root because it would cause your69application code to run as root, which is not secure. However, this70means it will not be possible to bind to port 80 or 443. Instead, a71reverse proxy such as :doc:`nginx` or :doc:`apache-httpd` should be used72in front of gevent.7374You can bind to all external IPs on a non-privileged port by using75``0.0.0.0`` in the server arguments shown in the previous section. Don't76do this when using a reverse proxy setup, otherwise it will be possible77to bypass the proxy.7879``0.0.0.0`` is not a valid address to navigate to, you'd use a specific80IP address in your browser.
added:docs/deploying/gunicorn.rst+130 added
1Gunicorn2========34`Gunicorn`_ is a pure Python WSGI server with simple configuration and5multiple worker implementations for performance tuning.67* It tends to integrate easily with hosting platforms.8* It does not support Windows (but does run on WSL).9* It is easy to install as it does not require additional dependencies10 or compilation.11* It has built-in async worker support using gevent or eventlet.1213This page outlines the basics of running Gunicorn. Be sure to read its14`documentation`_ and use ``gunicorn --help`` to understand what features15are available.1617.. _Gunicorn: https://gunicorn.org/18.. _documentation: https://docs.gunicorn.org/192021Installing22----------2324Gunicorn is easy to install, as it does not require external25dependencies or compilation. It runs on Windows only under WSL.2627Create a virtualenv, install your application, then install28``gunicorn``.2930.. code-block:: text3132 $ cd hello-app33 $ python -m venv venv34 $ . venv/bin/activate35 $ pip install . # install your application36 $ pip install gunicorn373839Running40-------4142The only required argument to Gunicorn tells it how to load your Flask43application. The syntax is ``{module_import}:{app_variable}``.44``module_import`` is the dotted import name to the module with your45application. ``app_variable`` is the variable with the application. It46can also be a function call (with any arguments) if you're using the47app factory pattern.4849.. code-block:: text5051 # equivalent to 'from hello import app'52 $ gunicorn -w 4 'hello:app'5354 # equivalent to 'from hello import create_app; create_app()'55 $ gunicorn -w 4 'hello:create_app()'5657 Starting gunicorn 20.1.058 Listening at: http://127.0.0.1:8000 (x)59 Using worker: sync60 Booting worker with pid: x61 Booting worker with pid: x62 Booting worker with pid: x63 Booting worker with pid: x6465The ``-w`` option specifies the number of processes to run; a starting66value could be ``CPU * 2``. The default is only 1 worker, which is67probably not what you want for the default worker type.6869Logs for each request aren't shown by default, only worker info and70errors are shown. To show access logs on stdout, use the71``--access-logfile=-`` option.727374Binding Externally75------------------7677Gunicorn should not be run as root because it would cause your78application code to run as root, which is not secure. However, this79means it will not be possible to bind to port 80 or 443. Instead, a80reverse proxy such as :doc:`nginx` or :doc:`apache-httpd` should be used81in front of Gunicorn.8283You can bind to all external IPs on a non-privileged port using the84``-b 0.0.0.0`` option. Don't do this when using a reverse proxy setup,85otherwise it will be possible to bypass the proxy.8687.. code-block:: text8889 $ gunicorn -w 4 -b 0.0.0.0 'hello:create_app()'90 Listening at: http://0.0.0.0:8000 (x)9192``0.0.0.0`` is not a valid address to navigate to, you'd use a specific93IP address in your browser.949596Async with gevent or eventlet97-----------------------------9899The default sync worker is appropriate for many use cases. If you need100asynchronous support, Gunicorn provides workers using either `gevent`_101or `eventlet`_. This is not the same as Python's ``async/await``, or the102ASGI server spec. You must actually use gevent/eventlet in your own code103to see any benefit to using the workers.104105When using either gevent or eventlet, greenlet>=1.0 is required,106otherwise context locals such as ``request`` will not work as expected.107When using PyPy, PyPy>=7.3.7 is required.108109To use gevent:110111.. code-block:: text112113 $ gunicorn -k gevent 'hello:create_app()'114 Starting gunicorn 20.1.0115 Listening at: http://127.0.0.1:8000 (x)116 Using worker: gevent117 Booting worker with pid: x118119To use eventlet:120121.. code-block:: text122123 $ gunicorn -k eventlet 'hello:create_app()'124 Starting gunicorn 20.1.0125 Listening at: http://127.0.0.1:8000 (x)126 Using worker: eventlet127 Booting worker with pid: x128129.. _gevent: https://www.gevent.org/130.. _eventlet: https://eventlet.net/
modified:docs/deploying/index.rst+71 added-26 removed
1Deployment Options2==================1Deploying to Production2=======================34While lightweight and easy to use, **Flask's built-in server is not suitable5for production** as it doesn't scale well. Some of the options available for6properly running Flask in production are documented here.4After developing your application, you'll want to make it available5publicly to other users. When you're developing locally, you're probably6using the built-in development server, debugger, and reloader. These7should not be used in production. Instead, you should use a dedicated8WSGI server or hosting platform, some of which will be described here.98If you want to deploy your Flask application to a WSGI server not listed here,9look up the server documentation about how to use a WSGI app with it. Just10remember that your :class:`Flask` application object is the actual WSGI11application.10"Production" means "not development", which applies whether you're11serving your application publicly to millions of users or privately /12locally to a single user. **Do not use the development server when13deploying to production. It is intended for use only during local14development. It is not designed to be particularly secure, stable, or15efficient.**1617Self-Hosted Options18-------------------1914Hosted options15--------------20Flask is a WSGI *application*. A WSGI *server* is used to run the21application, converting incoming HTTP requests to the standard WSGI22environ, and converting outgoing WSGI responses to HTTP responses.2317- `Deploying Flask on Heroku <https://devcenter.heroku.com/articles/getting-started-with-python>`_18- `Deploying Flask on Google App Engine <https://cloud.google.com/appengine/docs/standard/python3/runtime>`_19- `Deploying Flask on Google Cloud Run <https://cloud.google.com/run/docs/quickstarts/build-and-deploy/python>`_20- `Deploying Flask on AWS Elastic Beanstalk <https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create-deploy-python-flask.html>`_21- `Deploying on Azure (IIS) <https://docs.microsoft.com/en-us/azure/app-service/containers/how-to-configure-python>`_22- `Deploying on PythonAnywhere <https://help.pythonanywhere.com/pages/Flask/>`_24The primary goal of these docs is to familiarize you with the concepts25involved in running a WSGI application using a production WSGI server26and HTTP server. There are many WSGI servers and HTTP servers, with many27configuration possibilities. The pages below discuss the most common28servers, and show the basics of running each one. The next section29discusses platforms that can manage this for you.3024Self-hosted options25-------------------31.. toctree::32 :maxdepth: 13334 gunicorn35 waitress36 mod_wsgi37 uwsgi38 gevent39 eventlet40 asgi4142WSGI servers have HTTP servers built-in. However, a dedicated HTTP43server may be safer, more efficient, or more capable. Putting an HTTP44server in front of the WSGI server is called a "reverse proxy."4546.. toctree::28 :maxdepth: 247 :maxdepth: 14830 wsgi-standalone31 uwsgi32 mod_wsgi33 fastcgi34 cgi35 asgi49 proxy_fix50 nginx51 apache-httpd5253This list is not exhaustive, and you should evaluate these and other54servers based on your application's needs. Different servers will have55different capabilities, configuration, and support.565758Hosting Platforms59-----------------6061There are many services available for hosting web applications without62needing to maintain your own server, networking, domain, etc. Some63services may have a free tier up to a certain time or bandwidth. Many of64these services use one of the WSGI servers described above, or a similar65interface. The links below are for some of the most common platforms,66which have instructions for Flask, WSGI, or Python.6768- `PythonAnywhere <https://help.pythonanywhere.com/pages/Flask/>`_69- `Heroku <https://devcenter.heroku.com/articles/getting-started-with-python>`_70- `Google App Engine <https://cloud.google.com/appengine/docs/standard/python3/building-app>`_71- `Google Cloud Run <https://cloud.google.com/run/docs/quickstarts/build-and-deploy/deploy-python-service>`_72- `AWS Elastic Beanstalk <https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create-deploy-python-flask.html>`_73- `Microsoft Azure <https://docs.microsoft.com/en-us/azure/app-service/quickstart-python>`_7475This list is not exhaustive, and you should evaluate these and other76services based on your application's needs. Different services will have77different capabilities, configuration, pricing, and support.7879You'll probably need to :doc:`proxy_fix` when using most hosting80platforms.
modified:docs/deploying/mod_wsgi.rst+71 added-182 removed
1mod_wsgi (Apache)2=================1mod_wsgi2========34If you are using the `Apache`_ webserver, consider using `mod_wsgi`_.4`mod_wsgi`_ is a WSGI server integrated with the `Apache httpd`_ server.5The modern `mod_wsgi-express`_ command makes it easy to configure and6start the server without needing to write Apache httpd configuration.76.. admonition:: Watch Out8* Tightly integrated with Apache httpd.9* Supports Windows directly.10* Requires a compiler to install. Requires Apache installed separately11 on Windows.12* Does not require a reverse proxy setup.138 Please make sure in advance that any ``app.run()`` calls you might9 have in your application file are inside an ``if __name__ ==10 '__main__':`` block or moved to a separate file. Just make sure it's11 not called because this will always start a local WSGI server which12 we do not want if we deploy that application to mod_wsgi.14This page outlines the basics of running mod_wsgi-express, not the more15complex installation and configuration with httpd. Be sure to read the16`mod_wsgi-express`_, `mod_wsgi`_, and `Apache httpd`_ documentation to17understand what features are available.1819.. _mod_wsgi-express: https://pypi.org/project/mod-wsgi/20.. _mod_wsgi: https://modwsgi.readthedocs.io/14.. _Apache: https://httpd.apache.org/21.. _Apache httpd: https://httpd.apache.org/2216Installing `mod_wsgi`17---------------------2319If you don't have `mod_wsgi` installed yet you have to either install it20using a package manager or compile it yourself. The mod_wsgi21`installation instructions`_ cover source installations on UNIX systems.24Installing25----------2623If you are using Ubuntu/Debian you can apt-get it and activate it as24follows:27On Linux/Mac, the most straightforward way to install mod_wsgi is to28install the ``mod_wsgi-standalone`` package, which will compile an29up-to-date version of Apache httpd as well.3026.. sourcecode:: text31Create a virtualenv, install your application, then install32``mod_wsgi-standalone``.3328 $ apt-get install libapache2-mod-wsgi-py334.. code-block:: text3530If you are using a yum based distribution (Fedora, OpenSUSE, etc..) you31can install it as follows:36 $ cd hello-app37 $ python -m venv venv38 $ . venv/bin/activate39 $ pip install . # install your application40 $ pip install mod_wsgi-standalone4133.. sourcecode:: text42If you want to use the system-installed version of Apache httpd43(required on Windows, optional but faster on Linux/Mac), install the44``mod_wsgi`` package instead. You will get an error if Apache and its45development headers are not available. How to install them depends on46what OS and package manager you use.4735 $ yum install mod_wsgi48.. code-block:: text4937On FreeBSD install `mod_wsgi` by compiling the `www/mod_wsgi` port or by38using pkg_add:50 $ pip install mod_wsgi5140.. sourcecode:: text5242 $ pkg install ap24-py37-mod_wsgi53Running54-------5544If you are using pkgsrc you can install `mod_wsgi` by compiling the45`www/ap2-wsgi` package.56The only argument to ``mod_wsgi-express`` specifies a script containing57your Flask application, which must be called ``application``. You can58write a small script to import your app with this name, or to create it59if using the app factory pattern.6047If you encounter segfaulting child processes after the first apache48reload you can safely ignore them. Just restart the server.61.. code-block:: python62 :caption: ``wsgi.py``6350Creating a `.wsgi` file51-----------------------64 from hello import app6553To run your application you need a :file:`yourapplication.wsgi` file.54This file contains the code `mod_wsgi` is executing on startup55to get the application object. The object called `application`56in that file is then used as application.66 application = app6758For most applications the following file should be sufficient::68.. code-block:: python69 :caption: ``wsgi.py``7060 from yourapplication import app as application71 from hello import create_app7262If a factory function is used in a :file:`__init__.py` file, then the function should be imported::6364 from yourapplication import create_app73 application = create_app()7467If you don't have a factory function for application creation but a singleton68instance you can directly import that one as `application`.75Now run the ``mod_wsgi-express start-server`` command.7670Store that file somewhere that you will find it again (e.g.:71:file:`/var/www/yourapplication`) and make sure that `yourapplication` and all72the libraries that are in use are on the python load path. If you don't73want to install it system wide consider using a `virtual python`_74instance. Keep in mind that you will have to actually install your75application into the virtualenv as well. Alternatively there is the76option to just patch the path in the ``.wsgi`` file before the import::77.. code-block:: text7878 import sys79 sys.path.insert(0, '/path/to/the/application')79 $ mod_wsgi-express start-server wsgi.py --processes 48081Configuring Apache82------------------81The ``--processes`` option specifies the number of worker processes to82run; a starting value could be ``CPU * 2``.8384The last thing you have to do is to create an Apache configuration file85for your application. In this example we are telling `mod_wsgi` to86execute the application under a different user for security reasons:84Logs for each request aren't show in the terminal. If an error occurs,85its information is written to the error log file shown when starting the86server.8788.. sourcecode:: apache8890 <VirtualHost *>91 ServerName example.com89Binding Externally90------------------9193 WSGIDaemonProcess yourapplication user=user1 group=group1 threads=594 WSGIScriptAlias / /var/www/yourapplication/yourapplication.wsgi92Unlike the other WSGI servers in these docs, mod_wsgi can be run as93root to bind to privileged ports like 80 and 443. However, it must be94configured to drop permissions to a different user and group for the95worker processes.9696 <Directory /var/www/yourapplication>97 WSGIProcessGroup yourapplication98 WSGIApplicationGroup %{GLOBAL}99 Order deny,allow100 Allow from all101 </Directory>102 </VirtualHost>97For example, if you created a ``hello`` user and group, you should98install your virtualenv and application as that user, then tell99mod_wsgi to drop to that user after starting.100104Note: WSGIDaemonProcess isn't implemented in Windows and Apache will105refuse to run with the above configuration. On a Windows system, eliminate those lines:101.. code-block:: text102107.. sourcecode:: apache108109 <VirtualHost *>110 ServerName example.com111 WSGIScriptAlias / C:\yourdir\yourapp.wsgi112 <Directory C:\yourdir>113 Order deny,allow114 Allow from all115 </Directory>116 </VirtualHost>117118Note: There have been some changes in access control configuration119for `Apache 2.4`_.120121.. _Apache 2.4: https://httpd.apache.org/docs/trunk/upgrading.html122123Most notably, the syntax for directory permissions has changed from httpd 2.2124125.. sourcecode:: apache126127 Order allow,deny128 Allow from all129130to httpd 2.4 syntax131132.. sourcecode:: apache133134 Require all granted135136137For more information consult the `mod_wsgi documentation`_.138139.. _mod_wsgi: https://github.com/GrahamDumpleton/mod_wsgi140.. _installation instructions: https://modwsgi.readthedocs.io/en/develop/installation.html141.. _virtual python: https://pypi.org/project/virtualenv/142.. _mod_wsgi documentation: https://modwsgi.readthedocs.io/en/develop/index.html143144Troubleshooting145---------------146147If your application does not run, follow this guide to troubleshoot:148149**Problem:** application does not run, errorlog shows SystemExit ignored150 You have an ``app.run()`` call in your application file that is not151 guarded by an ``if __name__ == '__main__':`` condition. Either152 remove that :meth:`~flask.Flask.run` call from the file and move it153 into a separate :file:`run.py` file or put it into such an if block.154155**Problem:** application gives permission errors156 Probably caused by your application running as the wrong user. Make157 sure the folders the application needs access to have the proper158 privileges set and the application runs as the correct user159 (``user`` and ``group`` parameter to the `WSGIDaemonProcess`160 directive)161162**Problem:** application dies with an error on print163 Keep in mind that mod_wsgi disallows doing anything with164 :data:`sys.stdout` and :data:`sys.stderr`. You can disable this165 protection from the config by setting the `WSGIRestrictStdout` to166 ``off``:167168 .. sourcecode:: apache169170 WSGIRestrictStdout Off171172 Alternatively you can also replace the standard out in the .wsgi file173 with a different stream::174175 import sys176 sys.stdout = sys.stderr177178**Problem:** accessing resources gives IO errors179 Your application probably is a single .py file you symlinked into180 the site-packages folder. Please be aware that this does not work,181 instead you either have to put the folder into the pythonpath the182 file is stored in, or convert your application into a package.183184 The reason for this is that for non-installed packages, the module185 filename is used to locate the resources and for symlinks the wrong186 filename is picked up.187188Support for Automatic Reloading189-------------------------------190191To help deployment tools you can activate support for automatic192reloading. Whenever something changes the ``.wsgi`` file, `mod_wsgi` will193reload all the daemon processes for us.194195For that, just add the following directive to your `Directory` section:196197.. sourcecode:: apache198199 WSGIScriptReloading On200201Working with Virtual Environments202---------------------------------203204Virtual environments have the advantage that they never install the205required dependencies system wide so you have a better control over what206is used where. If you want to use a virtual environment with mod_wsgi207you have to modify your ``.wsgi`` file slightly.208209Add the following lines to the top of your ``.wsgi`` file::210211 activate_this = '/path/to/env/bin/activate_this.py'212 with open(activate_this) as file_:213 exec(file_.read(), dict(__file__=activate_this))214215This sets up the load paths according to the settings of the virtual216environment. Keep in mind that the path has to be absolute.103 $ sudo /home/hello/venv/bin/mod_wsgi-express start-server \104 /home/hello/wsgi.py \105 --user hello --group hello --port 80 --processes 4
added:docs/deploying/nginx.rst+69 added
1nginx2=====34`nginx`_ is a fast, production level HTTP server. When serving your5application with one of the WSGI servers listed in :doc:`index`, it is6often good or necessary to put a dedicated HTTP server in front of it.7This "reverse proxy" can handle incoming requests, TLS, and other8security and performance concerns better than the WSGI server.910Nginx can be installed using your system package manager, or a pre-built11executable for Windows. Installing and running Nginx itself is outside12the scope of this doc. This page outlines the basics of configuring13Nginx to proxy your application. Be sure to read its documentation to14understand what features are available.1516.. _nginx: https://nginx.org/171819Domain Name20-----------2122Acquiring and configuring a domain name is outside the scope of this23doc. In general, you will buy a domain name from a registrar, pay for24server space with a hosting provider, and then point your registrar25at the hosting provider's name servers.2627To simulate this, you can also edit your ``hosts`` file, located at28``/etc/hosts`` on Linux. Add a line that associates a name with the29local IP.3031Modern Linux systems may be configured to treat any domain name that32ends with ``.localhost`` like this without adding it to the ``hosts``33file.3435.. code-block:: python36 :caption: ``/etc/hosts``3738 127.0.0.1 hello.localhost394041Configuration42-------------4344The nginx configuration is located at ``/etc/nginx/nginx.conf`` on45Linux. It may be different depending on your operating system. Check the46docs and look for ``nginx.conf``.4748Remove or comment out any existing ``server`` section. Add a ``server``49section and use the ``proxy_pass`` directive to point to the address the50WSGI server is listening on. We'll assume the WSGI server is listening51locally at ``http://127.0.0.1:8000``.5253.. code-block:: nginx54 :caption: ``/etc/nginx.conf``5556 server {57 listen 80;58 server_name _;5960 location / {61 proxy_pass http://127.0.0.1:8000/;62 proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;63 proxy_set_header X-Forwarded-Proto $scheme;64 proxy_set_header X-Forwarded-Host $host;65 proxy_set_header X-Forwarded-Prefix /;66 }67 }6869Then :doc:`proxy_fix` so that your application uses these headers.
added:docs/deploying/proxy_fix.rst+33 added
1Tell Flask it is Behind a Proxy2===============================34When using a reverse proxy, or many Python hosting platforms, the proxy5will intercept and forward all external requests to the local WSGI6server.78From the WSGI server and Flask application's perspectives, requests are9now coming from the HTTP server to the local address, rather than from10the remote address to the external server address.1112HTTP servers should set ``X-Forwarded-`` headers to pass on the real13values to the application. The application can then be told to trust and14use those values by wrapping it with the15:doc:`werkzeug:middleware/proxy_fix` middleware provided by Werkzeug.1617This middleware should only be used if the application is actually18behind a proxy, and should be configured with the number of proxies that19are chained in front of it. Not all proxies set all the headers. Since20incoming headers can be faked, you must set how many proxies are setting21each header so the middleware knows what to trust.2223.. code-block:: python2425 from werkzeug.middleware.proxy_fix import ProxyFix2627 app.wsgi_app = ProxyFix(28 app.wsgi_app, x_for=1, x_proto=1, x_host=1, x_prefix=129 )3031Remember, only apply this middleware if you are behind a proxy, and set32the correct number of proxies that set each header. It can be a security33issue if you get this configuration wrong.
modified:docs/deploying/uwsgi.rst+125 added-51 removed
1uWSGI2=====34uWSGI is a deployment option on servers like `nginx`_, `lighttpd`_, and5`cherokee`_; see :doc:`fastcgi` and :doc:`wsgi-standalone` for other options.6To use your WSGI application with uWSGI protocol you will need a uWSGI server7first. uWSGI is both a protocol and an application server; the application8server can serve uWSGI, FastCGI, and HTTP protocols.4`uWSGI`_ is a fast, compiled server suite with extensive configuration5and capabilities beyond a basic server.610The most popular uWSGI server is `uwsgi`_, which we will use for this11guide. Make sure to have it installed to follow along.7* It can be very performant due to being a compiled program.8* It is complex to configure beyond the basic application, and has so9 many options that it can be difficult for beginners to understand.10* It does not support Windows (but does run on WSL).11* It requires a compiler to install in some cases.1213.. admonition:: Watch Out13This page outlines the basics of running uWSGI. Be sure to read its14documentation to understand what features are available.1515 Please make sure in advance that any ``app.run()`` calls you might16 have in your application file are inside an ``if __name__ ==17 '__main__':`` block or moved to a separate file. Just make sure it's18 not called because this will always start a local WSGI server which19 we do not want if we deploy that application to uWSGI.16.. _uWSGI: https://uwsgi-docs.readthedocs.io/en/latest/1721Starting your app with uwsgi22----------------------------1824`uwsgi` is designed to operate on WSGI callables found in python modules.19Installing20----------2126Given a flask application in myapp.py, use the following command:22uWSGI has multiple ways to install it. The most straightforward is to23install the ``pyuwsgi`` package, which provides precompiled wheels for24common platforms. However, it does not provide SSL support, which can be25provided with a reverse proxy instead.2628.. sourcecode:: text27Create a virtualenv, install your application, then install ``pyuwsgi``.2830 $ uwsgi -s /tmp/yourapplication.sock --manage-script-name --mount /yourapplication=myapp:app29.. code-block:: text3032The ``--manage-script-name`` will move the handling of ``SCRIPT_NAME``33to uwsgi, since it is smarter about that.34It is used together with the ``--mount`` directive which will make35requests to ``/yourapplication`` be directed to ``myapp:app``.36If your application is accessible at root level, you can use a37single ``/`` instead of ``/yourapplication``. ``myapp`` refers to the name of38the file of your flask application (without extension) or the module which39provides ``app``. ``app`` is the callable inside of your application (usually40the line reads ``app = Flask(__name__)``).31 $ cd hello-app32 $ python -m venv venv33 $ . venv/bin/activate34 $ pip install . # install your application35 $ pip install pyuwsgi3642If you want to deploy your flask application inside of a virtual environment,43you need to also add ``--virtualenv /path/to/virtual/environment``. You might44also need to add ``--plugin python`` or ``--plugin python3`` depending on which45python version you use for your project.37If you have a compiler available, you can install the ``uwsgi`` package38instead. Or install the ``pyuwsgi`` package from sdist instead of wheel.39Either method will include SSL support.4047Configuring nginx41.. code-block:: text4243 $ pip install uwsgi4445 # or46 $ pip install --no-binary pyuwsgi pyuwsgi474849Running50-------5152The most basic way to run uWSGI is to tell it to start an HTTP server53and import your application.5455.. code-block:: text5657 $ uwsgi --http 127.0.0.1:8000 --master -p 4 -w hello:app5859 *** Starting uWSGI 2.0.20 (64bit) on [x] ***60 *** Operational MODE: preforking ***61 mounting hello:app on /62 spawned uWSGI master process (pid: x)63 spawned uWSGI worker 1 (pid: x, cores: 1)64 spawned uWSGI worker 2 (pid: x, cores: 1)65 spawned uWSGI worker 3 (pid: x, cores: 1)66 spawned uWSGI worker 4 (pid: x, cores: 1)67 spawned uWSGI http 1 (pid: x)6869If you're using the app factory pattern, you'll need to create a small70Python file to create the app, then point uWSGI at that.7172.. code-block:: python73 :caption: ``wsgi.py``7475 from hello import create_app7677 app = create_app()7879.. code-block:: text8081 $ uwsgi --http 127.0.0.1:8000 --master -p 4 -w wsgi:app8283The ``--http`` option starts an HTTP server at 127.0.0.1 port 8000. The84``--master`` option specifies the standard worker manager. The ``-p``85option starts 4 worker processes; a starting value could be ``CPU * 2``.86The ``-w`` option tells uWSGI how to import your application878889Binding Externally90------------------9192uWSGI should not be run as root with the configuration shown in this doc93because it would cause your application code to run as root, which is94not secure. However, this means it will not be possible to bind to port9580 or 443. Instead, a reverse proxy such as :doc:`nginx` or96:doc:`apache-httpd` should be used in front of uWSGI. It is possible to97run uWSGI as root securely, but that is beyond the scope of this doc.9899uWSGI has optimized integration with `Nginx uWSGI`_ and100`Apache mod_proxy_uwsgi`_, and possibly other servers, instead of using101a standard HTTP proxy. That configuration is beyond the scope of this102doc, see the links for more information.103104.. _Nginx uWSGI: https://uwsgi-docs.readthedocs.io/en/latest/Nginx.html105.. _Apache mod_proxy_uwsgi: https://uwsgi-docs.readthedocs.io/en/latest/Apache.html#mod-proxy-uwsgi106107You can bind to all external IPs on a non-privileged port using the108``--http 0.0.0.0:8000`` option. Don't do this when using a reverse proxy109setup, otherwise it will be possible to bypass the proxy.110111.. code-block:: text112113 $ uwsgi --http 0.0.0.0:8000 --master -p 4 -w wsgi:app114115``0.0.0.0`` is not a valid address to navigate to, you'd use a specific116IP address in your browser.117118119Async with gevent120-----------------12150A basic flask nginx configuration looks like this::122The default sync worker is appropriate for many use cases. If you need123asynchronous support, uWSGI provides a `gevent`_ worker. This is not the124same as Python's ``async/await``, or the ASGI server spec. You must125actually use gevent in your own code to see any benefit to using the126worker.12752 location = /yourapplication { rewrite ^ /yourapplication/; }53 location /yourapplication { try_files $uri @yourapplication; }54 location @yourapplication {55 include uwsgi_params;56 uwsgi_pass unix:/tmp/yourapplication.sock;57 }128When using gevent, greenlet>=1.0 is required, otherwise context locals129such as ``request`` will not work as expected. When using PyPy,130PyPy>=7.3.7 is required.13159This configuration binds the application to ``/yourapplication``. If you want60to have it in the URL root its a bit simpler::132.. code-block:: text13362 location / { try_files $uri @yourapplication; }63 location @yourapplication {64 include uwsgi_params;65 uwsgi_pass unix:/tmp/yourapplication.sock;66 }134 $ uwsgi --http 127.0.0.1:8000 --master --gevent 100 -w wsgi:app13568.. _nginx: https://nginx.org/69.. _lighttpd: https://www.lighttpd.net/70.. _cherokee: https://cherokee-project.com/71.. _uwsgi: https://uwsgi-docs.readthedocs.io/en/latest/136 *** Starting uWSGI 2.0.20 (64bit) on [x] ***137 *** Operational MODE: async ***138 mounting hello:app on /139 spawned uWSGI master process (pid: x)140 spawned uWSGI worker 1 (pid: x, cores: 100)141 spawned uWSGI http 1 (pid: x)142 *** running gevent loop engine [addr:x] ***143144145.. _gevent: https://www.gevent.org/
added:docs/deploying/waitress.rst+75 added
1Waitress2========34`Waitress`_ is a pure Python WSGI server.56* It is easy to configure.7* It supports Windows directly.8* It is easy to install as it does not require additional dependencies9 or compilation.10* It does not support streaming requests, full request data is always11 buffered.12* It uses a single process with multiple thread workers.1314This page outlines the basics of running Waitress. Be sure to read its15documentation and ``waitress-serve --help`` to understand what features16are available.1718.. _Waitress: https://docs.pylonsproject.org/projects/waitress/192021Installing22----------2324Create a virtualenv, install your application, then install25``waitress``.2627.. code-block:: text2829 $ cd hello-app30 $ python -m venv venv31 $ . venv/bin/activate32 $ pip install . # install your application33 $ pip install waitress343536Running37-------3839The only required argument to ``waitress-serve`` tells it how to load40your Flask application. The syntax is ``{module}:{app}``. ``module`` is41the dotted import name to the module with your application. ``app`` is42the variable with the application. If you're using the app factory43pattern, use ``--call {module}:{factory}`` instead.4445.. code-block:: text4647 # equivalent to 'from hello import app'48 $ waitress-serve hello:app --host 127.0.0.14950 # equivalent to 'from hello import create_app; create_app()'51 $ waitress-serve --call hello:create_app --host 127.0.0.15253 Serving on http://127.0.0.1:80805455The ``--host`` option binds the server to local ``127.0.0.1`` only.5657Logs for each request aren't shown, only errors are shown. Logging can58be configured through the Python interface instead of the command line.596061Binding Externally62------------------6364Waitress should not be run as root because it would cause your65application code to run as root, which is not secure. However, this66means it will not be possible to bind to port 80 or 443. Instead, a67reverse proxy such as :doc:`nginx` or :doc:`apache-httpd` should be used68in front of Waitress.6970You can bind to all external IPs on a non-privileged port by not71specifying the ``--host`` option. Don't do this when using a revers72proxy setup, otherwise it will be possible to bypass the proxy.7374``0.0.0.0`` is not a valid address to navigate to, you'd use a specific75IP address in your browser.
deleted:docs/deploying/wsgi-standalone.rst-262 removed
1Standalone WSGI Servers2=======================34Most WSGI servers also provide HTTP servers, so they can run a WSGI5application and make it available externally.67It may still be a good idea to run the server behind a dedicated HTTP8server such as Apache or Nginx. See :ref:`deploying-proxy-setups` if you9run into issues with that.101112Gunicorn13--------1415`Gunicorn`_ is a WSGI and HTTP server for UNIX. To run a Flask16application, tell Gunicorn how to import your Flask app object.1718.. code-block:: text1920 $ gunicorn -w 4 -b 0.0.0.0:5000 your_project:app2122The ``-w 4`` option uses 4 workers to handle 4 requests at once. The23``-b 0.0.0.0:5000`` serves the application on all interfaces on port245000.2526Gunicorn provides many options for configuring the server, either27through a configuration file or with command line options. Use28``gunicorn --help`` or see the docs for more information.2930The command expects the name of your module or package to import and31the application instance within the module. If you use the application32factory pattern, you can pass a call to that.3334.. code-block:: text3536 $ gunicorn -w 4 -b 0.0.0.0:5000 "myproject:create_app()"373839Async with Gevent or Eventlet40~~~~~~~~~~~~~~~~~~~~~~~~~~~~~4142The default sync worker is appropriate for many use cases. If you need43asynchronous support, Gunicorn provides workers using either `gevent`_44or `eventlet`_. This is not the same as Python's ``async/await``, or the45ASGI server spec.4647When using either gevent or eventlet, greenlet>=1.0 is required,48otherwise context locals such as ``request`` will not work as expected.49When using PyPy, PyPy>=7.3.7 is required.5051To use gevent:5253.. code-block:: text5455 $ gunicorn -k gevent -b 0.0.0.0:5000 your_project:app5657To use eventlet:5859.. code-block:: text6061 $ gunicorn -k eventlet -b 0.0.0.0:5000 your_project:app626364.. _Gunicorn: https://gunicorn.org/65.. _gevent: http://www.gevent.org/66.. _eventlet: https://eventlet.net/67.. _greenlet: https://greenlet.readthedocs.io/en/latest/686970uWSGI71-----7273`uWSGI`_ is a fast application server written in C. It is very74configurable, which makes it more complicated to setup than Gunicorn.75It also provides many other utilities for writing robust web76applications. To run a Flask application, tell uWSGI how to import77your Flask app object.7879.. code-block:: text8081 $ uwsgi --master -p 4 --http 0.0.0.0:5000 -w your_project:app8283The ``-p 4`` option uses 4 workers to handle 4 requests at once. The84``--http 0.0.0.0:5000`` serves the application on all interfaces on port855000.8687uWSGI has optimized integration with Nginx and Apache instead of using88a standard HTTP proxy. See :doc:`configuring uWSGI and Nginx <uwsgi>`.899091Async with Gevent92~~~~~~~~~~~~~~~~~9394The default sync worker is appropriate for many use cases. If you need95asynchronous support, uWSGI provides workers using `gevent`_. It also96supports other async modes, see the docs for more information. This is97not the same as Python's ``async/await``, or the ASGI server spec.9899When using gevent, greenlet>=1.0 is required, otherwise context locals100such as ``request`` will not work as expected. When using PyPy,101PyPy>=7.3.7 is required.102103.. code-block:: text104105 $ uwsgi --master --gevent 100 --http 0.0.0.0:5000 -w your_project:app106107.. _uWSGI: https://uwsgi-docs.readthedocs.io/en/latest/108109110Gevent111------112113Prefer using `Gunicorn`_ with Gevent workers rather than using Gevent114directly. Gunicorn provides a much more configurable and115production-tested server. See the section on Gunicorn above.116117`Gevent`_ allows writing asynchronous, coroutine-based code that looks118like standard synchronous Python. It uses `greenlet`_ to enable task119switching without writing ``async/await`` or using ``asyncio``.120121It provides a WSGI server that can handle many connections at once122instead of one per worker process.123124`Eventlet`_, described below, is another library that does the same125thing. Certain dependencies you have, or other consideration, may affect126which of the two you choose to use127128To use gevent to serve your application, import its ``WSGIServer`` and129use it to run your ``app``.130131.. code-block:: python132133 from gevent.pywsgi import WSGIServer134 from your_project import app135136 http_server = WSGIServer(("", 5000), app)137 http_server.serve_forever()138139140Eventlet141--------142143Prefer using `Gunicorn`_ with Eventlet workers rather than using144Eventlet directly. Gunicorn provides a much more configurable and145production-tested server. See the section on Gunicorn above.146147`Eventlet`_ allows writing asynchronous, coroutine-based code that looks148like standard synchronous Python. It uses `greenlet`_ to enable task149switching without writing ``async/await`` or using ``asyncio``.150151It provides a WSGI server that can handle many connections at once152instead of one per worker process.153154`Gevent`_, described above, is another library that does the same155thing. Certain dependencies you have, or other consideration, may affect156which of the two you choose to use157158To use eventlet to serve your application, import its ``wsgi.server``159and use it to run your ``app``.160161.. code-block:: python162163 import eventlet164 from eventlet import wsgi165 from your_project import app166167 wsgi.server(eventlet.listen(("", 5000), app)168169170Twisted Web171-----------172173`Twisted Web`_ is the web server shipped with `Twisted`_, a mature,174non-blocking event-driven networking library. Twisted Web comes with a175standard WSGI container which can be controlled from the command line using176the ``twistd`` utility:177178.. code-block:: text179180 $ twistd web --wsgi myproject.app181182This example will run a Flask application called ``app`` from a module named183``myproject``.184185Twisted Web supports many flags and options, and the ``twistd`` utility does186as well; see ``twistd -h`` and ``twistd web -h`` for more information. For187example, to run a Twisted Web server in the foreground, on port 8080, with an188application from ``myproject``:189190.. code-block:: text191192 $ twistd -n web --port tcp:8080 --wsgi myproject.app193194.. _Twisted: https://twistedmatrix.com/trac/195.. _Twisted Web: https://twistedmatrix.com/trac/wiki/TwistedWeb196197198.. _deploying-proxy-setups:199200Proxy Setups201------------202203If you deploy your application using one of these servers behind an HTTP proxy204you will need to rewrite a few headers in order for the application to work.205The two problematic values in the WSGI environment usually are ``REMOTE_ADDR``206and ``HTTP_HOST``. You can configure your httpd to pass these headers, or you207can fix them in middleware. Werkzeug ships a fixer that will solve some common208setups, but you might want to write your own WSGI middleware for specific209setups.210211Here's a simple nginx configuration which proxies to an application served on212localhost at port 8000, setting appropriate headers:213214.. sourcecode:: nginx215216 server {217 listen 80;218219 server_name _;220221 access_log /var/log/nginx/access.log;222 error_log /var/log/nginx/error.log;223224 location / {225 proxy_pass http://127.0.0.1:8000/;226 proxy_redirect off;227228 proxy_set_header Host $host;229 proxy_set_header X-Real-IP $remote_addr;230 proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;231 proxy_set_header X-Forwarded-Proto $scheme;232 }233 }234235If your httpd is not providing these headers, the most common setup invokes the236host being set from ``X-Forwarded-Host`` and the remote address from237``X-Forwarded-For``::238239 from werkzeug.middleware.proxy_fix import ProxyFix240 app.wsgi_app = ProxyFix(app.wsgi_app, x_proto=1, x_host=1)241242.. admonition:: Trusting Headers243244 Please keep in mind that it is a security issue to use such a middleware in245 a non-proxy setup because it will blindly trust the incoming headers which246 might be forged by malicious clients.247248If you want to rewrite the headers from another header, you might want to249use a fixer like this::250251 class CustomProxyFix(object):252253 def __init__(self, app):254 self.app = app255256 def __call__(self, environ, start_response):257 host = environ.get('HTTP_X_FHOST', '')258 if host:259 environ['HTTP_HOST'] = host260 return self.app(environ, start_response)261262 app.wsgi_app = CustomProxyFix(app.wsgi_app)
modified:docs/async-await.rst+2 added-2 removed
68 unmodified lines
69If you wish to use background tasks it is best to use a task queue to70trigger background work, rather than spawn tasks in a view71function. With that in mind you can spawn asyncio tasks by serving72Flask with an ASGI server and utilising the asgiref WsgiToAsgi adapter73as described in :ref:`asgi`. This works as the adapter creates an74event loop that runs continually.73as described in :doc:`deploying/asgi`. This works as the adapter creates74an event loop that runs continually.757677When to use Quart instead78-------------------------
53 unmodified lines