Foundations of Python Network Programming

(WallPaper) #1

Chapter 11 ■ the World Wide Web


208


But SQLAlchemy itself does not know about HTML forms, so the programmer using a microframework will
need to find yet another third-party library to do the other half of what the previous models.py file does for the
Django programmer.
Instead of having the programmer attach URL paths to Python view functions using a Flask-style decorator,
Django has the application writer create a urls.py file like that shown in Listing 11-10. While this gives each
individual view a bit less context when read on its own, it makes them each position-independent and works to
centralize control of the URL space.


Listing 11-10. The urls.py for the Django App


#!/usr/bin/env python3


Foundations of Python Network Programming, Third Edition


https://github.com/brandon-rhodes/fopnp/blob/m/py3/chapter11/djbank/urls.py


URL patterns for our Django application.


from django.conf.urls import patterns, include, url
from django.contrib import admin
from django.contrib.auth.views import login


urlpatterns = patterns('',
url(r'^admin/', include(admin.site.urls)),
url(r'^accounts/login/$', login),
url(r'^$', 'djbank.views.index_view', name='index'),
url(r'^pay/$', 'djbank.views.pay_view', name='pay'),
url(r'^logout/$', 'djbank.views.logout_view'),
)


Django makes the quirky decision to use regular expression matching to match URLs, which can lead to difficult-
to-read patterns when a URL includes several variable portions. They can also—and I speak from experience—be
quite difficult to debug.
These patterns establish essentially the same URL space as in the earlier Flask applications, except that the path
to the login page is where the Django authentication module expects it to be. Instead of writing up your own login
page—and hoping you write it correctly and without some subtle security flaw—this code relies on the standard
Django login page to have gotten things right.
The views that finally tie this Django application together in Listing 11-11 are at once both simpler and more
complicated than the corresponding views in the Flask version of the app.


Listing 11-11. The views.py for the Django App


#!/usr/bin/env python3


Foundations of Python Network Programming, Third Edition


https://github.com/brandon-rhodes/fopnp/blob/m/py3/chapter11/djbank/views.py


A function for each view in our Django application.


from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.contrib.auth import logout
from django.db.models import Q
from django.shortcuts import redirect, render
from django.views.decorators.http import require_http_methods, require_safe
from .models import Payment, PaymentForm

Free download pdf