Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


advertisement
 

Getting Started with the Flask Web Framework

Building Web applications is hard. Learn more about Flask -- a Python Web framework that takes care of much of the hard work and allows you to focus on the essence of your application.


advertisement

Web applications are arguably the most common type of application developed these days. The browser is ubiquitous and writing a Web application ensures that your application will be able to run everywhere (although you'll probably need to take some care to ensure it looks good on different form factors). Web applications do a lot and writing them from scratch takes a great deal of effort. A lot of the hard work is generic and is not related to the application itself. In this article, I'll introduce you to Flask — a Python Web framework that takes care of much of the hard work and allows you to focus on the essence of your application.

Flask - The Big Picture

Flask is a very flexible and modular Web framework. It is built on top of Werkzeug, which takes care of all the low-level WSGI and HTTP details. Flask adds templating, routing, testing capabilities, organizational patterns via blueprints and a sensible extension mechanism with a huge number of useful extensions.

Simple Application

Let's see what a simple application looks like. If you want to follow along, install Flask first.



The beauty of Flask is that it scales from really simple one file applications to serious multi-module and multi-package applications.

from flask import Flask
app = Flask(__name__)
@app.route('/')
def hi_there():
return 'Hi There!'
if __name__ == '__main__':
app.run()

The Web application is an instance of the Flask class. The route is defined using the @app.route decorator. The decorated hi_there() function is the Web method that is called when you navigate to the root of the application.

Flask comes with a built-in test server, so to test your application locally just run this file. Flask will launch its test server on port 5000 by default and you can go in your browser to http://localhost:5000 and see the following message:

http://i.imgur.com/zq8TCJe.png

Views

This is super quick and easy, but typically you would want to return HTML/CSS/JavaScript and not just plain text. Flask has got you covered with Jinja2 templates.

Let's extend our little application to return the current time. I'll add some structure as follows:

.
??? app.py
??? templates
??? app.html 

Our main app.py file now looks like:

from flask import Flask, render_template
import date as datetime
app = Flask(__name__)
@app.route('/')
def hi_there():
now = datetime.now().replace(microsecond=0)
return render_template('app.html', now=now)
if __name__ == '__main__':
app.run(debug=True)

It imports the render_template() from flask and instead of return "Hi There!" as before, it renders the template "app.html" passing it the current time. By convention (can be configured), Flask is looking for templates in the templates sub-directory, which is exactly where I put the "app.html" file. Let's take a look:

<html>
<body background="http://i.imgur.com/X963eGf.jpg">
Hi There! The time is {{ now }}
</body>
</html>

That file looks suspiciously like a regular HTML file. Jinja2 templates are pretty much valid HTML files, but with some special syntax for injecting dynamic code and substituting variables. In this case "{{ now }}" will be replaced with the value of the "now" variable that the hi_there() function passed to render_template(). Every time someone browses to our application they'll get the current server time.

If you run the application again and browse to http://localhost:5000 you should see this beautiful result:

Other Stuff you can do with Flask

All this is barely scratching the surface. Flask and its extensions provide everything you need for full-fledged applications from login and user management to forms and even REST APIs. Strong database integration with Flask-SQLAlchemy. It supports organizing large applications into components using blueprints and can be deployed on all major hosting platforms and Web servers as it is a standard WSGI framework too.

Conclusion

Flask is a great Web framework. Very easy to get going, but scales for complex systems. It is very popular and has lots of excellent extensions. On top of it all, it has superb documentation, books and tutorials. If you are considering Web development using Python on the back end, I recommend you take a serious look at Flask.



   
Gigi Sayfan is the chief platform architect of VRVIU, a start-up developing cutting-edge hardware + software technology in the virtual reality space. Gigi has been developing software professionally for 21 years in domains as diverse as instant messaging, morphing, chip fabrication process control, embedded multi-media application for game consoles, brain-inspired machine learning, custom browser development, web services for 3D distributed game platform, IoT/sensors and most recently virtual reality. He has written production code every day in many programming languages such as C, C++, C#, Python, Java, Delphi, Javascript and even Cobol and PowerBuilder for operating systems such as Windows (3.11 through 7), Linux, Mac OSX, Lynx (embedded) and Sony Playstation. His technical expertise includes databases, low-level networking, distributed systems, unorthodox user interfaces and general software development life cycle.
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date