Python Web Development

Introduction

pythonQuote

Web apps are often created using a framework. Frameworks make it easier to develop web apps that are scalable, reliable and maintainable. It avoids recreating the same code over and over again.
Common features are:

  • URL Routing
  • Output templates
  • Database management
  • Session management
  • Security against common attacks

A framework may offer some or all of these features.

For example, the Flask web application framework does not have database support and you would need a separate module to use a database.  The Django web application framework supports databases by default.

Why use a web framework?

As you are doing web development, you want to avoid spending time on programming things that have already been solved. On the other hand, if you are an experienced web developer a web framework may not offer everything you need.

What Python web frameworks exist?

Django and Flask are the most popular web frameworks. However, you may want to evaluate the frameworks. An overview:

The most popular python web application framework is Django, followed by Flask.

python web development
# of projects on Github mentioning a framework.

Django

Django is the most used Python web framework. It takes care of many things so you can focus on the web app development. Sites built withDjango have dealt with high traffic spikes such as 50 thousands hits per second.  

Database access is achieved through an Object-relational mapper:   You define your data models in Python and Django deals with the actual database management systems (SQL).  However, if  you need to you can write your own SQL Queries with Django.  URL routing is supported by Django. It encourages beautiful URL design such as ending without .php or .asp.

Features:

  • Object-relational mapper
  • URLs routing and views
  • Template engine
  • Forms
  • Authentication
  • Admin
  • Internationalization
  • Security

If you want to know more about Django, read here.

Did you know the websites of NASA,  Bitbucket and Pinterest were made with Django?

Flask

flask-logo
Flask is a Python micro framework which is modular by design. The framework is intended to build web apps. Flask does not have a  specific database system or ORM system.  If you want to use a database, you’ll have to use extensions. Flask is often combined with SQLAlchemy for database use.

Flask is very easy to get running, a minimal app would be:

from flask import Flask
app = Flask(__name__)
 
@app.route('/')
def hello_world():
    return 'Hello World!'
 
if __name__ == '__main__':
    app.run()

The framework supports URL routing, template (using Jinja2), session management and has some out of the box security.

Features:

  • URL Routing and views
  • Template engine
  • Session management
  • Logging

If you want to know more about Flask, read here.

Did you know Flask started as an April Fools joke?

Python Hosting

To run your app on the web, you will need hosting. Unless you want to do hosting yourself, you need a party to host.
Hosting servers:

Django Getting started

Django is a high-level Python Web framework that takes care of much of the hassle of Web development, so you can focus on writing your app without needing to reinvent the wheel.

In this tutorial you will learn how to setup a basic Django web app.

Related course
The Ultimate Beginner’s Guide to Django

Django tutorial

Install Django using:

pip install Django==1.7.1

Once installed, create the directory /django-hello/ for your app. In this directory create the file hello.py with this contents:

#!/usr/bin/env python
import sys
from django.conf import settings 
from django.conf.urls import patterns
from django.http import HttpResponse
from django.core.management import execute_from_command_line
 
settings.configure(
    DEBUG=True,
    SECRET_KEY='asecretkey',
    ROOT_URLCONF=sys.modules[__name__],
)
 
def index(request):
    return HttpResponse('Hello, World')
 
urlpatterns = patterns('',
    (r'^hello/$', index),
)
 
if __name__ == "__main__":
    execute_from_command_line(sys.argv)

Execute the script using:

python hello.py runserver

A HTTP Django server will start and if you open http://127.0.0.1:8000/hello/

Django Web Framework
Django Web Framework

Django code explanation:
The top lines import the Django library:

from django.conf import settings 
from django.conf.urls import patterns
from django.http import HttpResponse
from django.core.management import execute_from_command_line

If you open the link /hello/, the webserver will call the index() function. We map the url to the function using:

urlpatterns = patterns('',
    (r'^hello/$', index),
)

In Django we have url friendly urls. This means you do not have a url that ends in /id=1359835, but instead we have the directory as name.  Finally, we set some default settings using settings.configure.

Django Tutorial: Building a note taking app

Django

If you want to start with python web development, you could use a web framework named Django. It is designed to be fast, secure and scalable. It comes with an object-relational mapper (ORM), which means that objects in Python are mapped to objects in a database.

Applications created with Django are separated in three separate layers: model (database), view (appearance) and controller (logic), or shortly themodel-view-controller (MVC) architecture.

Related courses

Setting up Django

Start with:

django-admin startproject mysite

This will create the directory mysite. Open mysite/mysite/settings.py. You can configure your desired database here:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}

Pick from sqlite3, postgresql_psycopg2, mysql or oracle. Name is the name of your database. If you use SQLite the database will be created automatically. For MySQL and Postgresql you need to create the database yourself. Go up one directory to /mysite/ and run:

python manage.py runserver

The terminal should say:

Performing system checks...
 
System check identified no issues (0 silenced).
 
You have unapplied migrations; your app may not work properly until they are applied.
Run 'python manage.py migrate' to apply them.
 
August 16, 2015 - 14:45:29
Django version 1.7.1, using settings 'myapp.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
[16/Aug/2015 14:45:35] "GET / HTTP/1.1" 200 1759

Open http://127.0.0.1:8000 in your web browser and you should see:

django
Our first Django app.

Now we created a project, we create an app. A project can have many apps.

python manage.py startapp notes

This creates the files:

notes/
    __init__.py
    admin.py
    migrations/
        __init__.py
    models.py
    tests.py
    views.py

Django database model

Change /mysite/notes/models.py to:

from django.db import models
 
class Note(models.Model):
    text = models.CharField(max_length=120)
    created = models.DateTimeField(auto_now_add=True)

Open /mysite/mysite/settings.py, add the web app:

INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'notes'
)

Run

python manage.py syncdb

which will update the database. We then update /mysite/mysite/admin.py to:

from django.contrib import admin
 
# Register your models here.
from .models import Note
 
class NoteAdmin(admin.ModelAdmin):
    class Meta:
        model = Note
 
admin.site.register(Note,NoteAdmin)

Run:

python manage.py makemigrations notes
python manage.py migrate

Start your server using:

manage.py runserver

Once you open up the admin panel http://127.0.0.1:8000/admin, Notes will appear on the page:

django_admin
Django admin panel

If you click on notes you can view all notes and add/delete them:

django_database
Django database admin menu.

Show the data

We have all our data in the database, now we want to create our app. Open /mysite/settings.py and add:

#print "base dir path", BASE_DIR
#print os.path.join(os.path.dirname(BASE_DIR), "mysite", "static",  "templates")
 
TEMPLATE_DIRS = (
    os.path.join(os.path.dirname(BASE_DIR), "mysite", "static",  "templates"),
    #'/home/frankbox/python/djangoapp/mysite/static/templates',
)

to the bottom of the file. This defines the directory of our templates (html).

Change /mysite/mysite/urls.py to:

from django.conf.urls import patterns, include, url
from django.contrib import admin
 
urlpatterns = patterns('',
    # Examples:
    # url(r'^$', 'mysite.views.home', name='home'),
    # url(r'^blog/', include('blog.urls')),
    url(r'^$', 'notes.views.home', name='home'),
    url(r'^admin/', include(admin.site.urls)),
)

Finally create /mysite/static/templates/ and add note.html, which is a simple static html file.

<!DOCTYPE html>
    <html>
        <head>
        </head>
 
        <body>
            <b>Hello</b>
        </body>
    </html>

Open http://127.0.0.1:8000/ to test if works. Change note.html to:

<!DOCTYPE html>
    <html>
        <head>
        </head>
 
        <body>
          <h2>Notes</h2>
          <ul>
          {% for note in notes.all %}
              <li>{{ note.text }}</li>
          {% endfor %}
        </ul>
        </body>
    </html>

Then open /mysite/notes/views.py and change to:

from django.shortcuts import render, render_to_response, RequestContext
from django.template import RequestContext, loader
from django.http import HttpResponse
from .models import Note
 
# Create your views here.
 
def home(request):
    notes = Note.objects
    template = loader.get_template('note.html')
    context = {'notes': notes}
    return render(request, 'note.html', context)
    #return render_to_response("note.html", notes)

Once you fire up your browser you will see the list of notes:

django app
django app

Insert data

While it’s nice to have a list, we want to add some notes to it.
Create the file /mysite/notes/forms.py

from django import forms
from .models import Note
 
class NoteForm(forms.ModelForm):
    class Meta:
        model = Note

Change view.py to:

from django.shortcuts import render, render_to_response, RequestContext
from django.template import RequestContext, loader
from django.http import HttpResponse
from .models import Note
from .forms import NoteForm
 
# Create your views here.
 
def home(request):
    notes = Note.objects
    template = loader.get_template('note.html')
    form = NoteForm(request.POST or None)
    if form.is_valid():
        save_it = form.save(commit=False)
        save_it.save() 
 
    context = {'notes': notes, 'form': form}
    return render(request, 'note.html', context)
    #return render_to_response("note.html", notes)

Finally we update note.html to:

<!DOCTYPE html>
    <html>
        <head>
        </head>
 
        <body>
          <h2>Notes</h2>
          <ul>
          {% for note in notes.all %}
              <li>{{ note.text }}</li>
          {% endfor %}
        </ul>
 
        <form method='POST' action=''>{% csrf_token %}
            {{ form.as_p }}
            <input type='submit'>
        </form>
 
        </body>
    </html>

Run it and we have our note taking app 🙂

django_app_insert
Djano note taking app

Styling the app

By modifying the note.html we can style it like any other html/css website. If you change note.html to:

<!DOCTYPE html>
    <html>
        <head>
            <link href="http://codepen.io/edbond88/pen/CcgvA.css" media="screen" rel="stylesheet" type="text/css" />
            <style>
            body {
              background: rgba(222,222,222,1);
              margin: 20px;
            }
            </style>
        </head>
 
        <body>
          <h1>Django Note Taking App</h1>
 
          {% for note in notes.all %}
            <aside class="note-wrap note-white">
              <li>{{ note.text }}</li>
            </aside>
          {% endfor %}
 
        <form method='POST' action=''>{% csrf_token %}
            {{ form.as_p }}
            <input type='submit' value='Add note'>
        </form>
 
        </body>
    </html>

You will get:

django_note_app
Django note taking app

 

 

Flask getting started: Hello World

In this tutorial you’ll learn how to build a web app with Python. 

We’ll use a micro-framework called Flask. It has a small core but is extensible with many plugins such as SQLAlchemy, Babel, CouchDB, MongoDB etc.  

Some Flask example apps are:

Related course
Complete Python Web Course: Build 8 Python Web Apps

Why Flask?

  • easy to use.
  • built in development server and debugger
  • integrated unit testing support
  • RESTful request dispatching
  • uses Jinja2 templating
  • support for secure cookies (client side sessions)
  • 100% WSGI 1.0 compliant
  • Unicode based
  • extensively documented

Download Flask Examples

Installing Flask

Install Flask using the command below:

pip install Flask

Flask hello world app

Create a file called hello.py

from flask import Flask
app = Flask(__name__)
 
@app.route("/")
def hello():
    return "Hello World!"
 
if __name__ == "__main__":
    app.run()

Finally run the web app using this command:

$ python hello.py
* Running on http://localhost:5000/

Open http://localhost:5000/ in your webbrowser, and “Hello World!” should appear.

Download Flask Examples