0% found this document useful (0 votes)
49 views27 pages

Introduction To Flask

Uploaded by

ahmed.ghannam
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
49 views27 pages

Introduction To Flask

Uploaded by

ahmed.ghannam
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

INTRODUCTION TO FLASK

MIGUEL GRINBERG
@miguelgrinberg
miguel.grinberg@gmail.com
WHAT IS FLASK?
Server-side web micro-framework for Python
Very small: ~2100 LOC
Well documented
Runs on Python 2.6, 2.7 and 3.3
Dependencies:
Werkzeug: routing, debugger, WSGI support
Jinja2: templating
FLASK FEATURES
Request dispatcher
Template engine
Secure cookies
User sessions
Unit testing
For the developer
Web server
In-browser debugger
Reloader
FLASK MISSING FEATURES
Database access
Web form validation
User authentication and authorization
Email support
Caching
Administration
... and more

REALLY???
FLASK IS EXTENSIBLE
Designed to be extended with third party packages.
Regular Python packages can be used directly.
Flask extensions are easy to write and integrate.
Extensions are available for most tasks.
FLASK IS MODULAR
Just install the packages and extensions that you need and
nothing more.
Your development stack has no cruft!
INSTALLING FLASK
Linux and Mac users
~/myapp $ virtualenv venv
~/myapp $ source venv/bin/activate
(venv) ~/myapp $ pip install flask

Windows users (*)


C:\myapp>virtualenv venv
C:\myapp>venv\scripts\activate
(venv) C:\myapp>pip install flask

(*) If you want to experience Unix power on Windows, try http://cygwin.org. This is not a VM!
ANATOMY OF A FLASK APPLICATION
1. Initialize and configure application
2. Define routes and view functions
3. Start the development web server
from flask import Flask
app = Flask(__name__)

@app.route('/')
def index():
return '<h1>Hello World!</h1>'

if __name__ == '__main__':
app.run(debug = True)
ANATOMY OF A FLASK APPLICATION
That's it!
(venv) ~/hello $ python hello.py
* Running on http://127.0.0.1:5000/
* Restarting with reloader
DYNAMIC ROUTES
from flask import Flask
app = Flask(__name__)

@app.route('/')
def index():
return '<h1>Hello World!</h1>'

@app.route('/index/<name>')
def hello(name):
return '<h1>Hello, %s!</h1>' % name

if __name__ == '__main__':
app.run(debug = True)
DYNAMIC ROUTES
TEMPLATES
from flask import Flask, render_template
app = Flask(__name__)

@app.route('/')
def index():
return '<h1>Hello World!</h1>'

@app.route('/index/<name>')
def hello(name):
return render_template('index.html', name = name)

if __name__ == '__main__':
app.run(debug = True)

templates/index.html
<h1>Hello, {{ name }}!</h1>
TWITTER BOOTSTRAP
Install the extension
(venv) ~/hello $ pip install flask-bootstrap
TWITTER BOOTSTRAP
from flask import Flask, render_template
from flask.ext.bootstrap import Bootstrap
app = Flask(__name__)
bootstrap = Bootstrap(app)

# ...

@app.route('/index/<name>')
def hello(name):
return render_template('index.html', name = name)

if __name__ == '__main__':
app.run(debug = True)

templates/index.html
{% extends "bootstrap_responsive.html" %}
{% block body_content %}
<div class="container">
<div class="page-header">
<h1>Hello, {{ name }}!</h1>
</div>
</div>
{% endblock %}
TWITTER BOOTSTRAP
FORMS
Install the extension
(venv) ~/hello $ pip install flask-wtf
FORMS
# ...
from flask.ext.wtf import Form
from wtforms import TextField
from wtforms.validators import Required

app = Flask(__name__)
app.config['SECRET_KEY'] = 'hard to guess string'
bootstrap = Bootstrap(app)

class NameForm(Form):
name = TextField('What is your name?', validators = [ Required() ])

@app.route('/', methods = ['GET', 'POST'])


@app.route('/index', methods = ['GET', 'POST'])
def index():
name = None
form = NameForm()
if form.validate_on_submit():
name = form.name.data
form.name.data = ''
return render_template('index.html', form = form, name = name)

# ...
FORMS
{% extends "bootstrap_responsive.html" %}
{% import "bootstrap_wtf.html" as wtf %}

{% block body_content %}
<div class="container">
<div class="page-header">
{% if name %}
<h1>Hello, {{ name }}!</h1>
{% endif %}
</div>

{{ wtf.quick_form(form) }}
</div>
{% endblock %}
FORMS
Initial state
FORMS
After valid input
FORMS
After invalid input
REDIRECTS AND USER SESSIONS
from flask import Flask, render_template, redirect, url_for, session

# ...

@app.route('/', methods = ['GET', 'POST'])


@app.route('/index', methods = ['GET', 'POST'])
def index():
form = NameForm()
if form.validate_on_submit():
session['name'] = form.name.data
form.name.data = ''
return redirect(url_for('index'))
return render_template('index.html',
form = form, name = session.get('name'))

# ...
LARGE APPLICATION STRUCTURE
|-[root folder]
|-venv/ Virtual environment
|-app/ Application package
|-templates/ Template files
|-static/ Static files
|-__init__.py Application creation
|-*.py Routes, models, forms, etc.
|-tests/ Unit tests
|-requirements.txt Dependencies
|-config.py Configuration
|-manage.py Server startup and admin tasks
BLUEPRINTS
Subset of the application stored in a separate Python
package
Contains any combination of static files, templates and
routes
Very useful for extensions that attach new behavior to
applications
BLUEPRINTS
|-[root folder]
|-venv/
|-app/
|-[blueprint]/ Blueprint package
|-templates/ Template files
|-static/ Static files
|-__init__.py Blueprint instance creation
|-*.py Routes, models, forms, etc.
|-templates/
|-static/
|-__init__.py Application creation & blueprint hookup
|-*.py
|-tests/
|-requirements.txt
|-config.py
|-manage.py
RESOURCES
http://github.com/miguelgrinberg/Flask-Intro
Sample code from this presentation
http://flask.pocoo.org
Official documentation and tutorial
Support: mailing list, IRC channel
http://blog.miguelgrinberg.com/category/Flask
Mega-Tutorial, RESTful API articles and more
Extensions
Official registry at http://flask.pocoo.org/extensions/
Other good places to search: github, PyPI, Google
http://stackoverflow/questions/tagged/flask
Nice collection of questions with answers
Ask your own!
THANKS!
Feedback, questions, etc:

@miguelgrinberg
miguel.grinberg@gmail.com

You might also like