Deploying Flask apps using mod_wsgi (+ Apache) is also a popular method described in the Official Documentation (https://flask.palletsprojects.com/en/0.12.x/deploying/mod_wsgi/). However, as far as I read, the explanation is unfriendly to beginners. I didn't know what to do because the script was broken at key points.
In addition, I was trying to use Pipenv for package management in Flask apps, but when it came to combining mod_wsgi, flask with Pipenv, I couldn't find a hit in English.
When I actually tried hard for about a whole day, deploying the app with the above combination required a slightly complicated procedure, so I would like to write it here as a memorandum for myself.
$ sudo apt install apache2
$ sudo apt install libapache2-mod-wsgi-py3
It seems that you need to specify libapache2-mod-wsgi-py3
instead of libapache2-mod-wsgi
when using Python 3. I think this is a pretty addictive point.
Add the Flask app under / var / www / html
. This time, let's make the program only display Hello, World for the sake of simplicity.
Create a wsgi-scripts
folder under html and save the following files with the name hello.py
.
/var/www/html/wsgi-scripts/hello.py
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello_world():
return 'Hello from flask!'
if __name__ == '__main__':
app.run()
If you can write
$ pipenv install
$ pipenv install flask
Let's create a virtual environment with.
Add the wsgi file to the same folder as the flask app. This is the file you will need to run on your production server. It looks a little strange, but it seems that this is a wsgi script. It sounds complicated, but except for the last line, it's preparation for using mod-wsgi and pipenv.
/var/www/html/wsgi-scripts/myapp.wsgi
activate_this = '/home/hoge/.local/share/virtualenvs/wsgi-scripts-XXXXXX/bin/activate_this.py'
with open(activate_this) as file_:
exec(file_.read(), dict(__file__=activate_this))
import sys
sys.path.insert(0, 'var/www/html/wsgi-scripts')
from hello import app as application
Here, the path corresponding to ʻactivate_thisneeds to be modified according to the individual environment. The point is the path of virtualenv, but as a confirmation method, you can copy the path that appears when you start
pipenv shell`.
From here, it is the setting of Apache. Let's add wsgi.conf
to/ etc / apache2 / conf-available /
.
```conf`
WSGIDaemonProcess myapp
WSGIProcessGroup myapp WSGIApplicationGroup %{GLOBAL}
WSGIScriptAlias /myapp /var/www/html/wsgi-scripts/myapp.wsgi
<Directory /var/www/html/wsgi-scripts> Require all granted
If you just want to run wsgi, you only need to write WSGIScriptAlias, but if you want to run the Flask app, you need to write other settings as well.
After writing, enable the site with the following command.
$ sudo a2enconf wsgi $ sudo sytemctl reload apache2
Now go to http: // localhost / myapp and you should see `hello from flask`.
that? When I wrote it, the amount of work was unexpectedly small ...
Recommended Posts