Ubuntu Python Flask

For production server

sudo apt-get install build-essential apache2 
sudo apt-get install libapache2-mod-wsgi-py3 apache2-dev
sudo apt-get install python3-venv python3-flask
sudo apt-get install python3-pip python3-dev
sudo virtualenv -p python3 venv
sudo a2enmod wsgi

### OLD
sudo apt-get install python-dev python-pip
sudo apt-get install python3.7-minimal

Create required folder structure

### Create Empty folders
cd /var/www
sudo mkdir myPython
cd myPython
sudo mkdir static templates

config file for apache

sudo nano /etc/apache2/sites-available/000-default.conf
<VirtualHost *:80>
     ### Put flaskapp.wsgi outside app folder
     WSGIScriptAlias /wsgi /var/www/myPython/flaskapp.wsgi
     <Directory /var/www/myPython/myFirstFlask>
            Order allow,deny
            Allow from all
            Require all granted
     </Directory>
     ...
</VirtualHost>

sudo nano flaskapp.wsgi

activate_this = '/var/www/FlaskApp/myFirstFlask/venv/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/FlaskApp')
sys.path.append("/var/www/FlaskApp/myFirstFlask")
from myFirstFlask import app as application

sudo nano kim.wsgi

#!/usr/bin/python3

import sys
sys.path.insert(0, '/var/www/demo')

from flaskblog import create_app_kim
application = create_app_kim()

sudo nano __init__.py

from flask import Flask
 app = Flask(name)
 @app.route("/")
 def hello():
     return "Hello Kim! 1 2"
 if name == "main":
     app.run(host='0.0.0.0', debug=True)

Give proper permissions to wsgi.py

sudo chown www-data:www-data /var/www/html/wsgy.py
sudo chmod 755 /var/www/html/wsgy.py

Enable the file with a2ensite (if you are using separate conf)

sudo a2ensite /etc/apache2/sites-available/ExampleFlask.conf
sudo service apache2 restart

Long method to execute

### Execute hello.py
(venv) kim@server:/var/www/myPython$ export FLASK_APP=hello.py

### Turn on debug
(venv) kim@server:/var/www/myPython$ export FLASK_DEBUG=1

### Run
(venv) kim@server:/var/www/myPython$ flask run 
or
(venv) kim@server:/var/www/myPython$ flask run --host=0.0.0.0 --port=80

Short method to execute

(venv) kim@server:/var/www/myPython$ sudo python init.py
or
(venv) kim@server:/var/www/myPython$ FLASK_APP=__init__.py FLASK_DEBUG=1 python -m flask run

Install additional

### Install virtualenv
pip3 install virtualenv

### pip3 list
pip3 list

### Create virtual environment 
virtualenv venv

### Activate
. venv/bin/activate

### Install Flask
(venv) pip3 install Flask

### mod_wsgi
(venv) pip3 install mod_wsgi

### flask-wtf
(venv) pip3 install flask-wtf

### flask-sqlalchemy
(venv) pip3 install flask-sqlalchemy

### deactivate to go back to shell
deactivate

tricks on Python interpreter

### Generate random string with 16 bytes
>>> import secrets
>>> secrets.token_hex(16)



Troubleshooting

[wsgi:error] ImportError: No module named myFirstFlaskAppFolder 
### Ensure app.wgsi is referencing correct folder

from myFirstFlaskAppFolder import app as application

Generate requirement.txt

### Create
pip3 freeze > requirements.txt

### Install
(venv) pip3 install -r requirements.txt

Verify environment variables

>>> import os
>>> os.environ
>>> os.environ.get['EMAIL_USER']

json

sudo nano config.json
{
    "SECRET_KEY": "PUT_YOUR_SECRET_KEY_XYZ",
    "SQLALCHEMY_DATABASE_URI": "SQLITE:///SITE.DB",
    "EMAIL_USER": "EMAIL_USER",
    "EMAIL_PASS": "EMAIL_PASS"
}

config.py

import json

with open(os.getcwd()+'\config.json') as config_file:
    config = json.load(config_file)

config.py (path works on all servers)

import os
import json

filename = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', 'config_secret.json'))

with open(filename) as config_secret_json:
    config_secret = json.load(config_secret_json)

From SQLite to MySQL

from flask import Flask
import flask_sqlalchemy

app = Flask(__name__)

#sqlite
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/test.db'

#mysql
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://username:password@localhost/db_name'

db = SQLAlchemy(app)

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to top