SlideShare una empresa de Scribd logo
1 de 48
DEVELOPING FLASK EXTENSIONS
Rachel Sanders @ PyTennessee 2014
Rachel Sanders




Engineer at LinkedIn & PyLadiesSF organizer
Our internal stack: Python + Flask
Team lead for a 30K LOC Flask app
What we talkin’ about







The really really really quick intro to Flask
The really really quick intro to extending Flask
Flask-FeatureFlags: a case study
Beyond the Basics
Questions
The really really quick intro to Flask
Like 3 min tops, promise
from flask import Flask
app = Flask(__name__)
@app.route("/")
def hello():
return "Hello San Dimas High!"
if __name__ == "__main__":
app.run()
whaaaaaaa?




No database??
No forms?
No admin interface?
“The idea of Flask is to build a
good foundation for all applications.
Everything else is up to you or extensions.”
-- Armin Ronacher, creator of Flask
All these are extensions




database  SQLAlchemy + Flask-SQLAlchemy
forms  WTForms + FlaskWTF
admin  Flask-Admin
The really quick intro to extending Flask
Like 5 min, promise
from flask import Flask

app = Flask(__name__)
@app.route("/")
def hello():
return "Hello San Dimas High!"
if __name__ == "__main__":
app.run()
from flask import Flask

app = Flask(__name__)
@app.route("/")
def hello():
return "Hello San Dimas High!"
if __name__ == "__main__":
app.run()
extending Flask = changing app
You can change the app object by



Hooking into request lifecycle
Adding more resources
 Jinja

filters, tests, global variables
 Routes, blueprints, static files




Middleware
Monkeypatching
Flask-FeatureFlags
with the power to turn code on or off
from flask import Flask
app = Flask(__name__)
@app.route("/")
def hello():
return "Hello San Dimas High!”
from flask import Flask
import flask_featureflags as feature
app = Flask(__name__)
feature_flag = feature.FeatureFlag(app)
@app.route("/")
def hello():
return "Hello San Dimas High!"
from flask import Flask
import flask_featureflags as feature
app = Flask(__name__)
feature_flag = feature.FeatureFlag(app)
@app.route("/")
def hello():
if feature.is_active('pytennessee'):
return "Hello PyTennessee!"
else:
return "Hello San Dimas High!"
from flask import Flask
import flask_featureflags as feature
app = Flask(__name__)
feature_flag = feature.FeatureFlag(app)
app.config['FEATURE_FLAGS']['pytennessee'] = True
@app.route("/")
def hello():
if feature.is_active('pytennessee'):
return "Hello PyTennessee!"
else:

return "Hello San Dimas High!"
{% if 'pytennesse' is active_feature %}
“Hi PyTennessee!”
{% else %}
“Hello San Dimas High!”
{% endif %}
FEATURE FLAG SPEC


feature flags stored in config



Jinja template test called “active_feature”



Module function called “is_active”
bit.ly/giantwallofcode
class FeatureFlags(object):
class FeatureFlags(object):
def __init__(self, app=None):
class FeatureFlags(object):
def __init__(self, app=None):
if app is not None:
self.init_app(app)
def init_app(self, app):
class FeatureFlags(object):
def __init__(self, app=None):
if app is not None:
self.init_app(app)
def init_app(self, app):
app.config.setdefault('FEATURE_FLAGS’, {})
from flask import current_app
class FeatureFlags(object):
def __init__(self, app=None):
if app is not None:
self.init_app(app)
def init_app(self, app):
app.config.setdefault('FEATURE_FLAGS’, {})
def in_config(self, feature):
try:
return current_app.config['FEATURE_FLAGS'][feature]
except (AttributeError, KeyError):
return False
FEATURE FLAGS SPEC


feature flags stored in config



Jinja template test



is_active function
{% if 'pytennesse' is active_feature %}
“Hi PyTennessee!”
{% else %}
“Hello San Dimas High!”
{% endif %}
from flask import current_app
class FeatureFlags(object):

def __init__(self, app=None):
if app is not None:
self.init_app(app)

def init_app(self, app):
app.config.setdefault('FEATURE_FLAGS’, {})

app.add_template_test(self.in_config, name=’active_feature’)
def in_config(self, feature):
try:
return current_app.config['FEATURE_FLAGS'][feature]
except (AttributeError, KeyError):
return False
class FeatureFlags(object):
def __init__(self, app=None):
if app is not None:
self.init_app(app)
def init_app(self, app):
app.config.setdefault('FEATURE_FLAGS’, {})
if hasattr(app, "add_template_test"):
app.add_template_test(self.in_config, name='active_feature')
else:
app.jinja_env.tests[’active_feature’] = self.in_config
FEATURE FLAGS SPEC


feature flags stored in config



Jinja template test



is_active function
from flask import Flask
import flask_featureflags as feature
app = Flask(__name__)
feature_flag = feature.FeatureFlag(app)
app.config['FEATURE_FLAGS']['pytennessee'] = True
@app.route("/")
def hello():
if feature.is_active('pytennessee'):
return "Hello PyTennessee!"
else:

return "Hello San Dimas High!"
class FeatureFlags(object):
def __init__(self, app=None):
if app is not None:
self.init_app(app)
def init_app(self, app):
app.config.setdefault('FEATURE_FLAGS’, {})
if hasattr(app, "add_template_test"):
app.add_template_test(self.in_config, name='active_feature')
else:
app.jinja_env.tests[’active_feature’] = self.in_config
app.extensions['FeatureFlags'] = self
from flask import current_app
def is_active(feature):
feature_flagger = current_app.extensions['FeatureFlags']
return feature_flagger.in_config(feature)
FEATURE FLAGS SPEC


feature flags stored in config



Jinja template test



is_active function
ok so what’d we learn?







use init_app because app factories
be sure to set config defaults
calling Flask hooks
0.10+ is a trap
how to get to our extension later
Beyond the basics
ok what now lady
Flask-DebugToolbar
http://flask-debugtoolbar.readthedocs.org/
other great extensions




Flask-SeaSurf – request processing, cookies
Flask-Admin – SQLAlchemy, blueprints, static files
Flask-Classy – adds class-based views
thanks everybody!




@trustrachel
github.com/trustrachel
trustrachel.com

Más contenido relacionado

La actualidad más candente

*Webinar* Learn from the Experts: How to Boost Test Coverage with Automated V...
*Webinar* Learn from the Experts: How to Boost Test Coverage with Automated V...*Webinar* Learn from the Experts: How to Boost Test Coverage with Automated V...
*Webinar* Learn from the Experts: How to Boost Test Coverage with Automated V...Applitools
 
OpenLayers 3 & Google Closure Compiler
OpenLayers 3 & Google Closure CompilerOpenLayers 3 & Google Closure Compiler
OpenLayers 3 & Google Closure CompilerCamptocamp
 
Laravel Beginners Tutorial 1
Laravel Beginners Tutorial 1Laravel Beginners Tutorial 1
Laravel Beginners Tutorial 1Vikas Chauhan
 
Advanced automated visual testing with Selenium
Advanced automated visual testing with SeleniumAdvanced automated visual testing with Selenium
Advanced automated visual testing with Seleniumadamcarmi
 
Flex automation. tools comparison
Flex automation. tools comparisonFlex automation. tools comparison
Flex automation. tools comparisonAlex
 
Console Apps: php artisan forthe:win
Console Apps: php artisan forthe:win Console Apps: php artisan forthe:win
Console Apps: php artisan forthe:win Joe Ferguson
 
Knowing Laravel 5 : The most popular PHP framework
Knowing Laravel 5 : The most popular PHP frameworkKnowing Laravel 5 : The most popular PHP framework
Knowing Laravel 5 : The most popular PHP frameworkBukhori Aqid
 
Eclipse RCP Demo
Eclipse RCP DemoEclipse RCP Demo
Eclipse RCP DemoCsaba Toth
 
Plugins And Making Your Own
Plugins And Making Your OwnPlugins And Making Your Own
Plugins And Making Your OwnLambert Beekhuis
 
Desktop|Embedded Application API JSR
Desktop|Embedded Application API JSRDesktop|Embedded Application API JSR
Desktop|Embedded Application API JSRAndres Almiray
 
Ted Husted Presentation Testing The Testers Ae2009
Ted Husted Presentation Testing The Testers Ae2009Ted Husted Presentation Testing The Testers Ae2009
Ted Husted Presentation Testing The Testers Ae2009Ajax Experience 2009
 
All Aboard for Laravel 5.1
All Aboard for Laravel 5.1All Aboard for Laravel 5.1
All Aboard for Laravel 5.1Jason McCreary
 
Laravel Starter Kit | Laravel Admin Template-ChandraAdmin
Laravel Starter Kit | Laravel Admin Template-ChandraAdmin Laravel Starter Kit | Laravel Admin Template-ChandraAdmin
Laravel Starter Kit | Laravel Admin Template-ChandraAdmin Lorvent56
 

La actualidad más candente (20)

*Webinar* Learn from the Experts: How to Boost Test Coverage with Automated V...
*Webinar* Learn from the Experts: How to Boost Test Coverage with Automated V...*Webinar* Learn from the Experts: How to Boost Test Coverage with Automated V...
*Webinar* Learn from the Experts: How to Boost Test Coverage with Automated V...
 
Article laravel 8
Article laravel 8Article laravel 8
Article laravel 8
 
OpenLayers 3 & Google Closure Compiler
OpenLayers 3 & Google Closure CompilerOpenLayers 3 & Google Closure Compiler
OpenLayers 3 & Google Closure Compiler
 
Laravel Beginners Tutorial 1
Laravel Beginners Tutorial 1Laravel Beginners Tutorial 1
Laravel Beginners Tutorial 1
 
Advanced automated visual testing with Selenium
Advanced automated visual testing with SeleniumAdvanced automated visual testing with Selenium
Advanced automated visual testing with Selenium
 
Why Laravel?
Why Laravel?Why Laravel?
Why Laravel?
 
Intro to Laravel 4
Intro to Laravel 4Intro to Laravel 4
Intro to Laravel 4
 
Flex automation. tools comparison
Flex automation. tools comparisonFlex automation. tools comparison
Flex automation. tools comparison
 
Console Apps: php artisan forthe:win
Console Apps: php artisan forthe:win Console Apps: php artisan forthe:win
Console Apps: php artisan forthe:win
 
Laravel 5
Laravel 5Laravel 5
Laravel 5
 
Knowing Laravel 5 : The most popular PHP framework
Knowing Laravel 5 : The most popular PHP frameworkKnowing Laravel 5 : The most popular PHP framework
Knowing Laravel 5 : The most popular PHP framework
 
Eclipse RCP Demo
Eclipse RCP DemoEclipse RCP Demo
Eclipse RCP Demo
 
Plugins And Making Your Own
Plugins And Making Your OwnPlugins And Making Your Own
Plugins And Making Your Own
 
Desktop|Embedded Application API JSR
Desktop|Embedded Application API JSRDesktop|Embedded Application API JSR
Desktop|Embedded Application API JSR
 
Ted Husted Presentation Testing The Testers Ae2009
Ted Husted Presentation Testing The Testers Ae2009Ted Husted Presentation Testing The Testers Ae2009
Ted Husted Presentation Testing The Testers Ae2009
 
All Aboard for Laravel 5.1
All Aboard for Laravel 5.1All Aboard for Laravel 5.1
All Aboard for Laravel 5.1
 
Presentation laravel 5 4
Presentation laravel 5 4Presentation laravel 5 4
Presentation laravel 5 4
 
Intro to Laravel
Intro to LaravelIntro to Laravel
Intro to Laravel
 
Laravel 5.4
Laravel 5.4 Laravel 5.4
Laravel 5.4
 
Laravel Starter Kit | Laravel Admin Template-ChandraAdmin
Laravel Starter Kit | Laravel Admin Template-ChandraAdmin Laravel Starter Kit | Laravel Admin Template-ChandraAdmin
Laravel Starter Kit | Laravel Admin Template-ChandraAdmin
 

Similar a Developing Flask Extensions

LvivPy - Flask in details
LvivPy - Flask in detailsLvivPy - Flask in details
LvivPy - Flask in detailsMax Klymyshyn
 
Automated User Tests with Apache Flex
Automated User Tests with Apache FlexAutomated User Tests with Apache Flex
Automated User Tests with Apache FlexGert Poppe
 
Automated User Tests with Apache Flex
Automated User Tests with Apache FlexAutomated User Tests with Apache Flex
Automated User Tests with Apache FlexGert Poppe
 
Python Flask Tutorial For Beginners | Flask Web Development Tutorial | Python...
Python Flask Tutorial For Beginners | Flask Web Development Tutorial | Python...Python Flask Tutorial For Beginners | Flask Web Development Tutorial | Python...
Python Flask Tutorial For Beginners | Flask Web Development Tutorial | Python...Edureka!
 
Behavior & Specification Driven Development in PHP - #OpenWest
Behavior & Specification Driven Development in PHP - #OpenWestBehavior & Specification Driven Development in PHP - #OpenWest
Behavior & Specification Driven Development in PHP - #OpenWestJoshua Warren
 
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
 
Zyncro zyncro apps & ui customization feb 2013
Zyncro zyncro apps & ui customization feb 2013Zyncro zyncro apps & ui customization feb 2013
Zyncro zyncro apps & ui customization feb 2013Zyncro
 
1Uso de DRF (Django Rest Framework).pptx
1Uso de DRF (Django Rest Framework).pptx1Uso de DRF (Django Rest Framework).pptx
1Uso de DRF (Django Rest Framework).pptxdanielfmd1
 
Flask patterns
Flask patternsFlask patterns
Flask patternsit-people
 
[QE 2018] Adam Stasiak – Nadchodzi React Native – czyli o testowaniu mobilnyc...
[QE 2018] Adam Stasiak – Nadchodzi React Native – czyli o testowaniu mobilnyc...[QE 2018] Adam Stasiak – Nadchodzi React Native – czyli o testowaniu mobilnyc...
[QE 2018] Adam Stasiak – Nadchodzi React Native – czyli o testowaniu mobilnyc...Future Processing
 
QA Fest 2018. Adam Stasiak. React Native is Coming – the story of hybrid mobi...
QA Fest 2018. Adam Stasiak. React Native is Coming – the story of hybrid mobi...QA Fest 2018. Adam Stasiak. React Native is Coming – the story of hybrid mobi...
QA Fest 2018. Adam Stasiak. React Native is Coming – the story of hybrid mobi...QAFest
 
Write your first WordPress plugin
Write your first WordPress pluginWrite your first WordPress plugin
Write your first WordPress pluginAnthony Montalbano
 
Plugin Development Practices
Plugin Development PracticesPlugin Development Practices
Plugin Development Practicesdanpastori
 
Rewriting a Plugin Architecture 3 Times to Harness the API Economy
Rewriting a Plugin Architecture 3 Times to Harness the API EconomyRewriting a Plugin Architecture 3 Times to Harness the API Economy
Rewriting a Plugin Architecture 3 Times to Harness the API EconomyTim Pettersen
 
Lean Php Presentation
Lean Php PresentationLean Php Presentation
Lean Php PresentationAlan Pinstein
 
Rits Brown Bag - Salesforce Lightning
Rits Brown Bag - Salesforce LightningRits Brown Bag - Salesforce Lightning
Rits Brown Bag - Salesforce LightningRight IT Services
 

Similar a Developing Flask Extensions (20)

LvivPy - Flask in details
LvivPy - Flask in detailsLvivPy - Flask in details
LvivPy - Flask in details
 
Kyiv.py #17 Flask talk
Kyiv.py #17 Flask talkKyiv.py #17 Flask talk
Kyiv.py #17 Flask talk
 
Automated User Tests with Apache Flex
Automated User Tests with Apache FlexAutomated User Tests with Apache Flex
Automated User Tests with Apache Flex
 
Automated User Tests with Apache Flex
Automated User Tests with Apache FlexAutomated User Tests with Apache Flex
Automated User Tests with Apache Flex
 
Python Flask Tutorial For Beginners | Flask Web Development Tutorial | Python...
Python Flask Tutorial For Beginners | Flask Web Development Tutorial | Python...Python Flask Tutorial For Beginners | Flask Web Development Tutorial | Python...
Python Flask Tutorial For Beginners | Flask Web Development Tutorial | Python...
 
Behavior & Specification Driven Development in PHP - #OpenWest
Behavior & Specification Driven Development in PHP - #OpenWestBehavior & Specification Driven Development in PHP - #OpenWest
Behavior & Specification Driven Development in PHP - #OpenWest
 
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...
 
JSF 2.0 Preview
JSF 2.0 PreviewJSF 2.0 Preview
JSF 2.0 Preview
 
Zyncro zyncro apps & ui customization feb 2013
Zyncro zyncro apps & ui customization feb 2013Zyncro zyncro apps & ui customization feb 2013
Zyncro zyncro apps & ui customization feb 2013
 
1Uso de DRF (Django Rest Framework).pptx
1Uso de DRF (Django Rest Framework).pptx1Uso de DRF (Django Rest Framework).pptx
1Uso de DRF (Django Rest Framework).pptx
 
Laravel 5.3 - Web Development Php framework
Laravel 5.3 - Web Development Php frameworkLaravel 5.3 - Web Development Php framework
Laravel 5.3 - Web Development Php framework
 
Flask
FlaskFlask
Flask
 
Flask patterns
Flask patternsFlask patterns
Flask patterns
 
[QE 2018] Adam Stasiak – Nadchodzi React Native – czyli o testowaniu mobilnyc...
[QE 2018] Adam Stasiak – Nadchodzi React Native – czyli o testowaniu mobilnyc...[QE 2018] Adam Stasiak – Nadchodzi React Native – czyli o testowaniu mobilnyc...
[QE 2018] Adam Stasiak – Nadchodzi React Native – czyli o testowaniu mobilnyc...
 
QA Fest 2018. Adam Stasiak. React Native is Coming – the story of hybrid mobi...
QA Fest 2018. Adam Stasiak. React Native is Coming – the story of hybrid mobi...QA Fest 2018. Adam Stasiak. React Native is Coming – the story of hybrid mobi...
QA Fest 2018. Adam Stasiak. React Native is Coming – the story of hybrid mobi...
 
Write your first WordPress plugin
Write your first WordPress pluginWrite your first WordPress plugin
Write your first WordPress plugin
 
Plugin Development Practices
Plugin Development PracticesPlugin Development Practices
Plugin Development Practices
 
Rewriting a Plugin Architecture 3 Times to Harness the API Economy
Rewriting a Plugin Architecture 3 Times to Harness the API EconomyRewriting a Plugin Architecture 3 Times to Harness the API Economy
Rewriting a Plugin Architecture 3 Times to Harness the API Economy
 
Lean Php Presentation
Lean Php PresentationLean Php Presentation
Lean Php Presentation
 
Rits Brown Bag - Salesforce Lightning
Rits Brown Bag - Salesforce LightningRits Brown Bag - Salesforce Lightning
Rits Brown Bag - Salesforce Lightning
 

Último

Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
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 TerraformAndrey Devyatkin
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesBoston Institute of Analytics
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
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...Martijn de Jong
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
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...apidays
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
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 FresherRemote DBA Services
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 

Último (20)

Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
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
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation Strategies
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
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...
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
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...
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
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
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 

Developing Flask Extensions

  • 1. DEVELOPING FLASK EXTENSIONS Rachel Sanders @ PyTennessee 2014
  • 2. Rachel Sanders    Engineer at LinkedIn & PyLadiesSF organizer Our internal stack: Python + Flask Team lead for a 30K LOC Flask app
  • 3. What we talkin’ about      The really really really quick intro to Flask The really really quick intro to extending Flask Flask-FeatureFlags: a case study Beyond the Basics Questions
  • 4. The really really quick intro to Flask Like 3 min tops, promise
  • 5. from flask import Flask app = Flask(__name__) @app.route("/") def hello(): return "Hello San Dimas High!" if __name__ == "__main__": app.run()
  • 7. “The idea of Flask is to build a good foundation for all applications. Everything else is up to you or extensions.” -- Armin Ronacher, creator of Flask
  • 8. All these are extensions    database  SQLAlchemy + Flask-SQLAlchemy forms  WTForms + FlaskWTF admin  Flask-Admin
  • 9. The really quick intro to extending Flask Like 5 min, promise
  • 10. from flask import Flask app = Flask(__name__) @app.route("/") def hello(): return "Hello San Dimas High!" if __name__ == "__main__": app.run()
  • 11. from flask import Flask app = Flask(__name__) @app.route("/") def hello(): return "Hello San Dimas High!" if __name__ == "__main__": app.run()
  • 12. extending Flask = changing app
  • 13. You can change the app object by   Hooking into request lifecycle Adding more resources  Jinja filters, tests, global variables  Routes, blueprints, static files   Middleware Monkeypatching
  • 14.
  • 15.
  • 16. Flask-FeatureFlags with the power to turn code on or off
  • 17. from flask import Flask app = Flask(__name__) @app.route("/") def hello(): return "Hello San Dimas High!”
  • 18. from flask import Flask import flask_featureflags as feature app = Flask(__name__) feature_flag = feature.FeatureFlag(app) @app.route("/") def hello(): return "Hello San Dimas High!"
  • 19. from flask import Flask import flask_featureflags as feature app = Flask(__name__) feature_flag = feature.FeatureFlag(app) @app.route("/") def hello(): if feature.is_active('pytennessee'): return "Hello PyTennessee!" else: return "Hello San Dimas High!"
  • 20. from flask import Flask import flask_featureflags as feature app = Flask(__name__) feature_flag = feature.FeatureFlag(app) app.config['FEATURE_FLAGS']['pytennessee'] = True @app.route("/") def hello(): if feature.is_active('pytennessee'): return "Hello PyTennessee!" else: return "Hello San Dimas High!"
  • 21. {% if 'pytennesse' is active_feature %} “Hi PyTennessee!” {% else %} “Hello San Dimas High!” {% endif %}
  • 22. FEATURE FLAG SPEC  feature flags stored in config  Jinja template test called “active_feature”  Module function called “is_active”
  • 23.
  • 27. class FeatureFlags(object): def __init__(self, app=None): if app is not None: self.init_app(app) def init_app(self, app):
  • 28. class FeatureFlags(object): def __init__(self, app=None): if app is not None: self.init_app(app) def init_app(self, app): app.config.setdefault('FEATURE_FLAGS’, {})
  • 29. from flask import current_app class FeatureFlags(object): def __init__(self, app=None): if app is not None: self.init_app(app) def init_app(self, app): app.config.setdefault('FEATURE_FLAGS’, {}) def in_config(self, feature): try: return current_app.config['FEATURE_FLAGS'][feature] except (AttributeError, KeyError): return False
  • 30. FEATURE FLAGS SPEC  feature flags stored in config  Jinja template test  is_active function
  • 31. {% if 'pytennesse' is active_feature %} “Hi PyTennessee!” {% else %} “Hello San Dimas High!” {% endif %}
  • 32. from flask import current_app class FeatureFlags(object): def __init__(self, app=None): if app is not None: self.init_app(app) def init_app(self, app): app.config.setdefault('FEATURE_FLAGS’, {}) app.add_template_test(self.in_config, name=’active_feature’) def in_config(self, feature): try: return current_app.config['FEATURE_FLAGS'][feature] except (AttributeError, KeyError): return False
  • 33.
  • 34.
  • 35.
  • 36. class FeatureFlags(object): def __init__(self, app=None): if app is not None: self.init_app(app) def init_app(self, app): app.config.setdefault('FEATURE_FLAGS’, {}) if hasattr(app, "add_template_test"): app.add_template_test(self.in_config, name='active_feature') else: app.jinja_env.tests[’active_feature’] = self.in_config
  • 37. FEATURE FLAGS SPEC  feature flags stored in config  Jinja template test  is_active function
  • 38. from flask import Flask import flask_featureflags as feature app = Flask(__name__) feature_flag = feature.FeatureFlag(app) app.config['FEATURE_FLAGS']['pytennessee'] = True @app.route("/") def hello(): if feature.is_active('pytennessee'): return "Hello PyTennessee!" else: return "Hello San Dimas High!"
  • 39. class FeatureFlags(object): def __init__(self, app=None): if app is not None: self.init_app(app) def init_app(self, app): app.config.setdefault('FEATURE_FLAGS’, {}) if hasattr(app, "add_template_test"): app.add_template_test(self.in_config, name='active_feature') else: app.jinja_env.tests[’active_feature’] = self.in_config app.extensions['FeatureFlags'] = self
  • 40. from flask import current_app def is_active(feature): feature_flagger = current_app.extensions['FeatureFlags'] return feature_flagger.in_config(feature)
  • 41. FEATURE FLAGS SPEC  feature flags stored in config  Jinja template test  is_active function
  • 42. ok so what’d we learn?      use init_app because app factories be sure to set config defaults calling Flask hooks 0.10+ is a trap how to get to our extension later
  • 43. Beyond the basics ok what now lady
  • 45.
  • 46.
  • 47. other great extensions    Flask-SeaSurf – request processing, cookies Flask-Admin – SQLAlchemy, blueprints, static files Flask-Classy – adds class-based views