LvivPy - Flask in details
Upcoming SlideShare
Loading in...5
×
 

LvivPy - Flask in details

on

  • 6,057 views

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

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

Statistics

Views

Total Views
6,057
Views on SlideShare
6,030
Embed Views
27

Actions

Likes
8
Downloads
76
Comments
1

3 Embeds 27

https://twitter.com 25
https://si0.twimg.com 1
http://www.linkedin.com 1

Accessibility

Categories

Upload Details

Uploaded via as Apple Keynote

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n

LvivPy - Flask in details LvivPy - Flask in details Presentation Transcript

  • Flask in details Max Klymyshyn CTO at GVMahines @maxmaxmaxmax github: joymax
  • From Django to Flask and back to Django
  • I remember when Flask appearedAnd I was one of guys who hadnt read the code when Flask was just a joke.
  • But Armin isreally nice,simple andvery smart guy
  • And when I start worked with Flask, aam...
  • Now I feel like ...
  • NA NA NA
  • Devil is in the details
  • 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
  • Project structure1. pure python module: settings.py - project - app.py - views.py - templates - static ...2. Configuration: local_settings, settings:app.config.from_object(settings)
  • 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(): ...
  • 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) }}
  • DatabaseFlask-SQLAlchemy minimongo Flask-Redis
  • 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)
  • 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 self.email = email def __repr__(self): return <User %r> % self.username
  • Flask-SQLAlchemy>>> from app import db>>> db.create_all()>>> from app import User>>> admin = User(admin, admin@example.com)>>> guest = User(guest, guest@example.com)>>> db.session.add(admin)>>> db.session.add(guest)>>> db.session.commit()>>> User.query.all()[<User uadmin>, <User uguest>]
  • 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))
  • 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}>>> profile.save(){username: uadmin, _id:ObjectId(4f13e019486dd09335000001), description:uFlask devleoper}
  • 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}
  • Flask-Redis1. Install flask-redis2. Add to app.py:from 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
  • Forms & Validation Flask-WTF
  • 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)
  • 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(form.email.errors) }}<br /> {{ form.email(size=20) }} <hr /> <input type="submit" value="Go"></form>
  • Management CommandsWrite external scripts with current project context
  • Flask-Script1. Create manage.py script within your project directory and put(which is quite similar to Djangos manage.py):from flaskext.script import Managerfrom app import appmanager = Manager(app)@manager.commanddef hello(): print "hello"if __name__ == "__main__": manager.run()
  • Flask-Scriptmaxk$ python manage.py shell Runs a Python shell insideFlask application context. hello runserver Runs the Flask developmentserver i.e. app.run()maxk$ python manage.py hellohello
  • 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.
  • Assets ManagementStatic, CSS & JavaScript files
  • 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
  • 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
  • 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
  • Flask-Assets: adding bundlesassets.py:from 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)
  • Flask-Assets: adding bundles...app = Bundle( js/src/app/*.js, filters=yui_js, output=js/bundle/app.js)assets.register(app, app)
  • 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 %}
  • 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>
  • 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 manage.py assets rebuild
  • More extensions: Flask-Mail Flask-Babel Flask-Cache Flask-csrf Flask-FlatPages Flask-lesscss ...
  • Admin panel Flask-Admin Flask-Dashed
  • TestsUnit, Behavior and JavaScript tests
  • Testing: Unit & BehaviorTo test templates, views etc we need to have request contextBefore execution:self.app.test_request_context().push()After execution:self.app.test_request_context().pop()
  • 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"
  • 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: https://github.com/joymax/lettuce-web
  • Flask-JasmineFlask-Jasmine is extension to execute Jasmine JavaScriptTests More details https://github.com/joymax/flask-jasmine
  • DebuggingFlask-DebugToolbarwerkzeug debugger
  • IssuesWhats going on in Flask world at the moment?
  • 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)
  • WerkzeugWerkzeug is really huge and have tons of tools.Flask based on Werkzeug.We all like Python for small, robust and clean libraries.
  • What’s next?Flask 0.9 52
  • Thats all Questions? Source: https://github.com/joymax/kyivpy-flask-in-details