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

Start with Flask

8cafbb6a1b892de6f03ec6db012fb39f?s=47 barrachri
October 22, 2014

Start with Flask

A talk about starting with Flask framework

8cafbb6a1b892de6f03ec6db012fb39f?s=128

barrachri

October 22, 2014
Tweet

Transcript

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

    Start with Flask
  2. WHAT IS FLASK ? 2

  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
  4. BASICALLY. 4

  5. • Werkzeug • Jinja2 • Others small things • No

    orm • No form • Only extensions 5
  6. FLASK IS FUN. 6

  7. 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
  8. 8 $ pip install flask $ python hello.py * Running

    on http://localhost:5000/
  9. RESPONSE OBJECT. 9

  10. 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
  11. REQUEST OBJECT. 11

  12. 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()
  13. METHOD VIEW. 13

  14. 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'))
  15. RETURN A TEMPLATE. 15

  16. 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()
  17. BLUEPRINT. 17

  18. 18 from flask import Blueprint, render_template simple_page = Blueprint('simple_page', __name__,

    template_folder='templates') @simple_page.route('/') @simple_page.route('/<page>') def show(page=None): if page is not None: return render_template('pages/%s.html' % page) else: return render_template('index.html')
  19. 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()
  20. • Blueprint are not an applications • They are similar

    for some things • A blueprint is like a pluggable behavior for the main app 20
  21. USEFUL DECORATORS. 21

  22. • 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
  23. DJANGO VS FLASK. 23

  24. WHAT I LIKE OF DJANGO. 24

  25. • Full batteries (orm, form, session, user, ecc.) • Easy

    to add “app” • Great community • Stable • Popular 25
  26. BUT. 26

  27. • Sometimes it is much more than what you need

    • You need to follow Django pattern • Implement REST API is not so easy 27
  28. WHAT I LIKE OF FLASK. 28

  29. • Simple • Minimalist • Easy to learn and start

    • Well documented • Awesome as backend API 29
  30. BUT. 30

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

  32. APP = FLASK(__NAME_) 32

  33. No magic, you need to share Flask instance between your

    files, but sometimes that can be a problem. 33
  34. #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
  35. CIRCULAR IMPORT ! 35

  36. #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
  37. IT WORKS BUT NOT SO PYTHONIC (???) 37

  38. CONTEXT 38

  39. Often in your flask app you need to access the

    app context, as with app instance, sometimes that can be a problem. 39
  40. #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
  41. AGAIN IT WORKS BUT NOT SO PYTHONIC (???) 41

  42. WE ARE NOT ALONE. 42

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

  44. SOME RESOURCES. 44

  45. 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
  46. THIS IS THE END. 46

  47. DID YOU LIKE THIS TALK ? 47

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

  49. 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
  50. BRAINSTORMING & QUESTIONS TIME 50