7 ม.ค. 2563

Setting up Flask and Apache on Ubuntu 18.04 Server

Setup Python3 Environment

First, update apt-get.
$ sudo apt-get update
 
Python3 installed.
$ sudo apt-get install python3-pip
 
Get virtualenv.
$ pip3 install virtualenv
 
Create the project folder.
$ mkdir flaskproject
 
Set up the virtual environment.
$ cd flaskproject
$ virtualenv venv
 
Activate the environment (use deactivate to exit the environment).
$ . venv/bin/activate

Setup Flask

Install Flask
$ pip install Flask
 
Create the Flask file. For now, we will use a basic sample file and call it app.py
$ vi app.py
 
Paste the following code in.
from flask import Flask
app = Flask(__name__)

@app.route('/')
def hello_world():
 return 'Hello, World!'

if __name__ == "__main__":
    app.run()

Setup Apache

Install mod_wsgi, make sure to have '-py3' at the end of libapache2-mod-wsgi-py3 or the runtime will default to Python2.7
$ sudo apt-get install apache2 libapache2-mod-wsgi-py3
 
Create a wsgi file.
$ vi app.wsgi
 
Paste the following code in.
activate_this = '/home/ubuntu/flaskproject/venv/bin/activate_this.py'
with open(activate_this) as f:
 exec(f.read(), dict(__file__=activate_this))

import sys
import logging

logging.basicConfig(stream=sys.stderr)
sys.path.insert(0,"/var/www/html/flaskproject/")

from app import app as application
 
Create a symlink so that the project directory appears in /var/www/html
$ sudo ln -sT ~/flaskproject /var/www/html/flaskproject
 
Enable wsgi.
$ sudo a2enmod wsgi
 
Configure apache (you will need to sudo to edit the file)
$ sudo vi /etc/apache2/sites-enabled/000-default.conf
 
Paste this in right after the line with DocumentRoot /var/www/html
WSGIDaemonProcess flaskproject threads=5
WSGIScriptAlias / /var/www/html/flaskproject/app.wsgi

<Directory flaskproject>
 WSGIProcessGroup flaskproject
 WSGIApplicationGroup %{GLOBAL}
 Order deny,allow
 Allow from all
</Directory>
 
Restart the Server
 service apache2 restart

ไม่มีความคิดเห็น:

แสดงความคิดเห็น