Configure Flask on virtual hosting
Introduction
This article is specifically about running on virtual hosting.
There is a separate article about deploying on your own server:
«Running a Flask application on a Linux server (Nginx + Gunicorn)»
About Flask in
Docker
Of course, much depends on the hosting but the main problems, I think, are the same everywhere.
Flask on hosting
There are a lot of articles on the internet about how to run Flask locally. But there are few guides on setting it up on virtual hosting (UPD: over the past couple of years there have become more).
For the material for this guide, I thank the hosting technical support
beget.com
their article about setting up
Flask
on hosting can be studied
here
Getting started with Flask on hosting
First you need to connect to your hosting account via SSH.
On
Linux
SSH client
is most likely built in.
On
Windows
you can install
SSH
from
Powershell
or
Windows Settings
or use an additional terminal such as
Putty
or
MobaXterm
The easiest way to connect to the account is by the domain name
ssh username@your_domain
You can also connect by IP. To find it out, run
ping your_domain
ssh username@ip
If on your hosting is installed Docker - go into the container with the command
ssh localhost -p222
(docker) will appear on the left in the command prompt
(docker) username@server:~/your_domain.ru
If this is beget.com , or find out how to do this on your hosting by asking a question to technical support.
Preparing the environment
After you have connected to your hosting and entered the docker environment, you may need
to prepare a working environment for installing Flask.
You need to install Python 3.6 or higher. Read more about installing with
configure make install
you can read
here
.
If Python is version 3.10 or higher, then openssl will need to be updated
It is recommended to create a temporary folder in the home directory
cd ~/.beget
mkdir
tmp
Updating OpenSSL
cd ~/.beget/tmp wget https://www.openssl.org/source/openssl-1.1.1l.tar.gz tar -xvzf openssl-1.1.1l.tar.gz && cd openssl-1.1.1l ./config --prefix=$HOME/.local --openssldir=$HOME/.local/ssl '-Wl,--enable-new-dtags,-rpath,$(LIBRPATH)'
… ********************************************************************** *** *** *** OpenSSL has been successfully configured *** *** *** *** If you encounter a problem while building, please open an *** *** issue on GitHub <https://github.com/openssl/openssl/issues> *** *** and include the output from the following command: *** *** *** *** perl configdata.pm --dump *** *** *** *** (If you are new to OpenSSL, you might want to consult the *** *** 'Troubleshooting' section in the INSTALL file first) *** *** *** **********************************************************************
make -j$((`nproc`/4)) && make install
~/.local/bin/openssl version
OpenSSL 1.1.1l 24 Aug 2021
Installing Python
At the time of writing this article, on the hosting Beget Python 3.11.0 can be installed with certainty. If you use another hosting, check what the latest supported version is.
cd ~/.beget/tmp wget https://www.python.org/ftp/python/3.11.0/Python-3.11.0.tgz tar -xvzf Python-3.11.0.tgz && cd Python-3.11.0 ./configure --prefix=$HOME/.local --with-openssl=$HOME/.local --with-openssl-rpath=auto --enable-optimizations --enable-loadable-sqlite-extensions LDFLAGS="-Wl,-rpath /usr/local/lib" make -j$((`nproc`/4)) && make install python3 -V
Python 3.11.0
Installing Flask
Update pip
python3 -m pip install --upgrade pip
Install flask
python3 -m pip install flask
or
pip3 install flask --user --ignore-installed
Creating the necessary files and directories
Let's create the simplest web application in the root of your site.
If your site already has a public_html folder, save it somewhere in a safe place and delete it
from the site.
We start in a completely empty directory; our goal is to create this structure (skeleton)
. └── your_domain.ru ├── HelloFlask │ └── __init__.py ├── .htaccess ├── passenger_wsgi.py └── tmp
Create two directories HelloFlask and tmp
mkdir HelloFlask tmp
We create two files in the root directory .htaccess and passenger_wsgi
touch .htaccess
touch passenger_wsgi.py
If you know how to edit files on the hosting, keep reading this article. If this causes problems, read my article «The vi text editor»
.htaccess
If you have not done this yet, in the root directory of the project run
touch .htaccess
In the file .htaccess write
PassengerEnabled On
PassengerPython /home/a/username/.local/bin/python3
Moreover, you will need to replace /home/a/username/.local/bin/python3 with the path
to your python3.
To find it out, run
which python3
You need exactly which python3 because which python will return the path to Python 2.7.17 /usr/bin/python
We have dealt with the file .htaccess , now let's edit passenger_wsgi.py
passenger_wsgi
# -*- coding: utf-8 -*-
import sys, os
# specify the directory with the project
sys.path.append('/home/a/username/testsetup.ru/HelloFlask')
# specify the directory with the libraries where Flask was installed
sys.path.append('/home/a/username/.local/bin/flask')
from HelloFlask import app as application
# When Flask starts, it looks for application.
# If you do not specify 'as application', the site will not work
from werkzeug.debug import DebuggedApplication
# Optional: connecting the debug module
application.wsgi_app = DebuggedApplication(application.wsgi_app, True)
# Optional: enabling the debug mode
application.debug = False
# Optional: True/False is set as needed for debugging
Where in /home/a/username/ you need to replace everywhere a/username with your username
And testsetup.ru needs to be replaced with your domain.
We have dealt with the file passenger_wsgi.py , now let's move to the folder HelloFlask
cd HelloFlask
Create a file there __init__.py
touch __init__.py
And write there
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello_world():
return 'Hello Flask!'
if __name__ == '__main__':
app.run()
We have dealt with the file __init__.py , let's return to the root directory
cd ..
And run
ln -s public_html public
touch tmp/restart.txt
Open your site and make sure it says Hello Flask!
When you make some updates, do not forget after saving
to perform a reload with the command.
touch tmp/restart.txt
Flask API for a PHP site
Suppose you already have a site on PHP and you need to make a REST API for it based on Flask. For this it is not necessary to order a dedicated server - on the hosting Beget they will help you implement this idea even on the simplest plan.
In the root directory of the site create a directory flaskapi
It will be at the same level as public_html
In the same place create a file .htaccess
mkdir flaskapi
touch .htaccess
ls -a
flaskapi public_html .htaccess
vi .htaccess
PassengerEnabled On PassengerPython /home/u/user/.local/bin/python3 PassengerAppRoot /home/u/user/domainname.ru/flaskapi PassengerBaseURI /flaskapi
Go to the directory flaskapi create a link public , the folder with the project HelloFlask and create a file there passenger_wsgi.py
cd flaskapi
ln -s public_html public
mkdir HelloFlask
touch HelloFlask/__init__.py
touch passenger_wsgi.py
vi passenger_wsgi.py
# -*- coding: utf-8 -*- import sys, os # specify the directory with the project sys.path.append('/home/u/user/domainame.ru/flaskapi/HelloFlask') # specify the directory with the libraries where Flask was installed sys.path.append('/home/u/user/.local/lib/python3.7/site-packages') #from flaskapi import app as application from HelloFlask import app as application # When Flask starts, it looks for application. # If you do not specify 'as application', the site will not work from werkzeug.debug import DebuggedApplication # Optional: connecting the debug module application.wsgi_app = DebuggedApplication(application.wsgi_app, True) # Optional: enabling the debug mode application.debug = False # Optional: True/False is set as needed for debugging
Edit the second .htaccess
file - the one in public_html
You need to make sure that PassengerEnabled off
vi public_html/.htaccess
PassengerEnabled off
Now you need to add directory routing to the Apache Virtual Host:
Alias /flaskapi /home/user/user/domainname.ru/flaskapi
You do not have enough rights for this action - so you need to ask technical support to do it
If you have not yet decided on the choice of hosting, I advise you to read my article
«Which hosting to choose»
A script for automatic installation
If you have installed Python3 and made sure that the right OpenSSL is in place, you can use my script for running a test Flask.
Create in a completely empty directory of your site the script
install_flask_vhost.sh
copy the following code into it, replace LETTER, USER and DOMAIN with your values and run the script
# install Flask on Beget # author: Andrey Olegovich # for: www.devhops.ru LETTER="t" USERNAME="tester" DOMAIN="testsetup.ru" python3 -m pip install --upgrade pip python3 -m pip install flask mkdir HelloFlask tmp touch .htaccess passenger_wsgi.py echo "PassengerEnabled On" > .htaccess echo "PassengerPython /home/${LETTER}/${USERNAME}/.local/bin/python3" >> .htaccess echo "import sys, os" > passenger_wsgi.py echo "" >> passenger_wsgi.py echo "sys.path.append('/home/${LETTER}/${USERNAME}/${DOMAIN}/HelloFlask')" >> passenger_wsgi.py echo "sys.path.append('/home/${LETTER}/${USERNAME}/.local/bin/flask')" >> passenger_wsgi.py echo "from HelloFlask import app as application" >> passenger_wsgi.py echo "from werkzeug.debug import DebuggedApplication" >> passenger_wsgi.py echo "application.wsgi_app = DebuggedApplication(application.wsgi_app, True)" >> passenger_wsgi.py echo "application.debug = False" >> passenger_wsgi.py echo "" >> passenger_wsgi.py cd HelloFlask touch __init__.py echo "from flask import Flask" > __init__.py echo "app = Flask(__name__)" >> __init__.py echo "" >> __init__.py echo "@app.route('/')" >> __init__.py echo "def hello_world():" >> __init__.py echo " return 'Hello Flask!'" >> __init__.py echo "if __name__ == '__main__':" >> __init__.py echo " app.run()" >> __init__.py echo "" >> __init__.py cd .. ln -s public_html public touch tmp/restart.txt
touch install_flask_vhost.sh chmod +x install_flask_vhost.sh ./install_flask_vhost.sh
Article author: Andrei Olegovich