Python Web Server

A web server hosting Python and (optionally) any framework (Django, Flask, ..) requires that the host provider gives you shell access to the root (typically via SSH), and the Apache installation needs to support CGI and mod_wsgi.   For security reasons, very few host providers will give you shell access to the root for a shared host plan.   You can get it through a dedicated server or virtual private server (VPS), but you will pay considerably more, and you will need to configure it yourself.  

The only inexpensive Python web hosting solution I could find was through HEROKU.   They support Python and popular Python frameworks, and they offer a 'Free' and an inexpensive 'Hobby' plans (they also have professional plans).   Heroku's getting started online documents are vast and detailed.  

 

Index:   Streamlit | Heroku | Bottle | Pyramid | CherryPy

 

Streamlit

Streamlit is a free and open-source framework to build and share Python based machine learning and data science web apps.   It includes options for connecting with data sources such as AWS S3, BigQuery, PostgreSQL, MS SQL Server, and local storage.   Streamlit supports continuous integration and continuous deployment (CI/CD) pipelines and automatically pulls code change from the project repository.  

A complete guide to building streamlit data web apps with code examples

 

Heroku Python Web Hosting

Getting Started

Sign up for a Free account

Install a supported Python runtime (3.8.2)

Install Git on your PC

Install Postgres locally on your PC   tutorial

Install the Heroku CLI on your PC

Verify your Heroku CLI installation and then login ("heroku login -i")

From your Heroku dashboard, Create a new app (app = web application on Heroku)

deploying a Python app (a simple Django app)

 

Pointing a domain to a Heroku app

To make an Heroku app available at a non-Heroku domain, you add a custom domain to it.   Adding custom domains does not incur extra charges.   See the first help link below to add a custom domain using the Heroku CLI.   In short, you execute the heroku command heroku domains:add www.example.com and then follow the instructions to point your domain www.example.com to the Heroku DNS target.  

Try add a CNAME record pointing the www subdomain to your Heroku app’s herokuapp.com hostname.  

Heroku - custom domain names for apps

 

Deploying Flask App on Heroku

Tutorial below derived from this link

Go into the Python virtual environment.

Install Gunicorn


pip install gunicorn

Create requirements.txt file.


pip freeze > requirements.txt

Create runtime.txt file to specify to Heroku the Python version.   Edit the runtime.txt file and add the Python version as reported by the python -V output, but with case and formatting of python-3.7.3.   Note that the version in runtime.txt seems to need to correspond with what the Heroku environment accepts, as I was running version 3.8.2 at the time in a virtual environment.  


python -V

Make sure Heroku supports the Python runtime selected by checking supported runtimes

Add a Procfile with the content web: gunicorn app:app.   The Procfile.windows file is for working with Heroku locally.  

User Heroku to create the heroku app


heroku login
heroku create

The .git file is the Heroku got remote repository where your applcaation exists on Heroku.   In the Heroku web dashboard, you should see your app listed.  


heroku git:remote -a your-heroku-remote-app-name

git add .
git commit -m "my notes about the repository"
git remote -v
git push heroku master

If the above is successful, then spin up the app on the Heroku cloud.


heroku ps:scale web=1

User the Heroku CLI to launch the app in your default browser:


heroku open
venv\scripts\deactivate

PyBites flask / heroku deploy tutorial

CobuildLab deploying a Flask app on Heroku

 


Flask

Flask is a Python web framework

Follow the tutorial links below:

Flask tutorial chapter 1 by Miguel

Manage static assets with Flask-Assets

Flask - jsonify - GET/POST - Fetch API

Static files in Flask have a special route. All application URLs that begin with "/static", by convention, are served from a folder located at "/static" inside your application's root folder.

Install Python virtualenvwrapper


$ pip install virtualenvwrapper

$ python -m venv venv
$ venv\scripts\activate

Install Flask and run it with the development features including debugging (set FLASK_ENV=development) enabled.  


(venv) $ pip install flask
(venv) $ set FLASK_APP=proj_flask.py
(venv) $ set FLASK_ENV=development
(venv) $ flask run

When done working on the project:


(venv) $ venv\scripts\deactivate
$ set FLASK_APP=

 

Links

geeksforgeeks.org

geeksforgeeks.org 1st Flask app

Scout - getting started with flask

Tutorial - Flask on Heroku

GET with url args; headers; etc.

the complete flask beginner tutorial 124i

Flask links

Explore Flask

Jinja tips & tricks

AJAX by healeycodes.com

REST API using Flask


Django

Learn how to use Django locally so you are more effective with Heroku.   Your local environment should already be configured to support the Django tutorial below.  

Writing your first Django app, part 1

 

Open Existing Django Project


cd 'py_website543'
python manage.py runserver

Open a browser to the URL http://localhost:8000/html_root/

 

Create a new Django Project

Login & create the new project 'py_website543' in folder 'django_proj1'


heroku login
md django_proj1
cd django_proj1
django-admin startproject py_website543

Use a file browser to look at the folders and files in folder 'django_proj1'.  


../py_website543
../py_website543/py_website543
../py_website543/py_website543/manage.py
../py_website543/py_website543/py_website543/
../py_website543/py_website543/py_website543/__init__.py
../py_website543/py_website543/py_website543/asgi.py
../py_website543/py_website543/py_website543/settings.py
../py_website543/py_website543/py_website543/urls.py
../py_website543/py_website543/py_website543/wsgi.py

The outer 'django_proj1' folder is a container for the project.   It's name doesn't matter to DJango, and it can be renamed.   The inner 'django_proj1' folder is the Python project location.   Read more about the files in the inner 'django_proj1' folder here.  

The project folder doesn't have any HTML files in it, but you can still run a local web server and see the default django page in a browser using the command:


cd 'py_website543'
python manage.py runserver

And then opening the page in a browser to http://127.0.0.1:8000/.   (or whatever URL is shown in the command window)   If you do this, you will need to enter the keystroke CTRL-BREAK in the command window to terminate the webserver.  

Now that the project is ready, create an app within your project that will hold html pages.   Note that each app (application) you write in Django consists of a Python package that follows a certain converntion.   In the folder where 'manage.py' resides, type this command to create an app called 'html_root'.  


python manage.py startapp html_root

Review with a file browser the files under the folder 'html_root'.   Next configure the html_root/views.py file to return a HTTP response with a simple message that will be shown in a browser window.   Edit the html/views.py file and add the content shown below:


from django.http import HttpResponse
def index(request):
    return HttpResponse("Hello, world. You're at the html_root index.")

To call the view, you need to map it to a URL using URLconf.   Create a html_root/urls.py file with the following content:.  


from django.urls import path

from . import views

urlpatterns = [
    path('', views.index, name='index'),
]

Point the root URLconf at the html_root/urls.py module.   Edit the file ../py_website543/py_website543/urls.py and add an import for django.urls.include, and insert an include() in the urlpatterns list.


from django.contrib import admin
from django.urls import include, path

urlpatterns = [
	path('html_root/', include('html_root.urls')),
    path('admin/', admin.site.urls),
]

Test the changes implemented by running the web server.   Change the folder to the outer 'py_website543' folder and execute python manage.py runserver.  


python manage.py runserver

And open a browser to the URL http://localhost:8000/html_root/

The view function (in file views.py) is a Python function that takes a HTTP request and returns a HTTP response.   The response can be the HTML contents for a web page, a redirect, an XML document, and image. etc.   The view function contains whatever is necessary to return a properly formatted HTTP response.   More view function examples

Configure Django to read a index.html file.   Edit the ../py_website543/py_website543/settings.py file and modify the TEMPLATES = [ section and add os.path.join(BASE_DIR,"templates") to the 'DIRS': [], so it looks like this:


TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR,"templates")],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

Additionally, at the end fo the ../py_website543/py_website543/settings.py file where STATIC_URL = '/static/' is found, add the the two statements STATICFILES_DIRS and STATIC_ROOT as shown below.


STATIC_URL = '/static/'
STATICFILES_DIRS = (
    os.path.join(BASE_DIR, 'static'),
    os.path.join(BASE_DIR, 'static/css'),
    os.path.join(BASE_DIR, 'static/images'),
)
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')

Static files that index.html and other similar files may use are stored within the static folder and subfolders.  

Django and Static Assets

Create folders templates and status under the project folder py_website543 where the manage.py resides.   In the static folder, create two subfolders css and images.   Download the html.zip file, extract, and then put the index.html file into a new folder templates, the screen.css file into the css folder, and the no-image-76x50.png file into the images folder.  


../py_website543/templates/index.html
../py_website543/static/css/screen.css
../py_website543/static/images/no-image-76x50.png

Save the file changes and referesh the browser (CTRL-F5) tab/window with the URL http://localhost:8000/html_root/ to see the result.   You should see a three column formatted web page with tab menus, a header, and a footer.  

The current folder structure should be:


../py_website543/..
../html_root/..
../static/
../static/css/
../static/images/
../staticfiles/
../templates/

 

Django Tutorial for Beginners

Django Templates & Static Files

 


Web Server Options

Python - Web Programming in Python

Python Web Frameworks

Django (Py 2.7)

web2py

General Web Server information

Apache HTTPD and nginx are the two common web servers used with python

Flask deployment to production

 

Python on HostMonster

HM Linux web servers have the capability to run Python CGI scripts in the "cgi-bin" directory.   More details

The only way to get root shell access at HostMonster is through a dedicated server, or a virtual private server (VPS).   The downside to this over the shared plans is that you get no Python or Python framework support, and you must install and manage the servers yourself.   Hostmonster VPS prices are competitive.  

HM install Python 2.7

Django on HostMonster (26 Jan 2020)

Serving a Python Flask Website on Hostmonster (2014)

HM install Python 2.7

Deploying Django on HostMonster Shared Hosting

 

Bottle

Bottle is a minimalist web framework that is designed for small-scale projects. It has a simple and intuitive API, making it easy to get started. Bottle is known for its speed and is suitable for developing lightweight web applications and APIs.

 

Pyramid

Pyramid is a full-stack web framework that aims to be flexible and adaptable. It provides a wide range of features and can be used for building small websites to large-scale applications. Pyramid follows the principle of "pay only for what you need" and allows you to choose the components you want to use.

 

CherryPy

CherryPy is a minimalist web framework that focuses on simplicity and performance. It is easy to learn and provides a built-in web server, making it convenient for development and testing. CherryPy is suitable for small to medium-sized web applications.