2018年10月18日 星期四

Deploying Flask App with mod_wsgi (Python3) in Ubuntu 1804

1. Install apache2
2. Install mod_wsgi
# sudo apt install libapache2-mod-wsgi-py3
3. Create a Python3 virtualenv with Flask installed
# mkvirtualenv -p $(which python3) flask
(flask)# pip install flask
4. Create a .wsgi file for project (put in project folder)
newsite.wsgi:

activate_this = '/home/jack/.virtualenvs/flask/bin/activate_this.py'
with open(activate_this) as file_:
    exec(file_.read(), dict(__file__=activate_this))
import sys
sys.path.insert(0, '/home/jack/Documents/Projects/newsite')
from app import app as application

5. Open Apache2 ports. Edit file /etc/apache2/ports.conf

Listen 4002

6. Create a file for new site in /etc/apache2/sites-available
newsite.conf:


    ServerName newsite

    WSGIDaemonProcess newsite user=jack group=jack threads=5
    WSGIScriptAlias / /home/jack/Documents/Projects/newsite/newsite.wsgi

   
        WSGIProcessGroup newsite
        WSGIApplicationGroup %{GLOBAL}
        Require all granted
   


7. Enable the newsite
# sudo a2ensite newsite
(a2dissite for disable)

8. Reload the Apache2
# sudo systemctl reload apache2

9. Allow port 4002 by ufw
# sudo ufw allow 4002
(sudo ufw delete allow 4002) to disable

10. Open broswer to browse http://:4002

Note1. Apache2 error log is in /var/log/apache2/error.log

Note2. If you are using open() in app.py, need to instead to app.open_resource() to prevent FileNotFoundException

Reference:
http://flask.pocoo.org/docs/1.0/deploying/mod_wsgi/
http://flask.pocoo.org/docs/0.12/api/#flask.Flask.open_resource

沒有留言:

張貼留言