$30 off During Our Annual Pro Sale. View Details »

PyConZA 2013: "An Introduction to Flask" by Adrianna Pińska

Pycon ZA
October 04, 2013

PyConZA 2013: "An Introduction to Flask" by Adrianna Pińska

Flask is a light-weight web framework that builds on werkzeug. This talk covers:

• Serving a static HTML page
• Using Jinja 2 templates
• Storing session data
• Using AJAX from Flask

Pycon ZA

October 04, 2013
Tweet

More Decks by Pycon ZA

Other Decks in Programming

Transcript

  1. Introduction to web applications with Flask Adrianna Pi´ nska1 October

    5, 2013 1adrianna.pinska@gmail.com
  2. What is Flask? Simple web framework Similar projects: web.py Bottle

    Uses: Werkzeug (WSGI) Jinja 2 (templating)
  3. Why Flask? Clean syntax Little boilerplate Easy to set up

  4. Hello world from flask import Flask app = Flask(__name__) @app.route("/")

    def hello (): return "Hello World!" if __name__ == "__main__": app.run()
  5. Templates Jinja 2 Other engines: Genshi

  6. Jinja example @app.route("/") def hello (): return render_template ( ’foo.html

    ’, message="Hello World!" ) <!doctype html > <link rel="stylesheet" href= "{{ url_for(’static ’, filename=’styles.css ’)}}"> <p id="message">{{ message }}</p>
  7. URL variables @app.route("/") @app.route("/<message >") def hello(message="Hello World!"): return render_template

    ( ’foo.html ’, message=message )
  8. POST / GET parameters @app.route(’/’, methods =[’GET’, ’POST ’]) def

    hello (): return render_template ( ’foo.html ’, message=request.args.get( ’message ’, "Hello world!") )
  9. Sessions (1) @app.route("/") def hello (): if ’message ’ in

    session: message = session[’message ’] else: message = "Hello world!" return render_template ( ’foo.html ’, message=message )
  10. Sessions (2) @app.route("/<message >") def put_message(message ): session[’message ’] =

    message return render_template ( ’foo.html ’, message="Message ’%s’ saved!" % message ) app.secret_key = ’super secret random string ’
  11. Sessions (3) Size limit: 4K Server-side sessions Recreate objects

  12. Make it do stuff Local scripting Forms AJAX

  13. AJAX (1) <p id="scramble">Scramble!</p> <script >$SCRIPT_ROOT = {{ request.script_root |tojson|safe

    }};</script > <script src="{{ url_for(’static ’, filename=’jquery.js ’) }}"></script > <script src="{{ url_for(’static ’, filename=’myscript.js ’)}}"></script >
  14. AJAX (2) $(function () { $(’#scramble ’). bind(’click ’, function

    () { $.getJSON($SCRIPT_ROOT + ’/_scramble ’, { message: $("#message"). text () }, function(data) { $("#message"). text(data.scrambled ); }); return false; }); });
  15. AJAX (3) @app.route(’/_scramble ’) def scramble (): message = request.args.get(’message

    ’) l = list(message) random.shuffle(l) scrambled = ’’.join(l) return jsonify(scrambled=scrambled)
  16. More information http://flask.pocoo.org/ #pocoo on Freenode