Apps in 10 minutes: Flask cheatsheet

Flask is a micro framework for python webapp. It’s really useful for creating prototypes and small application focusing on the logic.

Here’s a cheatsheet!

#!/usr/bin/python
# Import Flask
# and md5 algorithm
from flask import Flask
from flask import request, abort
from hashlib import md5

# Create a new application
app = Flask(__name__)

# Bind methods and functions
@app.route(‘/’)
def index():
 return ‘Index Page’

@app.route(‘/hello’, methods = [‘GET’, ‘POST’])
def hello():
 ”””Greets the user.”””
 # Those are get parameters
 user, client = map(request.args.get, [‘user’, ‘client’])
 return ‘Hello %s!’ % user

# do this BEFORE each request
@app.before_request
def authorizer():
 ”””Authenticate user and password passed via GET or POST.
  In this sample the password is the md5(user).
  Use the abort function to raise an http error!
 ”””
 params = [‘user’, ‘client’,’passwd’,’algorithm’]
 user, client, passwd, algorithm = map(request.values.get, params)
 if passwd != md5(user).hexdigest():
  abort(401)

@app.errorhandler(401)
def unauthorized(e):
 ”””Use error handlers to present error pages.”””
 return “Unauthorized user”, 404

# Run the app
if __name__ == ‘__main__’:
 app.debug = True
 app.run(host=’0.0.0.0′, port=9000)

Lascia un commento