SlideShare a Scribd company logo
1 of 54
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.
But Armin is
really nice,
simple and
very smart guy
And when I start worked with Flask,
              aam...
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)
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
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

What's hot

Build restful ap is with python and flask
Build restful ap is with python and flaskBuild restful ap is with python and flask
Build restful ap is with python and flaskJeetendra singh
 
Learn flask in 90mins
Learn flask in 90minsLearn flask in 90mins
Learn flask in 90minsLarry Cai
 
Python Flask app deployed to OPenShift using Wercker CI
Python Flask app deployed to OPenShift using Wercker CIPython Flask app deployed to OPenShift using Wercker CI
Python Flask app deployed to OPenShift using Wercker CIBruno Rocha
 
Rest API using Flask & SqlAlchemy
Rest API using Flask & SqlAlchemyRest API using Flask & SqlAlchemy
Rest API using Flask & SqlAlchemyAlessandro Cucci
 
Flask RESTful Flask HTTPAuth
Flask RESTful Flask HTTPAuthFlask RESTful Flask HTTPAuth
Flask RESTful Flask HTTPAuthEueung Mulyana
 
Python/Flask Presentation
Python/Flask PresentationPython/Flask Presentation
Python/Flask PresentationParag Mujumdar
 
Building a Dynamic Website Using Django
Building a Dynamic Website Using DjangoBuilding a Dynamic Website Using Django
Building a Dynamic Website Using DjangoNathan Eror
 
Django Architecture Introduction
Django Architecture IntroductionDjango Architecture Introduction
Django Architecture IntroductionHaiqi Chen
 
Laravel Beginners Tutorial 1
Laravel Beginners Tutorial 1Laravel Beginners Tutorial 1
Laravel Beginners Tutorial 1Vikas Chauhan
 
Scalable web application architecture
Scalable web application architectureScalable web application architecture
Scalable web application architecturepostrational
 
Laravel5 Introduction and essentials
Laravel5 Introduction and essentialsLaravel5 Introduction and essentials
Laravel5 Introduction and essentialsPramod Kadam
 
4 introduction-php-mvc-cakephp-m4-controllers-slides
4 introduction-php-mvc-cakephp-m4-controllers-slides4 introduction-php-mvc-cakephp-m4-controllers-slides
4 introduction-php-mvc-cakephp-m4-controllers-slidesMasterCode.vn
 
REST APIs in Laravel 101
REST APIs in Laravel 101REST APIs in Laravel 101
REST APIs in Laravel 101Samantha Geitz
 
Installation of Joomla on Windows XP
Installation of Joomla on Windows XPInstallation of Joomla on Windows XP
Installation of Joomla on Windows XPRupesh Kumar
 

What's hot (20)

Build restful ap is with python and flask
Build restful ap is with python and flaskBuild restful ap is with python and flask
Build restful ap is with python and flask
 
Flask
FlaskFlask
Flask
 
Kyiv.py #17 Flask talk
Kyiv.py #17 Flask talkKyiv.py #17 Flask talk
Kyiv.py #17 Flask talk
 
Learn flask in 90mins
Learn flask in 90minsLearn flask in 90mins
Learn flask in 90mins
 
Python Flask app deployed to OPenShift using Wercker CI
Python Flask app deployed to OPenShift using Wercker CIPython Flask app deployed to OPenShift using Wercker CI
Python Flask app deployed to OPenShift using Wercker CI
 
Rest API using Flask & SqlAlchemy
Rest API using Flask & SqlAlchemyRest API using Flask & SqlAlchemy
Rest API using Flask & SqlAlchemy
 
Flask RESTful Flask HTTPAuth
Flask RESTful Flask HTTPAuthFlask RESTful Flask HTTPAuth
Flask RESTful Flask HTTPAuth
 
Python/Flask Presentation
Python/Flask PresentationPython/Flask Presentation
Python/Flask Presentation
 
Flask vs. Django
Flask vs. DjangoFlask vs. Django
Flask vs. Django
 
Building a Dynamic Website Using Django
Building a Dynamic Website Using DjangoBuilding a Dynamic Website Using Django
Building a Dynamic Website Using Django
 
Django Architecture Introduction
Django Architecture IntroductionDjango Architecture Introduction
Django Architecture Introduction
 
Laravel Beginners Tutorial 1
Laravel Beginners Tutorial 1Laravel Beginners Tutorial 1
Laravel Beginners Tutorial 1
 
Django Girls Tutorial
Django Girls TutorialDjango Girls Tutorial
Django Girls Tutorial
 
Scalable web application architecture
Scalable web application architectureScalable web application architecture
Scalable web application architecture
 
Laravel5 Introduction and essentials
Laravel5 Introduction and essentialsLaravel5 Introduction and essentials
Laravel5 Introduction and essentials
 
4 introduction-php-mvc-cakephp-m4-controllers-slides
4 introduction-php-mvc-cakephp-m4-controllers-slides4 introduction-php-mvc-cakephp-m4-controllers-slides
4 introduction-php-mvc-cakephp-m4-controllers-slides
 
REST APIs in Laravel 101
REST APIs in Laravel 101REST APIs in Laravel 101
REST APIs in Laravel 101
 
Laravel 5
Laravel 5Laravel 5
Laravel 5
 
Laravel 101
Laravel 101Laravel 101
Laravel 101
 
Installation of Joomla on Windows XP
Installation of Joomla on Windows XPInstallation of Joomla on Windows XP
Installation of Joomla on Windows XP
 

Viewers also liked

Python and Flask introduction for my classmates Презентация и введение в flask
Python and Flask introduction for my classmates Презентация и введение в flaskPython and Flask introduction for my classmates Презентация и введение в flask
Python and Flask introduction for my classmates Презентация и введение в flaskNikita Lozhnikov
 
Introduction to Python and Web Programming
Introduction to Python and Web ProgrammingIntroduction to Python and Web Programming
Introduction to Python and Web ProgrammingDavid Neiss
 
Python and the Web
Python and the WebPython and the Web
Python and the Webpycontw
 
Flask admin vs. DIY
Flask admin vs. DIYFlask admin vs. DIY
Flask admin vs. DIYdokenzy
 
Why Python Web Frameworks Are Changing the Web
Why Python Web Frameworks Are Changing the WebWhy Python Web Frameworks Are Changing the Web
Why Python Web Frameworks Are Changing the Webjoelburton
 
An Introduction to Twisted
An Introduction to TwistedAn Introduction to Twisted
An Introduction to Twistedsdsern
 
Python talk web frameworks
Python talk web frameworksPython talk web frameworks
Python talk web frameworksKat Chuang
 
Зоопарк python веб-фреймворков
Зоопарк python веб-фреймворковЗоопарк python веб-фреймворков
Зоопарк python веб-фреймворковPyNSK
 
Чем Python плох для стартапа?
Чем Python плох для стартапа?Чем Python плох для стартапа?
Чем Python плох для стартапа?PyNSK
 
CHC Thesis #1
CHC Thesis #1CHC Thesis #1
CHC Thesis #1CHCStaff
 
STS Thesis by Hall 2015
STS Thesis by Hall 2015STS Thesis by Hall 2015
STS Thesis by Hall 2015Hank Lydick
 
Asynchronous Python with Twisted
Asynchronous Python with TwistedAsynchronous Python with Twisted
Asynchronous Python with TwistedAdam Englander
 
Writing your first web app using Python and Flask
Writing your first web app using Python and FlaskWriting your first web app using Python and Flask
Writing your first web app using Python and FlaskDanielle Madeley
 
Async Web Frameworks in Python
Async Web Frameworks in PythonAsync Web Frameworks in Python
Async Web Frameworks in PythonRyan Johnson
 
Web Scraping with Python
Web Scraping with PythonWeb Scraping with Python
Web Scraping with PythonPaul Schreiber
 

Viewers also liked (20)

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

Similar to LvivPy - Flask in details

Filling the flask
Filling the flaskFilling the flask
Filling the flaskJason Myers
 
What The Flask? and how to use it with some Google APIs
What The Flask? and how to use it with some Google APIsWhat The Flask? and how to use it with some Google APIs
What The Flask? and how to use it with some Google APIsBruno Rocha
 
Developing Flask Extensions
Developing Flask ExtensionsDeveloping Flask Extensions
Developing Flask ExtensionsRachel Sanders
 
Lean Php Presentation
Lean Php PresentationLean Php Presentation
Lean Php PresentationAlan Pinstein
 
Building and deploying React applications
Building and deploying React applicationsBuilding and deploying React applications
Building and deploying React applicationsAstrails
 
Flask jwt authentication tutorial
Flask jwt authentication tutorialFlask jwt authentication tutorial
Flask jwt authentication tutorialKaty Slemon
 
Python RESTful webservices with Python: Flask and Django solutions
Python RESTful webservices with Python: Flask and Django solutionsPython RESTful webservices with Python: Flask and Django solutions
Python RESTful webservices with Python: Flask and Django solutionsSolution4Future
 
20130528 solution linux_frousseau_nopain_webdev
20130528 solution linux_frousseau_nopain_webdev20130528 solution linux_frousseau_nopain_webdev
20130528 solution linux_frousseau_nopain_webdevFrank Rousseau
 
Mini Curso Django Ii Congresso Academico Ces
Mini Curso Django Ii Congresso Academico CesMini Curso Django Ii Congresso Academico Ces
Mini Curso Django Ii Congresso Academico CesLeonardo Fernandes
 
A I R Presentation Dev Camp Feb 08
A I R  Presentation  Dev Camp  Feb 08A I R  Presentation  Dev Camp  Feb 08
A I R Presentation Dev Camp Feb 08Abdul Qabiz
 
Maxim Salnikov - Service Worker: taking the best from the past experience for...
Maxim Salnikov - Service Worker: taking the best from the past experience for...Maxim Salnikov - Service Worker: taking the best from the past experience for...
Maxim Salnikov - Service Worker: taking the best from the past experience for...Codemotion
 
Flask - Backend com Python - Semcomp 18
Flask - Backend com Python - Semcomp 18Flask - Backend com Python - Semcomp 18
Flask - Backend com Python - Semcomp 18Lar21
 
Laravel development (Laravel History, Environment Setup & Laravel Installatio...
Laravel development (Laravel History, Environment Setup & Laravel Installatio...Laravel development (Laravel History, Environment Setup & Laravel Installatio...
Laravel development (Laravel History, Environment Setup & Laravel Installatio...Dilouar Hossain
 
Creating Sentiment Line Chart with Watson
Creating Sentiment Line Chart with Watson Creating Sentiment Line Chart with Watson
Creating Sentiment Line Chart with Watson Dev_Events
 
Grâce aux tags Varnish, j'ai switché ma prod sur Raspberry Pi
Grâce aux tags Varnish, j'ai switché ma prod sur Raspberry PiGrâce aux tags Varnish, j'ai switché ma prod sur Raspberry Pi
Grâce aux tags Varnish, j'ai switché ma prod sur Raspberry PiJérémy Derussé
 
Python from zero to hero (Twitter Explorer)
Python from zero to hero (Twitter Explorer)Python from zero to hero (Twitter Explorer)
Python from zero to hero (Twitter Explorer)Yuriy Senko
 

Similar to LvivPy - Flask in details (20)

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

More from Max Klymyshyn

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

More from Max Klymyshyn (20)

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

Recently uploaded

How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningLars Bell
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsMiki Katsuragi
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionDilum Bandara
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clashcharlottematthew16
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 

Recently uploaded (20)

How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine Tuning
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering Tips
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An Introduction
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clash
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 

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.
  • 4.
  • 5. But Armin is really nice, simple and very smart guy
  • 6. And when I start worked with Flask, aam...
  • 7.
  • 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', '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'>]
  • 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)
  • 36.
  • 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
  • 43.
  • 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

  1. \n
  2. \n
  3. \n
  4. \n
  5. \n
  6. \n
  7. \n
  8. \n
  9. \n
  10. \n
  11. \n
  12. \n
  13. \n
  14. \n
  15. \n
  16. \n
  17. \n
  18. \n
  19. \n
  20. \n
  21. \n
  22. \n
  23. \n
  24. \n
  25. \n
  26. \n
  27. \n
  28. \n
  29. \n
  30. \n
  31. \n
  32. \n
  33. \n
  34. \n
  35. \n
  36. \n
  37. \n
  38. \n
  39. \n
  40. \n
  41. \n
  42. \n
  43. \n
  44. \n
  45. \n
  46. \n
  47. \n
  48. \n
  49. \n
  50. \n
  51. \n
  52. \n
  53. \n
  54. \n