SlideShare a Scribd company logo
Flask in details
           Max Klymyshyn
        CTO at GVMahines

          @maxmaxmaxmax
            github: joymax
From Django to Flask

    and back to Django
I remember when Flask appeared

And I was one of guys who hadn't
         read the code
  when Flask was just a joke.
LvivPy - Flask in details
But Armin is
really nice,
simple and
very smart guy
And when I start worked with Flask,
              aam...
LvivPy - Flask in details
Now I feel like ...
NA NA NA
Devil is in the details
Here is details
1. Typical project structure
2. Blueprints
3. Database
4. Forms & Validation
5. Management Commands
6. Assets-management
7. Replacement of django.contrib.admin
8. Debugging
9. Unit tests and Behavior tests
Project structure
1. pure python module:

 settings.py
 - project
   - app.py
   - views.py
   - templates
   - static
   ...

2. Configuration: local_settings, settings:

app.config.from_object(settings)
Blueprints
Kind of django-apps
1. Initialization:
from flask import Blueprint
app = Blueprint(
       'profile', // namespace
       __name__, // logical python module or
                   // package
       template_folder='templates',
       static_folder='static'
       )
...
@app.route('/sample/')
def sample():
       ...
Register blueprint
1. To register use app.register_blueprint :
      from flask import Flask
      from proj.submodule.bp import app as
submodule

      app = Flask(__name__)
      app.register_blueprint(
          submodule,
          url_prefix='/submodule'
      )
2. Url namespace
{{ url_for('profile.sample') }}
Database
Flask-SQLAlchemy
    minimongo
    Flask-Redis
Flask-SQLAlchemy
Example configuration from docs:

from flask import Flask
from flaskext.sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 
    'sqlite:////tmp/test.db'
db = SQLAlchemy(app)
Flask-SQLAlchemy
class 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 u'admin'>, <User u'guest'>]
Minimongo
 1. No initial configuration needed
 2. Install & start mongo - that's enough
Sample model:

import minimongo as mm

class 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.username
u'admin'
>>> profile = Profile(username=admin.username,
... description=u'Flask devleoper')
>>> profile
{'username': u'admin', 'description': u'Flask
devleoper'}
>>> profile.save()
{'username': u'admin', '_id':
ObjectId('4f13e019486dd09335000001'), 'description':
u'Flask devleoper'}
Minimongo
>>> Profile.collection
Collection(Database(Connection('localhost',
27017), u'sampleproject'), u'profiles')

>>> Profile.collection.find_one(
... {'username': admin.username})
{u'username': u'admin', u'_id':
ObjectId('4f13df60486dd09335000000'),
u'description': u'Flask devleoper'}
Flask-Redis
1. Install flask-redis
2. 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 View
from flask.ext import wtf

class 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 Commands

Write external scripts with current
         project context
Flask-Script
1. Create manage.py script within your project directory and put
(which is quite similar to Django's manage.py):

from flaskext.script import Manager
from app import app

manager = Manager(app)

@manager.command
def hello():
    print "hello"

if __name__ == "__main__":
    manager.run()
Flask-Script
maxk$ python manage.py
  shell      Runs a Python shell inside
Flask application context.
  hello
  runserver Runs the Flask development
server i.e. app.run()

maxk$ python manage.py hello
hello
Flask-Script
With Flask-Script you able to:

•   Write custom management commands
•   Use existing ones like in flask-assets
•   Getting user's input
•   Use command line options

All of abilities above already automated with Flask-Script and
it's really easy-to-use.
Assets Management

Static, CSS & JavaScript files
JS/CSS minification and so on
Flask-Assets based on Webassets. To integrate we
need some work to do:

1. Install Flask-Assets
2. Initialize Flask-Assets environment
3. Add Assets Bundles
4. Configure compressors/minifiers etc. to optimize
   our assets
5. Generate bundles with management command
Flask-Assets: initializing environment
import Flask
from flask.ext.assets import Environment as
AssetsEnvironment

app = Flask(__name__)
assets = AssetsEnvironment(app)
assets.debug = True

app.config['ASSETS_DEBUG'] = True

app.config['YUI_COMPRESSOR_PATH'] = 'contrib/
yuicompressor-2.4.6.jar'
Flask-Assets: Adding files
I will show work with JavaScript only but feel free to use same
approach with CSS files.
JavaScript files directory structure:

 - static
   - js
- src
- core
* jquery.js
* underscore.js
- app
* module1.js
* module2.js
Flask-Assets: adding bundles
assets.py:

from flaskext.assets import Bundle

def 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)
LvivPy - Flask in details
Flask-Assets: how to use
Somewhere in your template code:

{% assets "core" %}
    <script src="{{ ASSET_URL }}"></script>
{% endassets %}

{% assets "app" %}
    <script src="{{ ASSET_URL }}"></script>
{% endassets %}
Flask-Assets: debug mode
Flask-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 mode
Flask-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
Tests

Unit, Behavior and JavaScript tests
LvivPy - Flask in details
Testing: Unit & Behavior
To test templates, views etc we need to have request context

Before execution:

self.app.test_request_context().push()

After execution:

self.app.test_request_context().pop()
Behavior Testes with Lettuce
Example 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 There's form with following fields:
                   | form__username |
                   | form__password |
            Fill the field "form__username" with "featured"
lettuce-web
Lettuce-web is a library which very close to headless testing
using twill. lettuce-web doesn't require browser. You can
write your features using lettuce-web predefined steps.



                       More here:
        https://github.com/joymax/lettuce-web
Flask-Jasmine
Flask-Jasmine is extension to execute Jasmine JavaScript
Tests



                       More details
        https://github.com/joymax/flask-jasmine
Debugging

Flask-DebugToolbar
werkzeug debugger
Issues

What's going on in Flask world at
          the moment?
Python 3
Status of porting Flask to Python 3 is unknown.

Werkzeug not ported yet. Hopefully, will be ported to Python
3.3 ( PEP 414 for details)
Werkzeug
Werkzeug 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
That's all
                  Questions?


                    Source: 
https://github.com/joymax/kyivpy-flask-in-details
LvivPy - Flask in details

More Related Content

PDF
Python Flask Tutorial For Beginners | Flask Web Development Tutorial | Python...
PDF
Build website in_django
PPTX
Flask – Python
PDF
Flask patterns
PDF
Flask Introduction - Python Meetup
PDF
Quick flask an intro to flask
PDF
Flask Basics
PDF
Web develop in flask
Python Flask Tutorial For Beginners | Flask Web Development Tutorial | Python...
Build website in_django
Flask – Python
Flask patterns
Flask Introduction - Python Meetup
Quick flask an intro to flask
Flask Basics
Web develop in flask

What's hot (20)

PPTX
Build restful ap is with python and flask
PPTX
PDF
Kyiv.py #17 Flask talk
PPT
Learn flask in 90mins
PDF
Python Flask app deployed to OPenShift using Wercker CI
PDF
Rest API using Flask & SqlAlchemy
PDF
Flask RESTful Flask HTTPAuth
PPTX
Python/Flask Presentation
PPTX
Flask vs. Django
PDF
Building a Dynamic Website Using Django
PPTX
Django Architecture Introduction
PPTX
Laravel Beginners Tutorial 1
PPTX
Django Girls Tutorial
PDF
Scalable web application architecture
PPTX
Laravel5 Introduction and essentials
PDF
4 introduction-php-mvc-cakephp-m4-controllers-slides
PPTX
REST APIs in Laravel 101
PPTX
Laravel 5
PDF
Laravel 101
PPT
Installation of Joomla on Windows XP
Build restful ap is with python and flask
Kyiv.py #17 Flask talk
Learn flask in 90mins
Python Flask app deployed to OPenShift using Wercker CI
Rest API using Flask & SqlAlchemy
Flask RESTful Flask HTTPAuth
Python/Flask Presentation
Flask vs. Django
Building a Dynamic Website Using Django
Django Architecture Introduction
Laravel Beginners Tutorial 1
Django Girls Tutorial
Scalable web application architecture
Laravel5 Introduction and essentials
4 introduction-php-mvc-cakephp-m4-controllers-slides
REST APIs in Laravel 101
Laravel 5
Laravel 101
Installation of Joomla on Windows XP
Ad

Viewers also liked (20)

PDF
Python and Flask introduction for my classmates Презентация и введение в flask
PDF
Snakes on the Web
PDF
Introduction to Python and Web Programming
PDF
Python and the Web
PDF
Flask admin vs. DIY
ODP
Why Python Web Frameworks Are Changing the Web
PDF
Спецификация WSGI (PEP-333)
PDF
An Introduction to Twisted
PPTX
Python talk web frameworks
PDF
Зоопарк python веб-фреймворков
PPTX
Чем Python плох для стартапа?
PPT
CHC Thesis #1
PDF
STS Thesis by Hall 2015
PPTX
Asynchronous Python with Twisted
PDF
Writing your first web app using Python and Flask
PPTX
Django vs Flask
PDF
Framework Battle: Django vs Flask vs Chalice
PDF
Python and you
PDF
Async Web Frameworks in Python
PDF
Web Scraping with Python
Python and Flask introduction for my classmates Презентация и введение в flask
Snakes on the Web
Introduction to Python and Web Programming
Python and the Web
Flask admin vs. DIY
Why Python Web Frameworks Are Changing the Web
Спецификация WSGI (PEP-333)
An Introduction to Twisted
Python talk web frameworks
Зоопарк python веб-фреймворков
Чем Python плох для стартапа?
CHC Thesis #1
STS Thesis by Hall 2015
Asynchronous Python with Twisted
Writing your first web app using Python and Flask
Django vs Flask
Framework Battle: Django vs Flask vs Chalice
Python and you
Async Web Frameworks in Python
Web Scraping with Python
Ad

Similar to LvivPy - Flask in details (20)

PDF
Filling the flask
PDF
What The Flask? and how to use it with some Google APIs
PPTX
Developing Flask Extensions
PPTX
SW Security Lec4 Securing architecture.pptx
PDF
Django tricks (2)
PDF
Symfony2 revealed
PDF
Lean Php Presentation
PDF
Building and deploying React applications
PDF
Flask jwt authentication tutorial
PDF
Python RESTful webservices with Python: Flask and Django solutions
PDF
20130528 solution linux_frousseau_nopain_webdev
PPT
Mini Curso Django Ii Congresso Academico Ces
PDF
A I R Presentation Dev Camp Feb 08
PDF
Maxim Salnikov - Service Worker: taking the best from the past experience for...
PDF
Flask - Backend com Python - Semcomp 18
PPT
Red5 - PHUG Workshops
PPTX
Laravel development (Laravel History, Environment Setup & Laravel Installatio...
PDF
Creating Sentiment Line Chart with Watson
PDF
Grâce aux tags Varnish, j'ai switché ma prod sur Raspberry Pi
PDF
Mini Curso de Django
Filling the flask
What The Flask? and how to use it with some Google APIs
Developing Flask Extensions
SW Security Lec4 Securing architecture.pptx
Django tricks (2)
Symfony2 revealed
Lean Php Presentation
Building and deploying React applications
Flask jwt authentication tutorial
Python RESTful webservices with Python: Flask and Django solutions
20130528 solution linux_frousseau_nopain_webdev
Mini Curso Django Ii Congresso Academico Ces
A I R Presentation Dev Camp Feb 08
Maxim Salnikov - Service Worker: taking the best from the past experience for...
Flask - Backend com Python - Semcomp 18
Red5 - PHUG Workshops
Laravel development (Laravel History, Environment Setup & Laravel Installatio...
Creating Sentiment Line Chart with Watson
Grâce aux tags Varnish, j'ai switché ma prod sur Raspberry Pi
Mini Curso de Django

More from Max Klymyshyn (20)

PDF
Papers We Love Kyiv, July 2018: A Conflict-Free Replicated JSON Datatype
PDF
KharkivJS 2017: Коллаборативные системы и CRDT
PDF
OdessaJS 2017: Groupware Systems for fun and profit
PDF
PyCon Ukraine 2017: Operational Transformation
PDF
Communicating Sequential Processes (CSP) in JavaScript
PDF
PiterPy 2016: Parallelization, Aggregation and Validation of API in Python
PDF
Fighting async JavaScript (CSP)
PDF
React.js: Ускоряем UX/UI
PDF
KharkovPy #12: I/O in Python apps and smart logging (russian)
PDF
5 мифов о производительности баз данных и Python
PDF
Изоформные приложения на React.js
PDF
Изоморфный JavaScript (iForum 2015)
PDF
Трансдюсеры, CSP каналы, неизменяемые структуры данных в JavaScript
PDF
PiterPy 2015 - Трансдюсеры и Python
PDF
Robust web apps with React.js
PDF
LvivJS 2014 - Win-win c React.js
PDF
Инновации и JavaScript
PDF
Odessapy2013 - Graph databases and Python
PDF
Angular.js - JS Camp UKraine 2013
PPT
Зачем читать чужой код?
Papers We Love Kyiv, July 2018: A Conflict-Free Replicated JSON Datatype
KharkivJS 2017: Коллаборативные системы и CRDT
OdessaJS 2017: Groupware Systems for fun and profit
PyCon Ukraine 2017: Operational Transformation
Communicating Sequential Processes (CSP) in JavaScript
PiterPy 2016: Parallelization, Aggregation and Validation of API in Python
Fighting async JavaScript (CSP)
React.js: Ускоряем UX/UI
KharkovPy #12: I/O in Python apps and smart logging (russian)
5 мифов о производительности баз данных и Python
Изоформные приложения на React.js
Изоморфный JavaScript (iForum 2015)
Трансдюсеры, CSP каналы, неизменяемые структуры данных в JavaScript
PiterPy 2015 - Трансдюсеры и Python
Robust web apps with React.js
LvivJS 2014 - Win-win c React.js
Инновации и JavaScript
Odessapy2013 - Graph databases and Python
Angular.js - JS Camp UKraine 2013
Зачем читать чужой код?

Recently uploaded (20)

PDF
Encapsulation theory and applications.pdf
PDF
Mushroom cultivation and it's methods.pdf
PDF
Encapsulation_ Review paper, used for researhc scholars
PPTX
A Presentation on Artificial Intelligence
PPTX
Programs and apps: productivity, graphics, security and other tools
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PDF
gpt5_lecture_notes_comprehensive_20250812015547.pdf
PDF
Univ-Connecticut-ChatGPT-Presentaion.pdf
PDF
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
PDF
August Patch Tuesday
PPTX
Machine Learning_overview_presentation.pptx
PDF
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
PPTX
cloud_computing_Infrastucture_as_cloud_p
PDF
NewMind AI Weekly Chronicles - August'25-Week II
PPTX
Tartificialntelligence_presentation.pptx
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PDF
Heart disease approach using modified random forest and particle swarm optimi...
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PDF
Assigned Numbers - 2025 - Bluetooth® Document
Encapsulation theory and applications.pdf
Mushroom cultivation and it's methods.pdf
Encapsulation_ Review paper, used for researhc scholars
A Presentation on Artificial Intelligence
Programs and apps: productivity, graphics, security and other tools
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
gpt5_lecture_notes_comprehensive_20250812015547.pdf
Univ-Connecticut-ChatGPT-Presentaion.pdf
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
August Patch Tuesday
Machine Learning_overview_presentation.pptx
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
cloud_computing_Infrastucture_as_cloud_p
NewMind AI Weekly Chronicles - August'25-Week II
Tartificialntelligence_presentation.pptx
Mobile App Security Testing_ A Comprehensive Guide.pdf
Heart disease approach using modified random forest and particle swarm optimi...
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
Per capita expenditure prediction using model stacking based on satellite ima...
Assigned Numbers - 2025 - Bluetooth® Document

LvivPy - Flask in details

  • 1. Flask in details Max Klymyshyn CTO at GVMahines @maxmaxmaxmax github: joymax
  • 2. From Django to Flask and back to Django
  • 3. I remember when Flask appeared And I was one of guys who hadn't read the code when Flask was just a joke.
  • 5. But Armin is really nice, simple and very smart guy
  • 6. And when I start worked with Flask, aam...
  • 8. Now I feel like ...
  • 10. Devil is in the details
  • 11. Here is details 1. Typical project structure 2. Blueprints 3. Database 4. Forms & Validation 5. Management Commands 6. Assets-management 7. Replacement of django.contrib.admin 8. Debugging 9. Unit tests and Behavior tests
  • 12. Project structure 1. pure python module: settings.py - project - app.py - views.py - templates - static ... 2. Configuration: local_settings, settings: app.config.from_object(settings)
  • 13. Blueprints Kind of django-apps 1. Initialization: from flask import Blueprint app = Blueprint( 'profile', // namespace __name__, // logical python module or // package template_folder='templates', static_folder='static' ) ... @app.route('/sample/') def sample(): ...
  • 14. Register blueprint 1. To register use app.register_blueprint : from flask import Flask from proj.submodule.bp import app as submodule app = Flask(__name__) app.register_blueprint( submodule, url_prefix='/submodule' ) 2. Url namespace {{ url_for('profile.sample') }}
  • 15. Database Flask-SQLAlchemy minimongo Flask-Redis
  • 16. Flask-SQLAlchemy Example configuration from docs: from flask import Flask from flaskext.sqlalchemy import SQLAlchemy app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/test.db' db = SQLAlchemy(app)
  • 17. Flask-SQLAlchemy class 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
  • 18. Flask-SQLAlchemy >>> from app import db >>> db.create_all() >>> from app import User >>> admin = User('admin', '[email protected]') >>> guest = User('guest', '[email protected]') >>> db.session.add(admin) >>> db.session.add(guest) >>> db.session.commit() >>> User.query.all() [<User u'admin'>, <User u'guest'>]
  • 19. Minimongo 1. No initial configuration needed 2. Install & start mongo - that's enough Sample model: import minimongo as mm class Profile(mm.Model): class Meta: database = "sampleproject" collection = "profiles" indices = (mm.Index('username'))
  • 20. Minimongo >>> from app import db, User, Profile >>> admin = User.query.filter_by( ... username='admin').first() >>> admin.username u'admin' >>> profile = Profile(username=admin.username, ... description=u'Flask devleoper') >>> profile {'username': u'admin', 'description': u'Flask devleoper'} >>> profile.save() {'username': u'admin', '_id': ObjectId('4f13e019486dd09335000001'), 'description': u'Flask devleoper'}
  • 21. Minimongo >>> Profile.collection Collection(Database(Connection('localhost', 27017), u'sampleproject'), u'profiles') >>> Profile.collection.find_one( ... {'username': admin.username}) {u'username': u'admin', u'_id': ObjectId('4f13df60486dd09335000000'), u'description': u'Flask devleoper'}
  • 22. Flask-Redis 1. Install flask-redis 2. 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'
  • 23. Forms & Validation Flask-WTF
  • 24. WTForms Form and View from flask.ext import wtf class 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)
  • 25. 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>
  • 26. Management Commands Write external scripts with current project context
  • 27. Flask-Script 1. Create manage.py script within your project directory and put (which is quite similar to Django's manage.py): from flaskext.script import Manager from app import app manager = Manager(app) @manager.command def hello(): print "hello" if __name__ == "__main__": manager.run()
  • 28. Flask-Script maxk$ python manage.py shell Runs a Python shell inside Flask application context. hello runserver Runs the Flask development server i.e. app.run() maxk$ python manage.py hello hello
  • 29. Flask-Script With Flask-Script you able to: • Write custom management commands • Use existing ones like in flask-assets • Getting user's input • Use command line options All of abilities above already automated with Flask-Script and it's really easy-to-use.
  • 30. Assets Management Static, CSS & JavaScript files
  • 31. JS/CSS minification and so on Flask-Assets based on Webassets. To integrate we need some work to do: 1. Install Flask-Assets 2. Initialize Flask-Assets environment 3. Add Assets Bundles 4. Configure compressors/minifiers etc. to optimize our assets 5. Generate bundles with management command
  • 32. Flask-Assets: initializing environment import Flask from flask.ext.assets import Environment as AssetsEnvironment app = Flask(__name__) assets = AssetsEnvironment(app) assets.debug = True app.config['ASSETS_DEBUG'] = True app.config['YUI_COMPRESSOR_PATH'] = 'contrib/ yuicompressor-2.4.6.jar'
  • 33. Flask-Assets: Adding files I will show work with JavaScript only but feel free to use same approach with CSS files. JavaScript files directory structure: - static - js - src - core * jquery.js * underscore.js - app * module1.js * module2.js
  • 34. Flask-Assets: adding bundles assets.py: from flaskext.assets import Bundle def 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)
  • 35. Flask-Assets: adding bundles ... app = Bundle( 'js/src/app/*.js', filters='yui_js', output='js/bundle/app.js' ) assets.register('app', app)
  • 37. Flask-Assets: how to use Somewhere in your template code: {% assets "core" %} <script src="{{ ASSET_URL }}"></script> {% endassets %} {% assets "app" %} <script src="{{ ASSET_URL }}"></script> {% endassets %}
  • 38. Flask-Assets: debug mode Flask-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>
  • 39. Flask-Assets: production mode Flask-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
  • 40. More extensions: Flask-Mail Flask-Babel Flask-Cache Flask-csrf Flask-FlatPages Flask-lesscss ...
  • 41. Admin panel Flask-Admin Flask-Dashed
  • 42. Tests Unit, Behavior and JavaScript tests
  • 44. Testing: Unit & Behavior To test templates, views etc we need to have request context Before execution: self.app.test_request_context().push() After execution: self.app.test_request_context().pop()
  • 45. Behavior Testes with Lettuce Example 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 There's form with following fields: | form__username | | form__password | Fill the field "form__username" with "featured"
  • 46. lettuce-web Lettuce-web is a library which very close to headless testing using twill. lettuce-web doesn't require browser. You can write your features using lettuce-web predefined steps. More here: https://github.com/joymax/lettuce-web
  • 47. Flask-Jasmine Flask-Jasmine is extension to execute Jasmine JavaScript Tests More details https://github.com/joymax/flask-jasmine
  • 49. Issues What's going on in Flask world at the moment?
  • 50. Python 3 Status of porting Flask to Python 3 is unknown. Werkzeug not ported yet. Hopefully, will be ported to Python 3.3 ( PEP 414 for details)
  • 51. Werkzeug Werkzeug is really huge and have tons of tools. Flask based on Werkzeug. We all like Python for small, robust and clean libraries.
  • 53. That's all Questions? Source:  https://github.com/joymax/kyivpy-flask-in-details

Editor's Notes