Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Large-Scale Applications with Flask: Doing More...

Large-Scale Applications with Flask: Doing More With Less

In this session I show you how you can take Flask, a so-called "microframework", and write readable, usable, testable and intelligent code for all of your macro-scale applications. We'll go through basic API design, ORM integration (including some popular non-relational databases), modular design with blueprints, and testing. By the end of this talk, you'll understand why Flask is the little framework that lets you do a lot, and be armed with the tools & knowledge to write applications of all sizes.

Joël Perras

March 02, 2012
Tweet

More Decks by Joël Perras

Other Decks in Technology

Transcript

  1. from flask import Flask app = Flask(__name__) @app.route("/") def hello():

    return "Hello World!" if __name__ == "__main__": Friday, 2 March, 12
  2. from flask import Flask app = Flask(__name__) @app.route("/") def hello():

    return "Hello World!" if __name__ == "__main__": app.run() Friday, 2 March, 12
  3. from werkzeug.routing import BaseConverter class ListConverter(BaseConverter): def to_python(self, value): return

    value.split(',') def to_url(self, values): return ','.join(BaseConverter.to_url(value) for value in values) app = Flask(__name__) app.url_map.converters['list'] = ListConverter Friday, 2 March, 12
  4. from flask import Flask from flaskext.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 def __repr__(self): return '<User %r>' % self.username Friday, 2 March, 12
  5. from flask import Flask from mongokit import Connection, Document #

    configuration MONGODB_HOST = 'localhost' MONGODB_PORT = 27017 # create the little application object app = Flask(__name__) app.config.from_object(__name__) # connect to the database connection = Connection(app.config['MONGODB_HOST'], app.config['MONGODB_PORT']) Friday, 2 March, 12
  6. class Post(Document): structure = { 'title':unicode, 'body':unicode, 'author':unicode, 'date_creation':datetime.datetime, 'rank':int,

    'tags': [unicode], } required_fields = ['title','author', 'date_creation'] default_values = {'rank':0, 'date_creation': datetime.datetime.utcnow} Friday, 2 March, 12
  7. from flask import Blueprint, render_template, abort from jinja2 import TemplateNotFound

    static_page = Blueprint('static_page', __name__, template_folder='templates') @static_page.route('/<page>') def show(page): try: return render_template('pages/%s.html' % page) except TemplateNotFound: abort(404) Friday, 2 March, 12
  8. from flask import Flask from myapp.static_page import static_page app =

    Flask(__name__) app.register_blueprint(static_page, url_prefix= ‘/pages’) Friday, 2 March, 12
  9. from flask.views import View class ShowUsers(View): def dispatch_request(self): users =

    User.query.all() return render_template('users.html', objects=users) app.add_url_rule('/users/', ShowUsers.as_view('show_users')) Friday, 2 March, 12
  10. from flask.views import View class ListView(View): def get_template_name(self): raise NotImplementedError()

    def render_template(self, context): return render_template(self.get_template_name(), **context) def dispatch_request(self): context = {'objects': self.get_objects()} return self.render_template(context) class UserView(ListView): def get_template_name(self): return 'users.html' def get_objects(self): return User.query.all() Friday, 2 March, 12
  11. from flask.views import MethodView class User(MethodView): def get(self): users =

    User.query.all() ... def post(self): user = User.from_form_data(request.form) ... app.add_url_rule('/users/', view_func=User.as_view('users')) Friday, 2 March, 12