7. Python Package Management
PIP:
Allows you to download python packages on
the fly:
http://www.pip-installer.org/en/latest/installing.html
pip install packagename==versionNumber
8. Virtualenv
Creates isolated python environments and
install an applications requirements
Command line
virtualenv venv
. venv/bin/activate
pip install -r requirements.
txt
requirements.txt
flask==0.10.1
12. Routing: variable urls
@app.route('/user/<username>')
def show_user_profile(username):
# show the user profile for that user
return 'User %s' % username
@app.route('/post/<int:post_id>')
def show_post(post_id):
# show the post with the given id, the id is an integer
return 'Post %d' % post_id
14. Templates: Jinga
{% extends "layout.html" %}
{% block body %}
<ul>
{% for user in users %}
<li><a href="{{ user.url }}">{{ user.username }}</a></li>
{% endfor %}
</ul>
{% endblock %}
Jinga Documentation
15. Models: classes
Models are abstractions of database tables
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/test.db'
db = SQLAlchemy(app)
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(80), unique=True)
email = db.Column(db.String(120), unique=True)
def __init__(self, username, email):
self.username = username
self.email = email
16. Models: operations
# create a user
jen = User(username=”jen”, email=”jen@email.
com”)
# save user to database
db.session.add(jen)
db.session.commit()
# retrieve user
jen =db.session.query.filter_by(username=”jen”).
first()
17. Favorite Flask Modules
● Flask-Sqlalchemy(for database interaction)
note: flask-sqlalchemy is a sqlalchemy wrapper for flask, and their syntax
differs. Make sure you use the correct documentation.
● Flask-Security (for user management)
● WTForms(for forms)