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

PyConZA 2013: "An Introduction to Flask" by Adr...

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. What is Flask? Simple web framework Similar projects: web.py Bottle

    Uses: Werkzeug (WSGI) Jinja 2 (templating)
  2. Hello world from flask import Flask app = Flask(__name__) @app.route("/")

    def hello (): return "Hello World!" if __name__ == "__main__": app.run()
  3. 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>
  4. POST / GET parameters @app.route(’/’, methods =[’GET’, ’POST ’]) def

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

    session: message = session[’message ’] else: message = "Hello world!" return render_template ( ’foo.html ’, message=message )
  6. 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 ’
  7. 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 >
  8. AJAX (2) $(function () { $(’#scramble ’). bind(’click ’, function

    () { $.getJSON($SCRIPT_ROOT + ’/_scramble ’, { message: $("#message"). text () }, function(data) { $("#message"). text(data.scrambled ); }); return false; }); });
  9. 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)