导航菜单
首页 >  How To Use Templates in a Flask Application DigitalOcean  > How To Deploy a Flask Application on an Ubuntu VPS

How To Deploy a Flask Application on an Ubuntu VPS

TutorialHow To Deploy a Flask Application on an Ubuntu VPSPublished on July 4, 2013ApachePythonUbuntuPython Frameworksauthor

Kundan Singh

How To Deploy a Flask Application on an Ubuntu VPSNot using Ubuntu 12.04?Choose a different version or distribution.Ubuntu 12.04What the Highlighting Means

The lines that the user needs to enter or customize will be highlighed in this tutorial! The rest should mostly be copy-and-pastable.

Introduction

Flask is a micro-framework written in Python and based on the Werkzeug and Jinja2 template engine for developing web applications. It is intended for developing web apps quickly.

Setup

You need to have Apache already installed and running on your VPS. If this is not the case, follow Step One of our article on installing a LAMP stack on Ubuntu.

Step One— Install and Enable mod_wsgi

WSGI (Web Server Gateway Interface) is an interface between web servers and web apps for python. Mod_wsgi is an Apache HTTP server mod that enables Apache to serve Flask applications.

Open terminal and type the following command to install mod_wsgi:

sudo apt-get install libapache2-mod-wsgi python-dev

To enable mod_wsgi, run the following command:

sudo a2enmod wsgi Step Two – Creating a Flask App

In this step, we will create a flask app. We will place our app in the /var/www directory.

Use the following command to move to the /var/www directory:

cd /var/www

Create the application directory structure using mkdir as shown. Replace "FlaskApp" with the name you would like to give your application. Create the initial directory FlaskApp by giving following command:

sudo mkdir FlaskApp

Move inside this directory using the following command:

cd FlaskApp

Create another directory FlaskApp by giving following command:

sudo mkdir FlaskApp

Then, move inside this directory and create two subdirectories named static and templates using the following commands:

cd FlaskAppsudo mkdir static templates

Your directory structure should now look like this:

|----FlaskApp|---------FlaskApp|--------------static|--------------templates

Now, create the __init__.py file that will contain the flask application logic.

sudo nano __init__.py

Add following logic to the file:

from flask import Flaskapp = Flask(__name__)@app.route("/")def hello():return "Hello, I love Digital Ocean!"if __name__ == "__main__":app.run()

Save and close the file.

Step Three – Install Flask

Setting up a virtual environment will keep the application and its dependencies isolated from the main system. Changes to it will not affect the cloud server's system configurations.

In this step, we will create a virtual environment for our flask application.

We will use pip to install virtualenv and Flask. If pip is not installed, install it on Ubuntu through apt-get.

sudo apt-get install python-pip

If virtualenv is not installed, use pip to install it using following command:

sudo pip install virtualenv

Give the following command (where venv is the name you would like to give your temporary environment):

sudo virtualenv venv

Now, install Flask in that environment by activating the virtual environment with the following command:

source venv/bin/activate

Give this command to install Flask inside:

sudo pip install Flask

Next, run the following command to test if the installation is successful and the app is running:

sudo python __init__.py

It should display “Running on http://localhost:5000/” or "Running on http://127.0.0.1:5000/". If you see this message, you have successfully configured the app.

To deactivate the environment, give the following command:

deactivateStep Four – Configure and Enable a New Virtual Host

Issue the following command in your terminal:

sudo nano /etc/apache2/sites-available/FlaskApp

NOTE: Newer versions of Ubuntu (13.10+) require a ".conf" extension for VirtualHost files -- run the following command instead:

sudo nano /etc/apache2/sites-available/FlaskApp.conf

Add the following lines of code to the file to configure the virtual host. Be sure to change the ServerName to your domain or cloud server's IP address:

ServerName mywebsite.comServerAdmin admin@mywebsite.comWSGIScriptAlias / /var/www/FlaskApp/flaskapp.wsgiOrder allow,denyAllow from allAlias /static /var/www/FlaskApp/FlaskApp/staticOrder allow,denyAllow from allErrorLog ${APACHE_LOG_DIR}/error.logLogLevel warnCustomLog ${APACHE_LOG_DIR}/access.log combined

Save and close the file.

Enable the virtual host with the following command:

sudo a2ensite FlaskAppStep Five – Create the .wsgi File

Apache uses the .wsgi file to serve the Flask app. Move to the /var/www/FlaskApp directory and create a file named flaskapp.wsgi with following commands:

cd /var/www/FlaskAppsudo nano flaskapp.wsgi

Add the following lines of code to the flaskapp.wsgi file:

#!/usr/bin/pythonimport sysimport logginglogging.basicConfig(stream=sys.stderr)sys.path.insert(0,"/var/www/FlaskApp/")from FlaskApp import app as applicationapplication.secret_key = 'Add your secret key'

Now your directory structure should look like this:

|--------FlaskApp|----------------FlaskApp|-----------------------static|-----------------------templates|-----------------------venv|-----------------------__init__.py|----------------flaskapp.wsgiStep Six – Restart Apache

Restart Apache with the following command to apply the changes:

sudo service apache2 restart

You may see a message similar to the following:

Could not reliably determine the VPS's fully qualified domain name, using 127.0.0.1 for ServerName

This message is just a warning, and you will be able to access your virtual host without any further issues. To view your application, open your browser and navigate to the domain name or IP address that you entered in your virtual host configuration.

You have successfully deployed a flask application.

Article Submitted by: Kundan Singh

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products

About the authorsDefault avatarKundan Singh

author

Still looking for an answer?Ask a questionSearch for more helpWas this helpful? 10 Comments

This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

Sign In or Sign Up to Commentpcosxlinux • January 26, 2016

This tutorial needs a bit renowation. But … let’s try to patch it :)

Today, january 2016, you are probably interested in python 3

libapache2-mod-wsgi should be libapache2-mod-wsgi-py3

python-pip should be python3-pip

“sudo pip install virtualenv” should be “sudo pip3 install virtualenv”(there is more options for ve but some didn’t work for me)

"sudo pip install Flask " > "sudo pip3 install Flask "

Now serious stuff …

apache config between must have:

WSGIDaemonProcess user=flask group=www-data threads=5 python-path=/var/www/:/var/www///venv/lib/python3.4/site-packages

example:

ServerName mywebsite.comServerAdmin admin@mywebsite.comWSGIDaemonProcess user=flask group=www-data threads=5 python-path=/var/www/:/var/www///venv/lib/python3.4/site-packagesWSGIScriptAlias / /var/www/FlaskApp/flaskapp.wsgiOrder allow,denyAllow from allAlias /static /var/www/FlaskApp/FlaskApp/staticOrder allow,denyAllow from allErrorLog ${APACHE_LOG_DIR}/error.logLogLevel warnCustomLog ${APACHE_LOG_DIR}/access.log combined

But this will only work if you have additional 2 lines in flaskapp.wsgi:

activate_this = ‘/var/www///venv/bin/activate_this.py’exec(compile(open(activate_this,“rb”).read(),activate_this, ‘exec’), dict(file=activate_this))

There is alternative, you can put next line in apache config outside of :

#WSGIPythonPath /var/www///venv/lib/python3.4/site-packages

Above code was my day … farewell :)

sbeau01 • April 21, 2014

for those with " ImportError: No module named flask", as said here http://flask.pocoo.org/docs/deploying/mod_wsgi/, I added the following lines to my wsgi file :activate_this = ‘/path/to/env/bin/activate_this.py’execfile(activate_this, dict(file=activate_this))

pmohseni • January 4, 2017

I have followed everything step by step and it works fine with the ‘Hello World’ app you use an example; but, when I upload my own application and try it in my browser, ****the page is loading indefinitely (‘waiting for host…’) ****so I do not get any errors to help me debug. Any idea what this could be??

Thanks for this amazing article!

ssundarraj • April 11, 2016

No point of installing virtualenv if you do this:

sudo pip install virtualenv

That command installs packages globally.

anantzoid • July 11, 2015

I’m not able to use the packages installed in my virtualenv while running my web application.The error says “ImportError: No module named …”However, if I directly run the python file in /var/www/, it runs perfectly.

Hamoud • February 20, 2015

but how to create many flask application running at the same time ?

jabbalaci • October 29, 2013

How can you tell Apache to run this app. using the app.'s virtualenv? Because I have the impression that the setup described here uses the global python installation!

ultrafaca • October 17, 2013

CSS is loaded. Homepage and other static pages are displayed in “sugar coated mode”, which means following: Links and pictures are displayed, but content of the page is 404. That is done via decorator (in init.py)

@app.errorhandler(404)def page_not_found(error):return flask.render_template(‘404.html’), 404

Now, the 404.html inherits from base.html basic html tags and CSS.

In other module, I have following code:

class Main(flask.views.MethodView):def get(self, page=“index”):page+= “.html”if os.path.isfile(“templates/” + page):return flask.render_template(page)else:flask.abort(404)

I have checked whether the paths are correct via Python interactive mode and they are fine.Everything was working on flask development server. Have any idea where is the problem.

Thanks

dirkswart • October 17, 2013

Hi Kamal,

I get:

It works!This is the default web page for this server.The web server software is running but no content has been added, yet.

What step should I search for the problem at?

Kamal NasserDigitalOcean EmployeeDigitalOcean Employee badge • August 16, 2013

@garethprice: Disable Apache’s default virtualhost:

sudo a2dissite default

Edit the virtualhost you created and set ServerName to e.g. ServerName flaskapp.dev and restart Apache.

sudo service apache2 restart

Edit /etc/hosts on your computer and add this line to the bottom:

1.2.3.4 flaskapp.dev

Where 1.2.3.4 is your droplet’s IP address. Save it and point your browser to http://flaskapp.dev - it should load your flask app properly.

Creative CommonsThis work is licensed under a Creative Commons Attribution-NonCommercial- ShareAlike 4.0 International License.

相关推荐: