Merge pull request #4637 from pallets/docs-deploy
Before adoption: this commit came in with the history the project adopted, so no landing records it.
rewrite deployment docs
authored by David Lord · committed by GitHub · parents 9398630, 2ea77c2 · 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
Provenance
- Commit
b0a144d- Tree
9242f68- Author
David Lord <davidism@gmail.com>- Committer
GitHub <noreply@github.com>- Parent 1
9398630- Parent 2
2ea77c2
15 files changed+802 added−824 removed
added:docs/deploying/apache-httpd.rst+66 added
1+Apache httpd2+============3+4+`Apache httpd`_ is a fast, production level HTTP server. When serving5+your application with one of the WSGI servers listed in :doc:`index`, it6+is often good or necessary to put a dedicated HTTP server in front of7+it. This "reverse proxy" can handle incoming requests, TLS, and other8+security and performance concerns better than the WSGI server.9+10+httpd can be installed using your system package manager, or a pre-built11+executable for Windows. Installing and running httpd itself is outside12+the scope of this doc. This page outlines the basics of configuring13+httpd to proxy your application. Be sure to read its documentation to14+understand what features are available.15+16+.. _Apache httpd: https://httpd.apache.org/17+18+19+Domain Name20+-----------21+22+Acquiring and configuring a domain name is outside the scope of this23+doc. In general, you will buy a domain name from a registrar, pay for24+server space with a hosting provider, and then point your registrar25+at the hosting provider's name servers.26+27+To simulate this, you can also edit your ``hosts`` file, located at28+``/etc/hosts`` on Linux. Add a line that associates a name with the29+local IP.30+31+Modern Linux systems may be configured to treat any domain name that32+ends with ``.localhost`` like this without adding it to the ``hosts``33+file.34+35+.. code-block:: python36+ :caption: ``/etc/hosts``37+38+ 127.0.0.1 hello.localhost39+40+41+Configuration42+-------------43+44+The httpd configuration is located at ``/etc/httpd/conf/httpd.conf`` on45+Linux. It may be different depending on your operating system. Check the46+docs and look for ``httpd.conf``.47+48+Remove or comment out any existing ``DocumentRoot`` directive. Add the49+config lines below. We'll assume the WSGI server is listening locally at50+``http://127.0.0.1:8000``.51+52+.. code-block:: apache53+ :caption: ``/etc/httpd/conf/httpd.conf``54+55+ 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 /60+61+The ``LoadModule`` lines might already exist. If so, make sure they are62+uncommented instead of adding them manually.63+64+Then :doc:`proxy_fix` so that your application uses the ``X-Forwarded``65+headers. ``X-Forwarded-For`` and ``X-Forwarded-Host`` are automatically66+set by ``ProxyPass``.modified:docs/deploying/asgi.rst-2 removed
1-.. _asgi:2-1 ASGI2 ====3 4 If you'd like to use an ASGI server you will need to utilise WSGI to23 unmodified linesdeleted:docs/deploying/cgi.rst-61 removed
1-CGI2-===3-4-If all other deployment methods do not work, CGI will work for sure.5-CGI is supported by all major servers but usually has a sub-optimal6-performance.7-8-This is also the way you can use a Flask application on Google's `App9-Engine`_, where execution happens in a CGI-like environment.10-11-.. admonition:: Watch Out12-13- 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.18-19- 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.22-23-Creating a `.cgi` file24-----------------------25-26-First you need to create the CGI application file. Let's call it27-:file:`yourapplication.cgi`::28-29- #!/usr/bin/python30- from wsgiref.handlers import CGIHandler31- from yourapplication import app32-33- CGIHandler().run(app)34-35-Server Setup36-------------37-38-Usually 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 to40-rewrite the URL) or let the server point to the file directly.41-42-In Apache for example you can put something like this into the config:43-44-.. sourcecode:: apache45-46- ScriptAlias /app /path/to/the/application.cgi47-48-On shared webhosting, though, you might not have access to your Apache config.49-In this case, a file called ``.htaccess``, sitting in the public directory50-you want your app to be available, works too but the ``ScriptAlias`` directive51-won't work in that case:52-53-.. sourcecode:: apache54-55- RewriteEngine On56- RewriteCond %{REQUEST_FILENAME} !-f # Don't interfere with static files57- RewriteRule ^(.*)$ /path/to/the/application.cgi/$1 [L]58-59-For more information consult the documentation of your webserver.60-61-.. _App Engine: https://cloud.google.com/appengine/docs/added:docs/deploying/eventlet.rst+80 added
1+eventlet2+========3+4+Prefer using :doc:`gunicorn` with eventlet workers rather than using5+`eventlet`_ directly. Gunicorn provides a much more configurable and6+production-tested server.7+8+`eventlet`_ allows writing asynchronous, coroutine-based code that looks9+like standard synchronous Python. It uses `greenlet`_ to enable task10+switching without writing ``async/await`` or using ``asyncio``.11+12+:doc:`gevent` is another library that does the same thing. Certain13+dependencies you have, or other considerations, may affect which of the14+two you choose to use.15+16+eventlet provides a WSGI server that can handle many connections at once17+instead of one per worker process. You must actually use eventlet in18+your own code to see any benefit to using the server.19+20+.. _eventlet: https://eventlet.net/21+.. _greenlet: https://greenlet.readthedocs.io/en/latest/22+23+24+Installing25+----------26+27+When using eventlet, greenlet>=1.0 is required, otherwise context locals28+such as ``request`` will not work as expected. When using PyPy,29+PyPy>=7.3.7 is required.30+31+Create a virtualenv, install your application, then install32+``eventlet``.33+34+.. code-block:: text35+36+ $ cd hello-app37+ $ python -m venv venv38+ $ . venv/bin/activate39+ $ pip install . # install your application40+ $ pip install eventlet41+42+43+Running44+-------45+46+To use eventlet to serve your application, write a script that imports47+its ```wsgi.server``, as well as your app or app factory.48+49+.. code-block:: python50+ :caption: ``wsgi.py``51+52+ import eventlet53+ from eventlet import wsgi54+ from hello import create_app55+56+ app = create_app()57+ wsgi.server(eventlet.listen(("127.0.0.1", 8000), app)58+59+.. code-block:: text60+61+ $ python wsgi.py62+ (x) wsgi starting up on http://127.0.0.1:800063+64+65+Binding Externally66+------------------67+68+eventlet should not be run as root because it would cause your69+application code to run as root, which is not secure. However, this70+means it will not be possible to bind to port 80 or 443. Instead, a71+reverse proxy such as :doc:`nginx` or :doc:`apache-httpd` should be used72+in front of eventlet.73+74+You 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.76+Don't do this when using a reverse proxy setup, otherwise it will be77+possible to bypass the proxy.78+79+``0.0.0.0`` is not a valid address to navigate to, you'd use a specific80+IP address in your browser.deleted:docs/deploying/fastcgi.rst-238 removed
1-FastCGI2-=======3-4-FastCGI is a deployment option on servers like `nginx`_, `lighttpd`_, and5-`cherokee`_; see :doc:`uwsgi` and :doc:`wsgi-standalone` for other options.6-To use your WSGI application with any of them you will need a FastCGI7-server first. The most popular one is `flup`_ which we will use for8-this guide. Make sure to have it installed to follow along.9-10-.. admonition:: Watch Out11-12- 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.17-18-Creating a `.fcgi` file19------------------------20-21-First you need to create the FastCGI server file. Let's call it22-`yourapplication.fcgi`::23-24- #!/usr/bin/python25- from flup.server.fcgi import WSGIServer26- from yourapplication import app27-28- if __name__ == '__main__':29- WSGIServer(app).run()30-31-This is enough for Apache to work, however nginx and older versions of32-lighttpd need a socket to be explicitly passed to communicate with the33-FastCGI server. For that to work you need to pass the path to the34-socket to the :class:`~flup.server.fcgi.WSGIServer`::35-36- WSGIServer(application, bindAddress='/path/to/fcgi.sock').run()37-38-The path has to be the exact same path you define in the server39-config.40-41-Save the :file:`yourapplication.fcgi` file somewhere you will find it again.42-It makes sense to have that in :file:`/var/www/yourapplication` or something43-similar.44-45-Make sure to set the executable bit on that file so that the servers46-can execute it:47-48-.. sourcecode:: text49-50- $ chmod +x /var/www/yourapplication/yourapplication.fcgi51-52-Configuring Apache53-------------------54-55-The 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 configure58-your application so that yourapplication.fcgi does not appear in the URL.59-A preferable way is to use the ScriptAlias and SetHandler configuration60-directives to route requests to the FastCGI server. The following example61-uses FastCgiServer to start 5 instances of the application which will62-handle all incoming requests::63-64- LoadModule fastcgi_module /usr/lib64/httpd/modules/mod_fastcgi.so65-66- FastCgiServer /var/www/html/yourapplication/app.fcgi -idle-timeout 300 -processes 567-68- <VirtualHost *>69- ServerName webapp1.mydomain.com70- DocumentRoot /var/www/html/yourapplication71-72- AddHandler fastcgi-script fcgi73- ScriptAlias / /var/www/html/yourapplication/app.fcgi/74-75- <Location />76- SetHandler fastcgi-script77- </Location>78- </VirtualHost>79-80-These processes will be managed by Apache. If you're using a standalone81-FastCGI server, you can use the FastCgiExternalServer directive instead.82-Note that in the following the path is not real, it's simply used as an83-identifier to other84-directives such as AliasMatch::85-86- FastCgiServer /var/www/html/yourapplication -host 127.0.0.1:300087-88-If you cannot set ScriptAlias, for example on a shared web host, you can use89-WSGI middleware to remove yourapplication.fcgi from the URLs. Set .htaccess::90-91- <IfModule mod_fcgid.c>92- AddHandler fcgid-script .fcgi93- <Files ~ (\.fcgi)>94- SetHandler fcgid-script95- Options +FollowSymLinks +ExecCGI96- </Files>97- </IfModule>98-99- <IfModule mod_rewrite.c>100- Options +FollowSymlinks101- RewriteEngine On102- RewriteBase /103- RewriteCond %{REQUEST_FILENAME} !-f104- RewriteRule ^(.*)$ yourapplication.fcgi/$1 [QSA,L]105- </IfModule>106-107-Set yourapplication.fcgi::108-109- #!/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')113-114- from flup.server.fcgi import WSGIServer115- from yourapplication import app116-117- class ScriptNameStripper(object):118- def __init__(self, app):119- self.app = app120-121- def __call__(self, environ, start_response):122- environ['SCRIPT_NAME'] = ''123- return self.app(environ, start_response)124-125- app = ScriptNameStripper(app)126-127- if __name__ == '__main__':128- WSGIServer(app).run()129-130-Configuring lighttpd131---------------------132-133-A basic FastCGI configuration for lighttpd looks like that::134-135- 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- )143-144- alias.url = (145- "/static/" => "/path/to/your/static/"146- )147-148- url.rewrite-once = (149- "^(/static($|/.*))$" => "$1",150- "^(/.*)$" => "/yourapplication.fcgi$1"151- )152-153-Remember to enable the FastCGI, alias and rewrite modules. This configuration154-binds the application to ``/yourapplication``. If you want the application to155-work in the URL root you have to work around a lighttpd bug with the156-:class:`~werkzeug.contrib.fixers.LighttpdCGIRootFix` middleware.157-158-Make sure to apply it only if you are mounting the application the URL159-root. Also, see the Lighty docs for more information on `FastCGI and Python160-<https://redmine.lighttpd.net/projects/lighttpd/wiki/Docs_ModFastCGI>`_ (note that161-explicitly passing a socket to run() is no longer necessary).162-163-Configuring nginx164------------------165-166-Installing FastCGI applications on nginx is a bit different because by167-default no FastCGI parameters are forwarded.168-169-A basic Flask FastCGI configuration for nginx looks like this::170-171- 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- }180-181-This configuration binds the application to ``/yourapplication``. If you182-want to have it in the URL root it's a bit simpler because you don't183-have to figure out how to calculate ``PATH_INFO`` and ``SCRIPT_NAME``::184-185- 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- }192-193-Running FastCGI Processes194--------------------------195-196-Since nginx and others do not load FastCGI apps, you have to do it by197-yourself. `Supervisor can manage FastCGI processes.198-<http://supervisord.org/configuration.html#fcgi-program-x-section-settings>`_199-You can look around for other FastCGI process managers or write a script200-to run your `.fcgi` file at boot, e.g. using a SysV ``init.d`` script.201-For a temporary solution, you can always run the ``.fcgi`` script inside202-GNU screen. See ``man screen`` for details, and note that this is a203-manual solution which does not persist across system restart::204-205- $ screen206- $ /var/www/yourapplication/yourapplication.fcgi207-208-Debugging209----------210-211-FastCGI deployments tend to be hard to debug on most web servers. Very212-often the only thing the server log tells you is something along the213-lines of "premature end of headers". In order to debug the application214-the only thing that can really give you ideas why it breaks is switching215-to the correct user and executing the application by hand.216-217-This example assumes your application is called `application.fcgi` and218-that your web server user is `www-data`::219-220- $ 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 yourapplication226-227-In this case the error seems to be "yourapplication" not being on the228-python path. Common problems are:229-230-- 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.234-235-.. _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
1+gevent2+======3+4+Prefer using :doc:`gunicorn` or :doc:`uwsgi` with gevent workers rather5+than using `gevent`_ directly. Gunicorn and uWSGI provide much more6+configurable and production-tested servers.7+8+`gevent`_ allows writing asynchronous, coroutine-based code that looks9+like standard synchronous Python. It uses `greenlet`_ to enable task10+switching without writing ``async/await`` or using ``asyncio``.11+12+:doc:`eventlet` is another library that does the same thing. Certain13+dependencies you have, or other considerations, may affect which of the14+two you choose to use.15+16+gevent provides a WSGI server that can handle many connections at once17+instead of one per worker process. You must actually use gevent in your18+own code to see any benefit to using the server.19+20+.. _gevent: https://www.gevent.org/21+.. _greenlet: https://greenlet.readthedocs.io/en/latest/22+23+24+Installing25+----------26+27+When using gevent, greenlet>=1.0 is required, otherwise context locals28+such as ``request`` will not work as expected. When using PyPy,29+PyPy>=7.3.7 is required.30+31+Create a virtualenv, install your application, then install ``gevent``.32+33+.. code-block:: text34+35+ $ cd hello-app36+ $ python -m venv venv37+ $ . venv/bin/activate38+ $ pip install . # install your application39+ $ pip install gevent40+41+42+Running43+-------44+45+To use gevent to serve your application, write a script that imports its46+``WSGIServer``, as well as your app or app factory.47+48+.. code-block:: python49+ :caption: ``wsgi.py``50+51+ from gevent.pywsgi import WSGIServer52+ from hello import create_app53+54+ app = create_app()55+ http_server = WSGIServer(("127.0.0.1", 8000), app)56+ http_server.serve_forever()57+58+.. code-block:: text59+60+ $ python wsgi.py61+62+No output is shown when the server starts.63+64+65+Binding Externally66+------------------67+68+gevent should not be run as root because it would cause your69+application code to run as root, which is not secure. However, this70+means it will not be possible to bind to port 80 or 443. Instead, a71+reverse proxy such as :doc:`nginx` or :doc:`apache-httpd` should be used72+in front of gevent.73+74+You 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't76+do this when using a reverse proxy setup, otherwise it will be possible77+to bypass the proxy.78+79+``0.0.0.0`` is not a valid address to navigate to, you'd use a specific80+IP address in your browser.added:docs/deploying/gunicorn.rst+130 added
1+Gunicorn2+========3+4+`Gunicorn`_ is a pure Python WSGI server with simple configuration and5+multiple worker implementations for performance tuning.6+7+* 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.12+13+This page outlines the basics of running Gunicorn. Be sure to read its14+`documentation`_ and use ``gunicorn --help`` to understand what features15+are available.16+17+.. _Gunicorn: https://gunicorn.org/18+.. _documentation: https://docs.gunicorn.org/19+20+21+Installing22+----------23+24+Gunicorn is easy to install, as it does not require external25+dependencies or compilation. It runs on Windows only under WSL.26+27+Create a virtualenv, install your application, then install28+``gunicorn``.29+30+.. code-block:: text31+32+ $ cd hello-app33+ $ python -m venv venv34+ $ . venv/bin/activate35+ $ pip install . # install your application36+ $ pip install gunicorn37+38+39+Running40+-------41+42+The only required argument to Gunicorn tells it how to load your Flask43+application. The syntax is ``{module_import}:{app_variable}``.44+``module_import`` is the dotted import name to the module with your45+application. ``app_variable`` is the variable with the application. It46+can also be a function call (with any arguments) if you're using the47+app factory pattern.48+49+.. code-block:: text50+51+ # equivalent to 'from hello import app'52+ $ gunicorn -w 4 'hello:app'53+54+ # equivalent to 'from hello import create_app; create_app()'55+ $ gunicorn -w 4 'hello:create_app()'56+57+ 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: x64+65+The ``-w`` option specifies the number of processes to run; a starting66+value could be ``CPU * 2``. The default is only 1 worker, which is67+probably not what you want for the default worker type.68+69+Logs for each request aren't shown by default, only worker info and70+errors are shown. To show access logs on stdout, use the71+``--access-logfile=-`` option.72+73+74+Binding Externally75+------------------76+77+Gunicorn should not be run as root because it would cause your78+application code to run as root, which is not secure. However, this79+means it will not be possible to bind to port 80 or 443. Instead, a80+reverse proxy such as :doc:`nginx` or :doc:`apache-httpd` should be used81+in front of Gunicorn.82+83+You 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,85+otherwise it will be possible to bypass the proxy.86+87+.. code-block:: text88+89+ $ gunicorn -w 4 -b 0.0.0.0 'hello:create_app()'90+ Listening at: http://0.0.0.0:8000 (x)91+92+``0.0.0.0`` is not a valid address to navigate to, you'd use a specific93+IP address in your browser.94+95+96+Async with gevent or eventlet97+-----------------------------98+99+The default sync worker is appropriate for many use cases. If you need100+asynchronous support, Gunicorn provides workers using either `gevent`_101+or `eventlet`_. This is not the same as Python's ``async/await``, or the102+ASGI server spec. You must actually use gevent/eventlet in your own code103+to see any benefit to using the workers.104+105+When using either gevent or eventlet, greenlet>=1.0 is required,106+otherwise context locals such as ``request`` will not work as expected.107+When using PyPy, PyPy>=7.3.7 is required.108+109+To use gevent:110+111+.. code-block:: text112+113+ $ 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: x118+119+To use eventlet:120+121+.. code-block:: text122+123+ $ 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: x128+129+.. _gevent: https://www.gevent.org/130+.. _eventlet: https://eventlet.net/modified:docs/deploying/index.rst+71 added-26 removed
1-Deployment Options2-==================1+Deploying to Production2+=======================3 4-While lightweight and easy to use, **Flask's built-in server is not suitable5-for production** as it doesn't scale well. Some of the options available for6-properly running Flask in production are documented here.4+After developing your application, you'll want to make it available5+publicly to other users. When you're developing locally, you're probably6+using the built-in development server, debugger, and reloader. These7+should not be used in production. Instead, you should use a dedicated8+WSGI server or hosting platform, some of which will be described here.9 8-If you want to deploy your Flask application to a WSGI server not listed here,9-look up the server documentation about how to use a WSGI app with it. Just10-remember that your :class:`Flask` application object is the actual WSGI11-application.10+"Production" means "not development", which applies whether you're11+serving your application publicly to millions of users or privately /12+locally to a single user. **Do not use the development server when13+deploying to production. It is intended for use only during local14+development. It is not designed to be particularly secure, stable, or15+efficient.**16 17+Self-Hosted Options18+-------------------19 14-Hosted options15---------------20+Flask is a WSGI *application*. A WSGI *server* is used to run the21+application, converting incoming HTTP requests to the standard WSGI22+environ, and converting outgoing WSGI responses to HTTP responses.23 17-- `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/>`_24+The primary goal of these docs is to familiarize you with the concepts25+involved in running a WSGI application using a production WSGI server26+and HTTP server. There are many WSGI servers and HTTP servers, with many27+configuration possibilities. The pages below discuss the most common28+servers, and show the basics of running each one. The next section29+discusses platforms that can manage this for you.30 24-Self-hosted options25--------------------31+.. toctree::32+ :maxdepth: 133 34+ gunicorn35+ waitress36+ mod_wsgi37+ uwsgi38+ gevent39+ eventlet40+ asgi41+42+WSGI servers have HTTP servers built-in. However, a dedicated HTTP43+server may be safer, more efficient, or more capable. Putting an HTTP44+server in front of the WSGI server is called a "reverse proxy."45+46 .. toctree::28- :maxdepth: 247+ :maxdepth: 148 30- wsgi-standalone31- uwsgi32- mod_wsgi33- fastcgi34- cgi35- asgi49+ proxy_fix50+ nginx51+ apache-httpd52+53+This list is not exhaustive, and you should evaluate these and other54+servers based on your application's needs. Different servers will have55+different capabilities, configuration, and support.56+57+58+Hosting Platforms59+-----------------60+61+There are many services available for hosting web applications without62+needing to maintain your own server, networking, domain, etc. Some63+services may have a free tier up to a certain time or bandwidth. Many of64+these services use one of the WSGI servers described above, or a similar65+interface. The links below are for some of the most common platforms,66+which have instructions for Flask, WSGI, or Python.67+68+- `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>`_74+75+This list is not exhaustive, and you should evaluate these and other76+services based on your application's needs. Different services will have77+different capabilities, configuration, pricing, and support.78+79+You'll probably need to :doc:`proxy_fix` when using most hosting80+platforms.modified:docs/deploying/mod_wsgi.rst+71 added-182 removed
1-mod_wsgi (Apache)2-=================1+mod_wsgi2+========3 4-If you are using the `Apache`_ webserver, consider using `mod_wsgi`_.4+`mod_wsgi`_ is a WSGI server integrated with the `Apache httpd`_ server.5+The modern `mod_wsgi-express`_ command makes it easy to configure and6+start the server without needing to write Apache httpd configuration.7 6-.. 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.13 8- 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.14+This page outlines the basics of running mod_wsgi-express, not the more15+complex installation and configuration with httpd. Be sure to read the16+`mod_wsgi-express`_, `mod_wsgi`_, and `Apache httpd`_ documentation to17+understand what features are available.18 19+.. _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/22 16-Installing `mod_wsgi`17----------------------23 19-If you don't have `mod_wsgi` installed yet you have to either install it20-using a package manager or compile it yourself. The mod_wsgi21-`installation instructions`_ cover source installations on UNIX systems.24+Installing25+----------26 23-If you are using Ubuntu/Debian you can apt-get it and activate it as24-follows:27+On Linux/Mac, the most straightforward way to install mod_wsgi is to28+install the ``mod_wsgi-standalone`` package, which will compile an29+up-to-date version of Apache httpd as well.30 26-.. sourcecode:: text31+Create a virtualenv, install your application, then install32+``mod_wsgi-standalone``.33 28- $ apt-get install libapache2-mod-wsgi-py334+.. code-block:: text35 30-If you are using a yum based distribution (Fedora, OpenSUSE, etc..) you31-can install it as follows:36+ $ cd hello-app37+ $ python -m venv venv38+ $ . venv/bin/activate39+ $ pip install . # install your application40+ $ pip install mod_wsgi-standalone41 33-.. sourcecode:: text42+If 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 its45+development headers are not available. How to install them depends on46+what OS and package manager you use.47 35- $ yum install mod_wsgi48+.. code-block:: text49 37-On FreeBSD install `mod_wsgi` by compiling the `www/mod_wsgi` port or by38-using pkg_add:50+ $ pip install mod_wsgi51 40-.. sourcecode:: text52 42- $ pkg install ap24-py37-mod_wsgi53+Running54+-------55 44-If you are using pkgsrc you can install `mod_wsgi` by compiling the45-`www/ap2-wsgi` package.56+The only argument to ``mod_wsgi-express`` specifies a script containing57+your Flask application, which must be called ``application``. You can58+write a small script to import your app with this name, or to create it59+if using the app factory pattern.60 47-If you encounter segfaulting child processes after the first apache48-reload you can safely ignore them. Just restart the server.61+.. code-block:: python62+ :caption: ``wsgi.py``63 50-Creating a `.wsgi` file51------------------------64+ from hello import app65 53-To run your application you need a :file:`yourapplication.wsgi` file.54-This file contains the code `mod_wsgi` is executing on startup55-to get the application object. The object called `application`56-in that file is then used as application.66+ application = app67 58-For most applications the following file should be sufficient::68+.. code-block:: python69+ :caption: ``wsgi.py``70 60- from yourapplication import app as application71+ from hello import create_app72 62-If a factory function is used in a :file:`__init__.py` file, then the function should be imported::63-64- from yourapplication import create_app73 application = create_app()74 67-If you don't have a factory function for application creation but a singleton68-instance you can directly import that one as `application`.75+Now run the ``mod_wsgi-express start-server`` command.76 70-Store that file somewhere that you will find it again (e.g.:71-:file:`/var/www/yourapplication`) and make sure that `yourapplication` and all72-the libraries that are in use are on the python load path. If you don't73-want to install it system wide consider using a `virtual python`_74-instance. Keep in mind that you will have to actually install your75-application into the virtualenv as well. Alternatively there is the76-option to just patch the path in the ``.wsgi`` file before the import::77+.. code-block:: text78 78- import sys79- sys.path.insert(0, '/path/to/the/application')79+ $ mod_wsgi-express start-server wsgi.py --processes 480 81-Configuring Apache82-------------------81+The ``--processes`` option specifies the number of worker processes to82+run; a starting value could be ``CPU * 2``.83 84-The last thing you have to do is to create an Apache configuration file85-for your application. In this example we are telling `mod_wsgi` to86-execute the application under a different user for security reasons:84+Logs for each request aren't show in the terminal. If an error occurs,85+its information is written to the error log file shown when starting the86+server.87 88-.. sourcecode:: apache88 90- <VirtualHost *>91- ServerName example.com89+Binding Externally90+------------------91 93- WSGIDaemonProcess yourapplication user=user1 group=group1 threads=594- WSGIScriptAlias / /var/www/yourapplication/yourapplication.wsgi92+Unlike the other WSGI servers in these docs, mod_wsgi can be run as93+root to bind to privileged ports like 80 and 443. However, it must be94+configured to drop permissions to a different user and group for the95+worker processes.96 96- <Directory /var/www/yourapplication>97- WSGIProcessGroup yourapplication98- WSGIApplicationGroup %{GLOBAL}99- Order deny,allow100- Allow from all101- </Directory>102- </VirtualHost>97+For example, if you created a ``hello`` user and group, you should98+install your virtualenv and application as that user, then tell99+mod_wsgi to drop to that user after starting.100 104-Note: WSGIDaemonProcess isn't implemented in Windows and Apache will105-refuse to run with the above configuration. On a Windows system, eliminate those lines:101+.. code-block:: text102 107-.. sourcecode:: apache108-109- <VirtualHost *>110- ServerName example.com111- WSGIScriptAlias / C:\yourdir\yourapp.wsgi112- <Directory C:\yourdir>113- Order deny,allow114- Allow from all115- </Directory>116- </VirtualHost>117-118-Note: There have been some changes in access control configuration119-for `Apache 2.4`_.120-121-.. _Apache 2.4: https://httpd.apache.org/docs/trunk/upgrading.html122-123-Most notably, the syntax for directory permissions has changed from httpd 2.2124-125-.. sourcecode:: apache126-127- Order allow,deny128- Allow from all129-130-to httpd 2.4 syntax131-132-.. sourcecode:: apache133-134- Require all granted135-136-137-For more information consult the `mod_wsgi documentation`_.138-139-.. _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.html143-144-Troubleshooting145----------------146-147-If your application does not run, follow this guide to troubleshoot:148-149-**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.154-155-**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)161-162-**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``:167-168- .. sourcecode:: apache169-170- WSGIRestrictStdout Off171-172- Alternatively you can also replace the standard out in the .wsgi file173- with a different stream::174-175- import sys176- sys.stdout = sys.stderr177-178-**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.183-184- 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.187-188-Support for Automatic Reloading189--------------------------------190-191-To help deployment tools you can activate support for automatic192-reloading. Whenever something changes the ``.wsgi`` file, `mod_wsgi` will193-reload all the daemon processes for us.194-195-For that, just add the following directive to your `Directory` section:196-197-.. sourcecode:: apache198-199- WSGIScriptReloading On200-201-Working with Virtual Environments202----------------------------------203-204-Virtual environments have the advantage that they never install the205-required dependencies system wide so you have a better control over what206-is used where. If you want to use a virtual environment with mod_wsgi207-you have to modify your ``.wsgi`` file slightly.208-209-Add the following lines to the top of your ``.wsgi`` file::210-211- activate_this = '/path/to/env/bin/activate_this.py'212- with open(activate_this) as file_:213- exec(file_.read(), dict(__file__=activate_this))214-215-This sets up the load paths according to the settings of the virtual216-environment. 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 4added:docs/deploying/nginx.rst+69 added
1+nginx2+=====3+4+`nginx`_ is a fast, production level HTTP server. When serving your5+application with one of the WSGI servers listed in :doc:`index`, it is6+often good or necessary to put a dedicated HTTP server in front of it.7+This "reverse proxy" can handle incoming requests, TLS, and other8+security and performance concerns better than the WSGI server.9+10+Nginx can be installed using your system package manager, or a pre-built11+executable for Windows. Installing and running Nginx itself is outside12+the scope of this doc. This page outlines the basics of configuring13+Nginx to proxy your application. Be sure to read its documentation to14+understand what features are available.15+16+.. _nginx: https://nginx.org/17+18+19+Domain Name20+-----------21+22+Acquiring and configuring a domain name is outside the scope of this23+doc. In general, you will buy a domain name from a registrar, pay for24+server space with a hosting provider, and then point your registrar25+at the hosting provider's name servers.26+27+To simulate this, you can also edit your ``hosts`` file, located at28+``/etc/hosts`` on Linux. Add a line that associates a name with the29+local IP.30+31+Modern Linux systems may be configured to treat any domain name that32+ends with ``.localhost`` like this without adding it to the ``hosts``33+file.34+35+.. code-block:: python36+ :caption: ``/etc/hosts``37+38+ 127.0.0.1 hello.localhost39+40+41+Configuration42+-------------43+44+The nginx configuration is located at ``/etc/nginx/nginx.conf`` on45+Linux. It may be different depending on your operating system. Check the46+docs and look for ``nginx.conf``.47+48+Remove or comment out any existing ``server`` section. Add a ``server``49+section and use the ``proxy_pass`` directive to point to the address the50+WSGI server is listening on. We'll assume the WSGI server is listening51+locally at ``http://127.0.0.1:8000``.52+53+.. code-block:: nginx54+ :caption: ``/etc/nginx.conf``55+56+ server {57+ listen 80;58+ server_name _;59+60+ 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+ }68+69+Then :doc:`proxy_fix` so that your application uses these headers.added:docs/deploying/proxy_fix.rst+33 added
1+Tell Flask it is Behind a Proxy2+===============================3+4+When using a reverse proxy, or many Python hosting platforms, the proxy5+will intercept and forward all external requests to the local WSGI6+server.7+8+From the WSGI server and Flask application's perspectives, requests are9+now coming from the HTTP server to the local address, rather than from10+the remote address to the external server address.11+12+HTTP servers should set ``X-Forwarded-`` headers to pass on the real13+values to the application. The application can then be told to trust and14+use those values by wrapping it with the15+:doc:`werkzeug:middleware/proxy_fix` middleware provided by Werkzeug.16+17+This middleware should only be used if the application is actually18+behind a proxy, and should be configured with the number of proxies that19+are chained in front of it. Not all proxies set all the headers. Since20+incoming headers can be faked, you must set how many proxies are setting21+each header so the middleware knows what to trust.22+23+.. code-block:: python24+25+ from werkzeug.middleware.proxy_fix import ProxyFix26+27+ app.wsgi_app = ProxyFix(28+ app.wsgi_app, x_for=1, x_proto=1, x_host=1, x_prefix=129+ )30+31+Remember, only apply this middleware if you are behind a proxy, and set32+the correct number of proxies that set each header. It can be a security33+issue if you get this configuration wrong.modified:docs/deploying/uwsgi.rst+125 added-51 removed
1 uWSGI2 =====3 4-uWSGI is a deployment option on servers like `nginx`_, `lighttpd`_, and5-`cherokee`_; see :doc:`fastcgi` and :doc:`wsgi-standalone` for other options.6-To use your WSGI application with uWSGI protocol you will need a uWSGI server7-first. uWSGI is both a protocol and an application server; the application8-server can serve uWSGI, FastCGI, and HTTP protocols.4+`uWSGI`_ is a fast, compiled server suite with extensive configuration5+and capabilities beyond a basic server.6 10-The most popular uWSGI server is `uwsgi`_, which we will use for this11-guide. 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.12 13-.. admonition:: Watch Out13+This page outlines the basics of running uWSGI. Be sure to read its14+documentation to understand what features are available.15 15- 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/17 21-Starting your app with uwsgi22-----------------------------18 24-`uwsgi` is designed to operate on WSGI callables found in python modules.19+Installing20+----------21 26-Given a flask application in myapp.py, use the following command:22+uWSGI has multiple ways to install it. The most straightforward is to23+install the ``pyuwsgi`` package, which provides precompiled wheels for24+common platforms. However, it does not provide SSL support, which can be25+provided with a reverse proxy instead.26 28-.. sourcecode:: text27+Create a virtualenv, install your application, then install ``pyuwsgi``.28 30- $ uwsgi -s /tmp/yourapplication.sock --manage-script-name --mount /yourapplication=myapp:app29+.. code-block:: text30 32-The ``--manage-script-name`` will move the handling of ``SCRIPT_NAME``33-to uwsgi, since it is smarter about that.34-It is used together with the ``--mount`` directive which will make35-requests to ``/yourapplication`` be directed to ``myapp:app``.36-If your application is accessible at root level, you can use a37-single ``/`` instead of ``/yourapplication``. ``myapp`` refers to the name of38-the file of your flask application (without extension) or the module which39-provides ``app``. ``app`` is the callable inside of your application (usually40-the line reads ``app = Flask(__name__)``).31+ $ cd hello-app32+ $ python -m venv venv33+ $ . venv/bin/activate34+ $ pip install . # install your application35+ $ pip install pyuwsgi36 42-If you want to deploy your flask application inside of a virtual environment,43-you need to also add ``--virtualenv /path/to/virtual/environment``. You might44-also need to add ``--plugin python`` or ``--plugin python3`` depending on which45-python version you use for your project.37+If you have a compiler available, you can install the ``uwsgi`` package38+instead. Or install the ``pyuwsgi`` package from sdist instead of wheel.39+Either method will include SSL support.40 47-Configuring nginx41+.. code-block:: text42+43+ $ pip install uwsgi44+45+ # or46+ $ pip install --no-binary pyuwsgi pyuwsgi47+48+49+Running50+-------51+52+The most basic way to run uWSGI is to tell it to start an HTTP server53+and import your application.54+55+.. code-block:: text56+57+ $ uwsgi --http 127.0.0.1:8000 --master -p 4 -w hello:app58+59+ *** 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)68+69+If you're using the app factory pattern, you'll need to create a small70+Python file to create the app, then point uWSGI at that.71+72+.. code-block:: python73+ :caption: ``wsgi.py``74+75+ from hello import create_app76+77+ app = create_app()78+79+.. code-block:: text80+81+ $ uwsgi --http 127.0.0.1:8000 --master -p 4 -w wsgi:app82+83+The ``--http`` option starts an HTTP server at 127.0.0.1 port 8000. The84+``--master`` option specifies the standard worker manager. The ``-p``85+option starts 4 worker processes; a starting value could be ``CPU * 2``.86+The ``-w`` option tells uWSGI how to import your application87+88+89+Binding Externally90+------------------91+92+uWSGI should not be run as root with the configuration shown in this doc93+because it would cause your application code to run as root, which is94+not secure. However, this means it will not be possible to bind to port95+80 or 443. Instead, a reverse proxy such as :doc:`nginx` or96+:doc:`apache-httpd` should be used in front of uWSGI. It is possible to97+run uWSGI as root securely, but that is beyond the scope of this doc.98+99+uWSGI has optimized integration with `Nginx uWSGI`_ and100+`Apache mod_proxy_uwsgi`_, and possibly other servers, instead of using101+a standard HTTP proxy. That configuration is beyond the scope of this102+doc, see the links for more information.103+104+.. _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-uwsgi106+107+You 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 proxy109+setup, otherwise it will be possible to bypass the proxy.110+111+.. code-block:: text112+113+ $ uwsgi --http 0.0.0.0:8000 --master -p 4 -w wsgi:app114+115+``0.0.0.0`` is not a valid address to navigate to, you'd use a specific116+IP address in your browser.117+118+119+Async with gevent120 -----------------121 50-A basic flask nginx configuration looks like this::122+The default sync worker is appropriate for many use cases. If you need123+asynchronous support, uWSGI provides a `gevent`_ worker. This is not the124+same as Python's ``async/await``, or the ASGI server spec. You must125+actually use gevent in your own code to see any benefit to using the126+worker.127 52- 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- }128+When using gevent, greenlet>=1.0 is required, otherwise context locals129+such as ``request`` will not work as expected. When using PyPy,130+PyPy>=7.3.7 is required.131 59-This configuration binds the application to ``/yourapplication``. If you want60-to have it in the URL root its a bit simpler::132+.. code-block:: text133 62- 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:app135 68-.. _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] ***143+144+145+.. _gevent: https://www.gevent.org/added:docs/deploying/waitress.rst+75 added
1+Waitress2+========3+4+`Waitress`_ is a pure Python WSGI server.5+6+* 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.13+14+This page outlines the basics of running Waitress. Be sure to read its15+documentation and ``waitress-serve --help`` to understand what features16+are available.17+18+.. _Waitress: https://docs.pylonsproject.org/projects/waitress/19+20+21+Installing22+----------23+24+Create a virtualenv, install your application, then install25+``waitress``.26+27+.. code-block:: text28+29+ $ cd hello-app30+ $ python -m venv venv31+ $ . venv/bin/activate32+ $ pip install . # install your application33+ $ pip install waitress34+35+36+Running37+-------38+39+The only required argument to ``waitress-serve`` tells it how to load40+your Flask application. The syntax is ``{module}:{app}``. ``module`` is41+the dotted import name to the module with your application. ``app`` is42+the variable with the application. If you're using the app factory43+pattern, use ``--call {module}:{factory}`` instead.44+45+.. code-block:: text46+47+ # equivalent to 'from hello import app'48+ $ waitress-serve hello:app --host 127.0.0.149+50+ # equivalent to 'from hello import create_app; create_app()'51+ $ waitress-serve --call hello:create_app --host 127.0.0.152+53+ Serving on http://127.0.0.1:808054+55+The ``--host`` option binds the server to local ``127.0.0.1`` only.56+57+Logs for each request aren't shown, only errors are shown. Logging can58+be configured through the Python interface instead of the command line.59+60+61+Binding Externally62+------------------63+64+Waitress should not be run as root because it would cause your65+application code to run as root, which is not secure. However, this66+means it will not be possible to bind to port 80 or 443. Instead, a67+reverse proxy such as :doc:`nginx` or :doc:`apache-httpd` should be used68+in front of Waitress.69+70+You can bind to all external IPs on a non-privileged port by not71+specifying the ``--host`` option. Don't do this when using a revers72+proxy setup, otherwise it will be possible to bypass the proxy.73+74+``0.0.0.0`` is not a valid address to navigate to, you'd use a specific75+IP address in your browser.deleted:docs/deploying/wsgi-standalone.rst-262 removed
1-Standalone WSGI Servers2-=======================3-4-Most WSGI servers also provide HTTP servers, so they can run a WSGI5-application and make it available externally.6-7-It may still be a good idea to run the server behind a dedicated HTTP8-server such as Apache or Nginx. See :ref:`deploying-proxy-setups` if you9-run into issues with that.10-11-12-Gunicorn13---------14-15-`Gunicorn`_ is a WSGI and HTTP server for UNIX. To run a Flask16-application, tell Gunicorn how to import your Flask app object.17-18-.. code-block:: text19-20- $ gunicorn -w 4 -b 0.0.0.0:5000 your_project:app21-22-The ``-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 port24-5000.25-26-Gunicorn provides many options for configuring the server, either27-through a configuration file or with command line options. Use28-``gunicorn --help`` or see the docs for more information.29-30-The command expects the name of your module or package to import and31-the application instance within the module. If you use the application32-factory pattern, you can pass a call to that.33-34-.. code-block:: text35-36- $ gunicorn -w 4 -b 0.0.0.0:5000 "myproject:create_app()"37-38-39-Async with Gevent or Eventlet40-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~41-42-The default sync worker is appropriate for many use cases. If you need43-asynchronous support, Gunicorn provides workers using either `gevent`_44-or `eventlet`_. This is not the same as Python's ``async/await``, or the45-ASGI server spec.46-47-When using either gevent or eventlet, greenlet>=1.0 is required,48-otherwise context locals such as ``request`` will not work as expected.49-When using PyPy, PyPy>=7.3.7 is required.50-51-To use gevent:52-53-.. code-block:: text54-55- $ gunicorn -k gevent -b 0.0.0.0:5000 your_project:app56-57-To use eventlet:58-59-.. code-block:: text60-61- $ gunicorn -k eventlet -b 0.0.0.0:5000 your_project:app62-63-64-.. _Gunicorn: https://gunicorn.org/65-.. _gevent: http://www.gevent.org/66-.. _eventlet: https://eventlet.net/67-.. _greenlet: https://greenlet.readthedocs.io/en/latest/68-69-70-uWSGI71------72-73-`uWSGI`_ is a fast application server written in C. It is very74-configurable, which makes it more complicated to setup than Gunicorn.75-It also provides many other utilities for writing robust web76-applications. To run a Flask application, tell uWSGI how to import77-your Flask app object.78-79-.. code-block:: text80-81- $ uwsgi --master -p 4 --http 0.0.0.0:5000 -w your_project:app82-83-The ``-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 port85-5000.86-87-uWSGI has optimized integration with Nginx and Apache instead of using88-a standard HTTP proxy. See :doc:`configuring uWSGI and Nginx <uwsgi>`.89-90-91-Async with Gevent92-~~~~~~~~~~~~~~~~~93-94-The default sync worker is appropriate for many use cases. If you need95-asynchronous support, uWSGI provides workers using `gevent`_. It also96-supports other async modes, see the docs for more information. This is97-not the same as Python's ``async/await``, or the ASGI server spec.98-99-When using gevent, greenlet>=1.0 is required, otherwise context locals100-such as ``request`` will not work as expected. When using PyPy,101-PyPy>=7.3.7 is required.102-103-.. code-block:: text104-105- $ uwsgi --master --gevent 100 --http 0.0.0.0:5000 -w your_project:app106-107-.. _uWSGI: https://uwsgi-docs.readthedocs.io/en/latest/108-109-110-Gevent111-------112-113-Prefer using `Gunicorn`_ with Gevent workers rather than using Gevent114-directly. Gunicorn provides a much more configurable and115-production-tested server. See the section on Gunicorn above.116-117-`Gevent`_ allows writing asynchronous, coroutine-based code that looks118-like standard synchronous Python. It uses `greenlet`_ to enable task119-switching without writing ``async/await`` or using ``asyncio``.120-121-It provides a WSGI server that can handle many connections at once122-instead of one per worker process.123-124-`Eventlet`_, described below, is another library that does the same125-thing. Certain dependencies you have, or other consideration, may affect126-which of the two you choose to use127-128-To use gevent to serve your application, import its ``WSGIServer`` and129-use it to run your ``app``.130-131-.. code-block:: python132-133- from gevent.pywsgi import WSGIServer134- from your_project import app135-136- http_server = WSGIServer(("", 5000), app)137- http_server.serve_forever()138-139-140-Eventlet141---------142-143-Prefer using `Gunicorn`_ with Eventlet workers rather than using144-Eventlet directly. Gunicorn provides a much more configurable and145-production-tested server. See the section on Gunicorn above.146-147-`Eventlet`_ allows writing asynchronous, coroutine-based code that looks148-like standard synchronous Python. It uses `greenlet`_ to enable task149-switching without writing ``async/await`` or using ``asyncio``.150-151-It provides a WSGI server that can handle many connections at once152-instead of one per worker process.153-154-`Gevent`_, described above, is another library that does the same155-thing. Certain dependencies you have, or other consideration, may affect156-which of the two you choose to use157-158-To use eventlet to serve your application, import its ``wsgi.server``159-and use it to run your ``app``.160-161-.. code-block:: python162-163- import eventlet164- from eventlet import wsgi165- from your_project import app166-167- wsgi.server(eventlet.listen(("", 5000), app)168-169-170-Twisted Web171------------172-173-`Twisted Web`_ is the web server shipped with `Twisted`_, a mature,174-non-blocking event-driven networking library. Twisted Web comes with a175-standard WSGI container which can be controlled from the command line using176-the ``twistd`` utility:177-178-.. code-block:: text179-180- $ twistd web --wsgi myproject.app181-182-This example will run a Flask application called ``app`` from a module named183-``myproject``.184-185-Twisted Web supports many flags and options, and the ``twistd`` utility does186-as well; see ``twistd -h`` and ``twistd web -h`` for more information. For187-example, to run a Twisted Web server in the foreground, on port 8080, with an188-application from ``myproject``:189-190-.. code-block:: text191-192- $ twistd -n web --port tcp:8080 --wsgi myproject.app193-194-.. _Twisted: https://twistedmatrix.com/trac/195-.. _Twisted Web: https://twistedmatrix.com/trac/wiki/TwistedWeb196-197-198-.. _deploying-proxy-setups:199-200-Proxy Setups201-------------202-203-If you deploy your application using one of these servers behind an HTTP proxy204-you will need to rewrite a few headers in order for the application to work.205-The two problematic values in the WSGI environment usually are ``REMOTE_ADDR``206-and ``HTTP_HOST``. You can configure your httpd to pass these headers, or you207-can fix them in middleware. Werkzeug ships a fixer that will solve some common208-setups, but you might want to write your own WSGI middleware for specific209-setups.210-211-Here's a simple nginx configuration which proxies to an application served on212-localhost at port 8000, setting appropriate headers:213-214-.. sourcecode:: nginx215-216- server {217- listen 80;218-219- server_name _;220-221- access_log /var/log/nginx/access.log;222- error_log /var/log/nginx/error.log;223-224- location / {225- proxy_pass http://127.0.0.1:8000/;226- proxy_redirect off;227-228- 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- }234-235-If your httpd is not providing these headers, the most common setup invokes the236-host being set from ``X-Forwarded-Host`` and the remote address from237-``X-Forwarded-For``::238-239- from werkzeug.middleware.proxy_fix import ProxyFix240- app.wsgi_app = ProxyFix(app.wsgi_app, x_proto=1, x_host=1)241-242-.. admonition:: Trusting Headers243-244- 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.247-248-If you want to rewrite the headers from another header, you might want to249-use a fixer like this::250-251- class CustomProxyFix(object):252-253- def __init__(self, app):254- self.app = app255-256- 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)261-262- app.wsgi_app = CustomProxyFix(app.wsgi_app)modified:docs/async-await.rst+2 added-2 removed
68 unmodified lines69 If you wish to use background tasks it is best to use a task queue to70 trigger background work, rather than spawn tasks in a view71 function. With that in mind you can spawn asyncio tasks by serving72 Flask with an ASGI server and utilising the asgiref WsgiToAsgi adapter73-as described in :ref:`asgi`. This works as the adapter creates an74-event loop that runs continually.73+as described in :doc:`deploying/asgi`. This works as the adapter creates74+an event loop that runs continually.75 76 77 When to use Quart instead78 -------------------------53 unmodified lines