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

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
MasterCode.vn
 

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

Flask admin vs. DIY
Flask admin vs. DIYFlask admin vs. DIY
Flask admin vs. DIY
dokenzy
 
STS Thesis by Hall 2015
STS Thesis by Hall 2015STS Thesis by Hall 2015
STS Thesis by Hall 2015
Hank Lydick
 

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

20130528 solution linux_frousseau_nopain_webdev
20130528 solution linux_frousseau_nopain_webdev20130528 solution linux_frousseau_nopain_webdev
20130528 solution linux_frousseau_nopain_webdev
Frank Rousseau
 

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

Зачем читать чужой код?
Зачем читать чужой код?Зачем читать чужой код?
Зачем читать чужой код?
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

Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Victor Rentea
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 

Recently uploaded (20)

Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKSpring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 

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