Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
240 views
in Technique[技术] by (71.8m points)

python - Is the server bundled with Flask safe to use in production?

Is the server bundled with Flask safe for deployment in a production environment? If not, what should I use to deploy Flask in production?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

No. The bundled server is a development server. It's not designed with production environments in mind.

  • It will not handle more than one request at a time by default.
  • If you leave debug mode on and an error pops up, it opens up a shell that allows for arbitrary code to be executed on your server (think os.system('rm -rf /')).
  • The development server doesn't scale well.

Flask uses Werkzeug's development server, and the documentation says the same thing:

The development server is not intended to be used on production systems. It was designed especially for development purposes and performs poorly under high load. For deployment setups have a look at the Application Deployment pages.

The recommended approach is to use a production WSGI server to run your Flask application. There's a whole section dedicated to deployment in the docs: Deployment Options.

Deploying your application is as simple as installing a WSGI server like uWSGI or gunicorn and running that instead of Flask's development server:

gunicorn -w 4 -b 127.0.0.1:4000 myproject:app

If you are serving any static assets like images or videos, need low-level caching, or have higher concurrency demands, it's recommended to use a webserver like nginx and have it handle all of your requests.

In crappy ASCII form:

                +----------+
                | Client 2 |
                +----------+
                      |
                      V 
+----------+      +-------+      +----------+
| Client 1 |----->| nginx |<-----| Client 3 |
+----------+      +-------+      +----------+
                      ^
                      |
                      V
           /--------------------
           | useful nginx stuff |
           | like asset serving |
           | and rate limiting  |
           --------------------/
                      |
                      V
               +-------------+
               | WSGI server |
               +-------------+

To actually run the WSGI server process, you can use Supervisor. It automatically restarts the server if it fails for some reason, keeps logs, and runs as a daemon so your service starts when the server boots.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...