简体   繁体   中英

Running Python Web Server

I am using python with Flask framework. As you may know that when you run the script, It will run in foreground. Like this:

python hello.py
 * Running on http://localhost:5000/

How can I run a python web server to run python script in background like what Apache Web Server does.

Thanks

If all you want is the web server process to detach from your terminal so you can keep using the terminal, then just send it to the background (like any other command):

python hello.py &

Or use more detailed output redirection:

python hello.py > /dev/null 2>&1 &

But note that (as stated in Fask documentation as well) Flask's default web server is not written for production and is meant to be used for development. Other WSGI servers (like Apache with mod_wsgi, Gunicorn, etc.) are suggested for production environment.

Apache is easier to manage on production server since most distro packages provide scripts to start/stop/monitor the Apache process. So all your need to do is install/enable mod_wsgi and configure the server to run your app.

Gunicorn is easy to start with .

I'll include samples to run the app in question using both Gunicorn and Apache, however please note that these samples are not the best configurations for a production environment.

Gunicorn

Assuming you have your hello.py file module, and the Flask object is stored in a variable named app , you can run the app by running:

sudo pip install gunicorn
gunicorn --daemon --workers 4 --bind 0.0.0.0:8000 hello:app

Now this process is detached from your terminal (--daemon option). The above command starts gunicorn listening on a non-privileged port (8000). If you want to listen on a privileged port (like 80), you can drop privileges for worker processes:

sudo gunicorn --daemon --workers 4 --bind 0.0.0.0:80 --user www-data --group www-data hello:app 

However if you need to have more control over the process, a process management tool like Supervisord or Perp can help.

Apache mod_wsgi

If you're more convenient with Apache, install and enable mod_wsgi , then add a VirtualHost to point to your application.

Here is a sample config for the app and Apache configurations to run it.

Say we have hello.py where we have the Flask app, so save it to a proper place (and provide proper permissions). Here for example we use /var/www/myapp but it's just for simplicity.

# file: /var/www/myapp/hello.py
from flask import Flask

application = Flask(__name__)

@application.route("/")
def index():
    return "Hello!"

Note that the Flask object is stored in application variable, since mod_wsgi looks for the WSGI app object named application in the specified module.

Then install and enable mod_wsgi , as an example on Ubuntu:

sudo apt-get install apache2 libapache2-mod-wsgi
sudo a2enmod wsgi

Now add a VirtualHost to point to your WSGI app.

# file: /etc/apache2/sites-available/101-myapp.conf
<Directory /var/www/myapp>
    Order allow,deny
    Allow from all
</Directory>

<VirtualHost *:80>
        ServerName myapp.local
        ServerAdmin webmaster@localhost
        DocumentRoot /var/www/myapp
        WSGIDaemonProcess www-data processes=2 threads=15 display-name=%{GROUP}
        WSGIProcessGroup www-data
        WSGIScriptAlias / /var/www/myapp/hello.py
        ErrorLog ${APACHE_LOG_DIR}/myapp-error.log
        CustomLog ${APACHE_LOG_DIR}/myapp-access.log combined
</VirtualHost>

Now enable the host:

sudo a2ensite 101-myapp
sudo service apache2 reload

Note in the above example, I used myapp.local as the ServerName, so you'd need to change it to a name that can be resolved with DNS (or add myapp.local to your /etc/hosts if you're testing on your devbox).

Flask deployment documentation provides more details regarding installing required modules or using virtualenv to run the app.

See mod_wsgi docs for more details.

Both of the above solutions can be used to run other WSGI apps, not just the ones using Flask.

[EDIT] I misread the question. I thought you wanted a production ready server, but in case you're still in the testing phase, I normally use screen (here's a tutorial ). In any case it's really good to learn screen, since it will come in handy in a lot of server related tasks. [/EDIT]

I just set up a production server for flask using nginx and uwsgi using this tutorial . Assuming you're on Ubuntu 14.04, it's basically:

first install nginx:

sudo add-apt-repository ppa:nginx/stable
sudo apt-get update && sudo apt-get upgrade
sudo apt-get install nginx

check if nginx is running by going to the ip-address in the browser and checking if you see the nginx welcome screen.

Then install uwsgi:

sudo apt-get install build-essential python python-dev
pip install uwsgi

remove the default nginx config:

sudo rm /etc/nginx/sites-enabled/default

create an nginx config file for you website called something like yourwebsite_nginx.conf (adjust the path to point to your website folder):

server {
    listen      80;
    server_name localhost;
    charset     utf-8;
    client_max_body_size 75M;
    location / { try_files $uri @yourapplication; }
    location @yourapplication {
        include uwsgi_params;
        uwsgi_pass unix:/var/www/yourwebsite/yourwebsite_uwsgi.sock;
    }
}

symlink this file and restart nginx:

sudo ln -s /var/www/yourwebsite/yourwebsite_nginx.conf /etc/nginx/conf.d/
sudo service nginx restart

configure uwsgi to create the .sock file to which you point in the nginx config ( /var/www/yourwebsite/yourwebsite_uwsgi.sock ). Create a file in /var/www/yourwebsite/yourwebsite_uwsgi.ini for this, containing:

[uwsgi]
#application's base folder
base = /var/www/yourwebsite

#python module to import
app = yourappfile  # yourappfile should have the name of the file in which you do the `app = Flask(__name__)`
module = %(app)

home = %(base)/venv  # This should point to your virtualenv python install
pythonpath = %(base)

#socket file's location
socket = /var/www/yourwebsite/%n.sock

#permissions for the socket file
chmod-socket    = 666

#the variable that holds a flask application inside the module imported at line #6
callable = app  # This is normally `app`

The start uwsgi:

uwsgi --ini /var/www/yourwebsite/yourwebsite_uwsgi.ini

This is it in a nutshell. But check the tutorial I linked to above, it explains things in slower, easier steps.

You can take a look at the Flask documentation for deploying your application using Apache and mod_wsgi. There's also an additional snippet that someone wrote who mentioned that the Flask docs didn't work perfectly for them.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM