Learning Python Network Programming

(Sean Pound) #1

Applications for the Web


Some frameworks provide the minimum to quickly build a simple web application.
These are often called microframeworks, the most popular here being Armin
Ronacher's excellent Flask. Although they may not include the functionality of some
of the heavyweight frameworks, what they do, they generally do very well, and
provide hooks to allow easy extension for more complex tasks. This allows a fully
customizable approach to web application development.


Other frameworks take a much more batteries-included stance, providing for all the
common needs of modern web applications. The major contender here is Django,
which includes everything from templating to form management and database
abstraction, and even a complete out-of-the-box web-based database admin interface.
TurboGears provides similar functionality by integrating a core microframework
with several established packages for the other features.


Yet other frameworks provide features such as supporting web applications with an
event-driven architecture, such as Tornado, and CherryPy. Both of these also feature
their own built-in production quality web servers.


Choosing a framework can be a tricky decision, and there is no right answer. We're
going to take a quick look at one of today's most popular frameworks to get an
idea of the services a framework can offer, then discuss how you might approach
choosing one.


Flask – a microframework


To get a taste of working with a Python web framework, we're going to write a small
app with Flask. We've chosen Flask because it provides a lean interface, giving us
the features we need while getting out of the way and letting us code. Also, it doesn't
require any significant preconfiguration, all we need to do is install it, like this:





pip install flask





Downloading/unpacking flask


Flask can also be downloaded from the project's homepage at http://flask.pocoo.
org. Note that to run Flask under Python 3, you will need Python 3.3 or higher.


Now create a project directory, and within the directory create a text file called
tinyflaskapp.py. Our app is going to allow us to browse the docstrings for the
Python built-in functions. Enter this into tinyflaskapp.py:


from flask import Flask, abort
app = Flask(__name__)
app.debug = True

objs = __builtins__.__dict__.items()
Free download pdf