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

Start with Flask

barrachri
October 22, 2014

Start with Flask

A talk about starting with Flask framework

barrachri

October 22, 2014
Tweet

More Decks by barrachri

Other Decks in Programming

Transcript

  1. Christian Barra
    @christianbarra
    www.chrisbarra.me
    1
    Meetup Python Milan - 21/10/2014
    Start with Flask

    View full-size slide

  2. WHAT IS FLASK ?
    2

    View full-size slide

  3. • Flask is a “micro” framework
    • micro means that Flask keep the core simple but
    extensible
    • Flask won’t make many decisions for you, such as
    what database to use
    3

    View full-size slide

  4. • Werkzeug
    • Jinja2
    • Others small things
    • No orm
    • No form
    • Only extensions
    5

    View full-size slide

  5. FLASK IS FUN.
    6

    View full-size slide

  6. 7
    from flask import Flask # Import Flask class
    app = Flask(__name__) # Create a new Flask instance
    @app.route(“/“) # Flask routing system
    def index(): # Your view
    return "Hello World”
    if __name__ == "__main__":
    app.run() # Run development server

    View full-size slide

  7. 8
    $ pip install flask
    $ python hello.py
    * Running on http://localhost:5000/

    View full-size slide

  8. RESPONSE OBJECT.
    9

    View full-size slide

  9. from flask import Flask, jsonify
    app = Flask(__name__)
    @app.route("/")
    def index():
    msg = {"type": False, "code": "Something went wrong"}
    # Return a json object with 500 status code
    return jsonify(msg), 500
    if __name__ == "__main__":
    app.run()
    10

    View full-size slide

  10. REQUEST OBJECT.
    11

    View full-size slide

  11. 12
    from flask import Flask, request
    app = Flask(__name__)
    @app.route("/", methods=[‘POST'])
    # You can specific methods for every view
    def index():
    # create a dict with request data
    data = request.json
    user = request.json[‘user’]
    … … …
    return "I got your data !”
    if __name__ == "__main__":
    app.run()

    View full-size slide

  12. METHOD VIEW.
    13

    View full-size slide

  13. 14
    from flask.views import MethodView
    class UserAPI(MethodView):
    def get(self):
    return "This is a GET request"
    def post(self):
    return "This is a POST request"
    def put(self):
    return "This is a PUT request"
    def delete(self):
    return "This is a DELETE request”
    app.add_url_rule('/', view_func=UserAPI.as_view('users'))

    View full-size slide

  14. RETURN A TEMPLATE.
    15

    View full-size slide

  15. 16
    from flask import Flask, render_template
    app = Flask(__name__)
    @app.route("/")
    def index():
    user = "Rag. Fantozzi"
    return render_template("index.html", user=user)
    if __name__ == "__main__":
    app.run()

    View full-size slide

  16. BLUEPRINT.
    17

    View full-size slide

  17. 18
    from flask import Blueprint, render_template
    simple_page = Blueprint('simple_page', __name__,
    template_folder='templates')
    @simple_page.route('/')
    @simple_page.route('/')
    def show(page=None):
    if page is not None:
    return render_template('pages/%s.html' % page)
    else:
    return render_template('index.html')

    View full-size slide

  18. 19
    from flask import Flask
    from yourapplication.simple_page import simple_page
    app = Flask(__name__)
    app.register_blueprint(simple_page)
    if __name__ == "__main__":
    app.run()

    View full-size slide

  19. • Blueprint are not an applications
    • They are similar for some things
    • A blueprint is like a pluggable behavior for the main
    app
    20

    View full-size slide

  20. USEFUL DECORATORS.
    21

    View full-size slide

  21. • route: registers functions to handle routes
    • before_request: registers a function to run before
    request handlers
    • before_first_request: is similar, but only once at start
    • after_request: registers a function to run after request
    handlers run
    • teardown_request: registers a function to run after
    request handlers run, even if they throw an exception
    • errorhandler: defines a custom error handler
    22

    View full-size slide

  22. DJANGO VS FLASK.
    23

    View full-size slide

  23. WHAT I LIKE OF DJANGO.
    24

    View full-size slide

  24. • Full batteries (orm, form, session, user, ecc.)
    • Easy to add “app”
    • Great community
    • Stable
    • Popular
    25

    View full-size slide

  25. • Sometimes it is much more than what you need
    • You need to follow Django pattern
    • Implement REST API is not so easy
    27

    View full-size slide

  26. WHAT I LIKE OF FLASK.
    28

    View full-size slide

  27. • Simple
    • Minimalist
    • Easy to learn and start
    • Well documented
    • Awesome as backend API
    29

    View full-size slide

  28. • app = Flask(__name__)
    • context
    31

    View full-size slide

  29. APP = FLASK(__NAME_)
    32

    View full-size slide

  30. No magic, you need to share Flask instance between
    your files, but sometimes that can be a problem.
    33

    View full-size slide

  31. #views.py
    from flask import Flask
    from models import db
    app = Flask(__name__)
    #models.py
    from flask.ext.sqlalchemy import SQLAlchemy
    from views import app
    db = SQLAlchemy(app)
    34

    View full-size slide

  32. CIRCULAR IMPORT !
    35

    View full-size slide

  33. #factory.py
    from flask.ext.sqlalchemy import SQLAlchemy
    db = SQLAlchemy()
    def create_app(name):
    from flask import Flask
    app = Flask(name)
    db.init(app)
    return app
    #views.py
    from factory import create_app
    from models import db, OthersModels
    app = create_app(__name__)
    #models.py
    from factory import db
    36

    View full-size slide

  34. IT WORKS BUT NOT SO PYTHONIC (???)
    37

    View full-size slide

  35. Often in your flask app you need to access the app
    context, as with app instance, sometimes that can be
    a problem.
    39

    View full-size slide

  36. #factory.py
    … … …
    def make_celery(package_name, app=None):
    from celery import Celery
    app = app or create_app(package_name)
    celery = Celery(package_name,
    broker=app.config['CELERY_BROKER_URL'])
    celery.conf.update(app.config)
    TaskBase = celery.Task
    class ContextTask(TaskBase):
    abstract = True
    def __call__(self, *args, **kwargs):
    with app.app_context():
    return TaskBase.__call__(self, *args, **kwargs)
    celery.Task = ContextTask
    return celery
    40

    View full-size slide

  37. AGAIN IT WORKS BUT NOT SO PYTHONIC (???)
    41

    View full-size slide

  38. WE ARE NOT ALONE.
    42

    View full-size slide

  39. Tornado ?
    Falcon ?
    Wheezy Web ?
    Others ?
    43

    View full-size slide

  40. SOME RESOURCES.
    44

    View full-size slide

  41. Flask - http://flask.pocoo.org
    Flask list - http://librelist.com/browser/flask/
    Miguel Grinberg - http://blog.miguelgrinberg.com/
    Real Python - https://realpython.com/blog/
    Google - http://goo.gl/Rps6vo
    45

    View full-size slide

  42. THIS IS THE END.
    46

    View full-size slide

  43. DID YOU LIKE THIS TALK ?
    47

    View full-size slide

  44. GREAT BECAUSE I’M LOOKING
    FOR A PART TIME JOB.
    48

    View full-size slide

  45. class part_time_job():
    location = "Milan or remotely"
    current = "A wanna be data scientist"
    doing = ["Statistic at Bicocca", "read", "travel", "code"]
    knowledge = {}
    knowledge["Python"] = ["Django", "Flask", "Pandas", "…"]
    knowledge["JS"] = ["Nodejs", "AngularJS", “D3.js", "…"]
    knowledge["Database"] = ["PostgreSQL", "Redis", "…"]
    knowledge["Other"] = ["Machine learning", "much more !"]
    print("Do you want to hire me ?")
    print("My email {}@{}.com").format("barrachri", "gmail")
    49

    View full-size slide

  46. BRAINSTORMING
    &
    QUESTIONS
    TIME
    50

    View full-size slide