Learning Python Network Programming

(Sean Pound) #1
Chapter 9

Then in templates with forms, just do the following:


<form method="post" action="<whatever>">
<input name="_csrf_token" type="hidden" value="{{ csrf_token()
}}">

This is from the Flask site: http://flask.pocoo.org/snippets/3/. Although this
contains some Flask functionality, we haven't covered, including sessions and the
@app.before_request() decorator, you just need to include the above code in
your app, and make sure you include a _csrf_token hidden input in every form.
An alternative approach is to use the Flask-WTF plugin that provides integration
with the WTForms package, which has built-in CSRF protection.


Django on the other hand has built-in protection, though you need to enable and use
it. Other frameworks vary. Always check your chosen framework's documentation.


There is more information on XSS and CSRF on the Flask and
Django sites:


Finishing up with frameworks


That's as far as we're going to take our dip into Flask, here. There are some examples
of further adaptations to our application in the downloadable source code of this
chapter, notably form submission, accessing form values in the request, and sessions.
The Flask tutorial covers many of these elements in some detail, and is well worth
checking out http://flask.pocoo.org/docs/0.10/tutorial/.


So that's a taste of what a very basic Python web application can look like. There are
obviously as many ways to write the same app as there are frameworks though, so
how do you choose a framework?


Firstly, it helps to have a clear idea of what you're looking to achieve with your
application. Do you require database interaction? If so, a more integrated solution
like Django may be quicker to get started with. Will you need a web-based data entry
or administration interface? Again if so, Django has this out of the box.

Free download pdf