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. • 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
  2. • Werkzeug • Jinja2 • Others small things • No

    orm • No form • Only extensions 5
  3. 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
  4. 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
  5. 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()
  6. 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'))
  7. 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()
  8. 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')
  9. 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()
  10. • Blueprint are not an applications • They are similar

    for some things • A blueprint is like a pluggable behavior for the main app 20
  11. • 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
  12. • Full batteries (orm, form, session, user, ecc.) • Easy

    to add “app” • Great community • Stable • Popular 25
  13. • Sometimes it is much more than what you need

    • You need to follow Django pattern • Implement REST API is not so easy 27
  14. • Simple • Minimalist • Easy to learn and start

    • Well documented • Awesome as backend API 29
  15. No magic, you need to share Flask instance between your

    files, but sometimes that can be a problem. 33
  16. #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
  17. #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
  18. Often in your flask app you need to access the

    app context, as with app instance, sometimes that can be a problem. 39
  19. #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
  20. 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
  21. 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