Learning Python Network Programming

(Sean Pound) #1

Applications for the Web


Let's go through our code. From the top, we create our Flask app by creating a Flask
instance, in this case giving it the name of our main module. We then set debug
mode to active, which provides nice tracebacks in the browser when something goes
wrong, and also sets the development server to automatically reload code changes
without needing a restart. Note that debug mode should never be left active in a
production app! This is because the debugger has an interactive element, which
allows code to be executed on the server. By default, debug is off, so all we need to
do is delete the app.config.debug line when we put the app into production.


Next we filter the built-in function objects out of the globals and extract their
docstrings for later use. Now we have the main section of the app, and we encounter
the first of Flask's superpowers: URL routing. The heart of a Flask app is a set of
functions, usually called views, that handle requests for various parts of our URL
space—index() and show_docstring() are such functions. You will see both are
preceded by a Flask decorator function, app.route(). This tells Flask which parts of
our URL space the decorated function should handle. That is, when a request comes
in with a URL that matches a pattern in an app.route() decorator, the function with
the matching decorator is called to handle the request. View functions must return a
response that Flask can return to the client, but more on that in a moment.


The URL pattern for our index() function is just the site root, '/', meaning that
only requests for the root will be handled by index().


In index(), we just compile our output HTML as a string—first our list of links
to the functions' pages, then a header—and then we return the string. Flask takes
the string and creates a response out of it, using the string as the response body
and adding a few HTTP headers. In particular, for str return values, it sets
Content-Type to text/html.


The show_docstrings() view does a similar thing—it returns the name of the
built-in function we're viewing in an HTML header tag, plus the docstring
wrapped in a

 tag (to preserve new lines and whitespace).


The interesting part is the app.route('/functions/') call. Here we're
declaring that our functions' pages will live in the functions directory, and we're
capturing the name of the requested function using the segment.
Flask captures the section of the URL in angle brackets and makes it available to our
view. We pull it into the view namespace by declaring the func_name argument for
show_docstring().

Free download pdf