Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

LvivPy - Flask in details


Published on

Overview of the Flask and its environment to build successful project.

Published in: Technology
  • Login to see the comments

LvivPy - Flask in details

  1. 1. Flask in details Max Klymyshyn CTO at GVMahines @maxmaxmaxmax github: joymax
  2. 2. From Django to Flask and back to Django
  3. 3. I remember when Flask appearedAnd I was one of guys who hadnt read the code when Flask was just a joke.
  4. 4. But Armin isreally nice,simple andvery smart guy
  5. 5. And when I start worked with Flask, aam...
  6. 6. Now I feel like ...
  7. 7. NA NA NA
  8. 8. Devil is in the details
  9. 9. Here is details1. Typical project structure2. Blueprints3. Database4. Forms & Validation5. Management Commands6. Assets-management7. Replacement of django.contrib.admin8. Debugging9. Unit tests and Behavior tests
  10. 10. Project structure1. pure python module: - project - - - templates - static ...2. Configuration: local_settings, settings:app.config.from_object(settings)
  11. 11. BlueprintsKind of django-apps1. Initialization:from flask import Blueprintapp = Blueprint( profile, // namespace __name__, // logical python module or // package template_folder=templates, static_folder=static )...@app.route(/sample/)def sample(): ...
  12. 12. Register blueprint1. To register use app.register_blueprint : from flask import Flask from proj.submodule.bp import app assubmodule app = Flask(__name__) app.register_blueprint( submodule, url_prefix=/submodule )2. Url namespace{{ url_for(profile.sample) }}
  13. 13. DatabaseFlask-SQLAlchemy minimongo Flask-Redis
  14. 14. Flask-SQLAlchemyExample configuration from docs:from flask import Flaskfrom flaskext.sqlalchemy import SQLAlchemyapp = Flask(__name__)app.config[SQLALCHEMY_DATABASE_URI] = sqlite:////tmp/test.dbdb = SQLAlchemy(app)
  15. 15. Flask-SQLAlchemyclass User(db.Model): id = db.Column(db.Integer, primary_key=True) username = db.Column( db.String(80), unique=True) email = db.Column( db.String(120), unique=True) def __init__(self, username, email): self.username = username = email def __repr__(self): return <User %r> % self.username
  16. 16. Flask-SQLAlchemy>>> from app import db>>> db.create_all()>>> from app import User>>> admin = User(admin,>>> guest = User(guest,>>> db.session.add(admin)>>> db.session.add(guest)>>> db.session.commit()>>> User.query.all()[<User uadmin>, <User uguest>]
  17. 17. Minimongo 1. No initial configuration needed 2. Install & start mongo - thats enoughSample model:import minimongo as mmclass Profile(mm.Model): class Meta: database = "sampleproject" collection = "profiles" indices = (mm.Index(username))
  18. 18. Minimongo>>> from app import db, User, Profile>>> admin = User.query.filter_by(... username=admin).first()>>> admin.usernameuadmin>>> profile = Profile(username=admin.username,... description=uFlask devleoper)>>> profile{username: uadmin, description: uFlaskdevleoper}>>>{username: uadmin, _id:ObjectId(4f13e019486dd09335000001), description:uFlask devleoper}
  19. 19. Minimongo>>> Profile.collectionCollection(Database(Connection(localhost,27017), usampleproject), uprofiles)>>> Profile.collection.find_one(... {username: admin.username}){uusername: uadmin, u_id:ObjectId(4f13df60486dd09335000000),udescription: uFlask devleoper}
  20. 20. Flask-Redis1. Install flask-redis2. Add to flask.ext.redis import init_redis...redis = init_redis(app)2. Quite easy to use:>>> from app import redis>>> p = redis.pipeline()>>> p.set("username", "admin")<redis.client.Pipeline object at 0x10139b350>>>> p.execute()[True]>>> redis.get("username")admin
  21. 21. Forms & Validation Flask-WTF
  22. 22. WTForms Form and Viewfrom flask.ext import wtfclass UserForm(wtf.Form): username = wtf.TextField("Username", [wtf.Required()]) email = wtf.TextField( "Email", [wtf.Required(), wtf.Email()])@app.route(/form, methods=[POST, GET])def form(): form = UserForm() if form.validate_on_submit(): flash("Success") return redirect("/form") return render_template("form.html", form=form)
  23. 23. WTForm Template{% with messages = get_flashed_messages() %} {{ ", ".join(messages or []) }}{% endwith %}<hr /><form method="post" action="/form">{{ form.csrf }} <i>{{ "; ".join(form.username.errors) }}</i> <br /> {{ form.username(size=20) }} <hr /> {{ "; ".join( }}<br /> {{ }} <hr /> <input type="submit" value="Go"></form>
  24. 24. Management CommandsWrite external scripts with current project context
  25. 25. Flask-Script1. Create script within your project directory and put(which is quite similar to Djangos flaskext.script import Managerfrom app import appmanager = Manager(app)@manager.commanddef hello(): print "hello"if __name__ == "__main__":
  26. 26. Flask-Scriptmaxk$ python shell Runs a Python shell insideFlask application context. hello runserver Runs the Flask developmentserver i.e.$ python hellohello
  27. 27. Flask-ScriptWith Flask-Script you able to:• Write custom management commands• Use existing ones like in flask-assets• Getting users input• Use command line optionsAll of abilities above already automated with Flask-Script andits really easy-to-use.
  28. 28. Assets ManagementStatic, CSS & JavaScript files
  29. 29. JS/CSS minification and so onFlask-Assets based on Webassets. To integrate weneed some work to do:1. Install Flask-Assets2. Initialize Flask-Assets environment3. Add Assets Bundles4. Configure compressors/minifiers etc. to optimize our assets5. Generate bundles with management command
  30. 30. Flask-Assets: initializing environmentimport Flaskfrom flask.ext.assets import Environment asAssetsEnvironmentapp = Flask(__name__)assets = AssetsEnvironment(app)assets.debug = Trueapp.config[ASSETS_DEBUG] = Trueapp.config[YUI_COMPRESSOR_PATH] = contrib/yuicompressor-2.4.6.jar
  31. 31. Flask-Assets: Adding filesI will show work with JavaScript only but feel free to use sameapproach with CSS files.JavaScript files directory structure: - static - js- src- core* jquery.js* underscore.js- app* module1.js* module2.js
  32. 32. Flask-Assets: adding flaskext.assets import Bundledef register_assets(assets): core = Bundle( js/src/core/jquery.js, js/src/core/underscore.js, filters=yui_js, output=js/bundle/core.js ) assets.register(core, core)
  33. 33. Flask-Assets: adding = Bundle( js/src/app/*.js, filters=yui_js, output=js/bundle/app.js)assets.register(app, app)
  34. 34. Flask-Assets: how to useSomewhere in your template code:{% assets "core" %} <script src="{{ ASSET_URL }}"></script>{% endassets %}{% assets "app" %} <script src="{{ ASSET_URL }}"></script>{% endassets %}
  35. 35. Flask-Assets: debug modeFlask-Assets generate code below (debug mode):<script src="/static/js/src/core/jquery.js"></script><script src="/static/js/src/core/underscore.js"></script><script src="/static/js/src/app/module1.js"></script><script src="/static/js/src/app/module2.js"></script>
  36. 36. Flask-Assets: production modeFlask-Assets generate code below (production mode):<script src="/static/js/bundles/core.js"></script><script src="/static/js/bundles/app.js"></script>Static files was generated with Flask-Script command:maxk$ python assets rebuild
  37. 37. More extensions: Flask-Mail Flask-Babel Flask-Cache Flask-csrf Flask-FlatPages Flask-lesscss ...
  38. 38. Admin panel Flask-Admin Flask-Dashed
  39. 39. TestsUnit, Behavior and JavaScript tests
  40. 40. Testing: Unit & BehaviorTo test templates, views etc we need to have request contextBefore
  41. 41. Behavior Testes with LettuceExample feature and scenario:Feature: Auth Scenario: Sign In as featured expert When I go to "auth.login" view Then I see that response code is 200 And Theres form with following fields: | form__username | | form__password | Fill the field "form__username" with "featured"
  42. 42. lettuce-webLettuce-web is a library which very close to headless testingusing twill. lettuce-web doesnt require browser. You canwrite your features using lettuce-web predefined steps. More here:
  43. 43. Flask-JasmineFlask-Jasmine is extension to execute Jasmine JavaScriptTests More details
  44. 44. DebuggingFlask-DebugToolbarwerkzeug debugger
  45. 45. IssuesWhats going on in Flask world at the moment?
  46. 46. Python 3Status of porting Flask to Python 3 is unknown.Werkzeug not ported yet. Hopefully, will be ported to Python3.3 ( PEP 414 for details)
  47. 47. WerkzeugWerkzeug is really huge and have tons of tools.Flask based on Werkzeug.We all like Python for small, robust and clean libraries.
  48. 48. What’s next?Flask 0.9 52
  49. 49. Thats all Questions? Source: