SlideShare une entreprise Scribd logo
1  sur  22
Télécharger pour lire hors ligne
Flask Templates
(aka Jinja2)
by @alanhamlett
Blocks ( templates/common/base.html )
Blocks name parts of your template, and can be re-used in child templates.
<html>
<title>{% block title %}My Website{% endblock %}</title>
<body>
{% block body %}
{% endblock %}
</body>
</html>
Inheritance ( templates/login.html )
{% extends "common/base.html" %}
{% block title %}super() - Login{% endblock %}
{% block body %}
<form method="POST">
<p><input type="text" name="username" /></p>
<p><input type="password" name="password" /></p>
<p><button type="submit">Login</button></p>
</form>
{% endblock %}
Variable Scope ( templates/common/base.html )
<html>
<title>{% block title %}My Website{% endblock %}</title>
<body>
{% with %}
{% set variable = "value" %}
{% block body %}
{% endblock %}
{% endwith %}
</body>
</html>
Variable Scope ( templates/login.html )
{% extends "common/base.html" %}
{% block title %}super() - Login{% endblock %}
{% block body %}
<form method="POST">
<p><input type="hidden" name="variable" value="{{variable}}" /></p>
<p><input type="text" name="username" /></p>
<p><input type="password" name="password" /></p>
<p><button type="submit">Login</button></p>
</form>
{% endblock %}
Rendering Templates ( __init__.py )
from flask import Flask
app = Flask(__name__)
from flask import render_template
@app.route("/login")
def login():
return render_template('login.html')
if __name__ == "__main__":
app.run()
Rendering Templates ( __init__.py )
from flask import Flask
app = Flask(__name__)
from . import views
if __name__ == "__main__":
app.run()
Rendering Templates ( views.py )
from . import app
from flask import render_template
@app.route("/login")
def login():
context = {
'features': [
{'icon': 'free.png', 'name': 'Free'},
{'icon': 'easy.png', 'name': 'Easy'},
{'icon': 'powerful.png', 'name': 'Powerful'},
],
}
return render_template('login.html', **context)
Rendering Variables ( templates/login.html )
{% extends "common/base.html" %}
{% block title %}super() - Login{% endblock %}
{% block body %}
<h1>Included Features:</h1>
<ul>
{% for feature in features %}
<li><img src="{{STATIC_URL}}img/icons/{{feature.icon}}" /> {{feature.name}}</li>
{% endfor %}
</ul>
<form method="POST">
<p><input type="text" name="username" /></p>
<p><input type="password" name="password" /></p>
<p><button type="submit">Login</button></p>
</form>
{% endblock %}
Filters ( templates/login.html )
{% extends "common/base.html" %}
{% block title %}super() - Login{% endblock %}
{% block body %}
<h1>Included Features:</h1>
<ul>
{% for feature in features %}
<li><img src="{{STATIC_URL}}img/icons/{{feature.icon}}"/> {{feature.name|lower}}</li>
{% endfor %}
</ul>
<form method="POST">
<p><input type="text" name="username" /></p>
<p><input type="password" name="password" /></p>
<p><button type="submit">Login</button></p>
</form>
{% endblock %}
Flask-WTF ( forms.py )
from flask.ext.wtf import Form
from wtforms import StringField, PasswordField
from wtforms.validators import DataRequired, Email, Length
class LoginForm(Form):
username = StringField('name', validators=[DataRequired(), Email()])
username = PasswordField('name', validators=[DataRequired(), Length(min=6)])
Flask-WTF ( views.py )
from . import app
from .forms import LoginForm
from flask import render_template, request
@app.route("/login", methods=('GET', 'POST'))
def login():
form = LoginForm(request.form)
if request.method == 'POST' and form.validate():
return redirect('/myprofile')
return render_template('login.html', form=form)
Flask-WTF ( templates/login.html )
{% extends "common/base.html" %}
{% block title %}super() - Login{% endblock %}
{% block body %}
<form method="POST">
<p>Username <input type="text" name="username" value="{{form.data.username or ''}}" /></p>
<p>Password <input type="password" name="password" value="{{form.data.password or ''}}" /></p>
<p><button type="submit">Login</button></p>
</form>
{% endblock %}
Flask-WTF ( templates/login.html )
...
{% block body %}
<form method="POST">
{% for field in form._fields.values() %}
< div class="form-group" >
{{ field.label(class="col-sm-3 control-label") }}
< div class="col-sm-6 col-md-4" >
{{ field(class="form-control") }}
{% for error in field.errors %}
< p>{{error}}</ p>
{% endfor %}
</ div>
</ div>
{% endfor %}
< div class="form-group" >
< div class="col-sm-6 col-md-4 col-sm-offset-3" >
< button type="submit">Login</button>
</ div>
</ div>
</form>
{% endblock %}
...
Flask-Admin
Flask-Admin ( admin.py )
from . import app
from .models import db, User
from flask.ext.admin import Admin
from flask.ext.admin.contrib.sqla import ModelView
admin = Admin(app)
admin.add_view(ModelView(User, db.session))
Flask-Admin ( __init__.py )
from flask import Flask
app = Flask(__name__)
from . import views
from . import admin
if __name__ == "__main__":
app.run()
Flask-Admin
Extend these Flask-Admin classes to protect your Admin pages:
● flask.ext.admin.AdminIndexView
● sqla.ModelView
Flask-Admin ( admin.py )
from . import app
from .models import db, User
from flask.ext.admin import Admin, AdminIndexView as UnsafeAdminIndexView, expose
from flask.ext.admin.contrib.sqla import ModelView
class AdminIndexView(UnsafeAdminIndexView):
@expose('/')
def index(self):
if not app.current_user.is_authenticated():
return redirect('/login')
if not app.current_user.is_admin:
abort(403)
return super(AdminIndexView, self).index()
@expose('/login/')
def login_view(self):
return redirect('/login')
@expose('/logout/')
def logout_view(self):
return redirect('/logout')
admin = Admin(app, index_view=AdminIndexView(), template_mode='bootstrap3', base_template='admin/custom_base.html')
admin.add_view(ModelView(User, db.session))
Flask-Admin ( admin.py )...
class ModelView(sqla.ModelView):
edit_template = 'admin/model/edit.html'
create_template = 'admin/model/create.html'
list_template = 'admin/model/custom_list.html'
def __init__(self, *args, **kwargs):
if 'exclude' in kwargs:
self.form_excluded_columns = kwargs['exclude']
del kwargs['exclude']
if 'include' in kwargs:
self.column_list = kwargs['include']
del kwargs['include']
pass_through = [
'can_create',
'can_edit',
'can_delete',
]
for item in pass_through:
if item in kwargs:
setattr(self, item, kwargs[item])
del kwargs[item]
super(ModelView, self).__init__(*args, **kwargs)
def is_accessible(self):
return app.current_user.is_authenticated() and app.current_user.is_admin
admin.add_view(ModelView(User, db.session, category='Users', exclude=['password', 'heartbeats'], can_delete=False))
...
Now go build something cool!
Alan Hamlett
@alanhamlett on Twitter & GitHub
alan@wakatime.com
View this online at
http://slidesha.re/1wfDzrv

Contenu connexe

Tendances

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!
 
Introduction to BOOTSTRAP
Introduction to BOOTSTRAPIntroduction to BOOTSTRAP
Introduction to BOOTSTRAPJeanie Arnoco
 
CSS Day: CSS Grid Layout
CSS Day: CSS Grid Layout CSS Day: CSS Grid Layout
CSS Day: CSS Grid Layout Rachel Andrew
 
PHP Workshop Notes
PHP Workshop NotesPHP Workshop Notes
PHP Workshop NotesPamela Fox
 
Django for Beginners
Django for BeginnersDjango for Beginners
Django for BeginnersJason Davies
 
Flask Introduction - Python Meetup
Flask Introduction - Python MeetupFlask Introduction - Python Meetup
Flask Introduction - Python MeetupAreski Belaid
 
Introduction to Django
Introduction to DjangoIntroduction to Django
Introduction to DjangoJames Casey
 
Introduction to JavaScript (1).ppt
Introduction to JavaScript (1).pptIntroduction to JavaScript (1).ppt
Introduction to JavaScript (1).pptMuhammadRehan856177
 
Angular 2.0 forms
Angular 2.0 formsAngular 2.0 forms
Angular 2.0 formsEyal Vardi
 
Introduction to Spring's Dependency Injection
Introduction to Spring's Dependency InjectionIntroduction to Spring's Dependency Injection
Introduction to Spring's Dependency InjectionRichard Paul
 
HTML presentation for beginners
HTML presentation for beginnersHTML presentation for beginners
HTML presentation for beginnersjeroenvdmeer
 
The effective use of Django ORM
The effective use of Django ORMThe effective use of Django ORM
The effective use of Django ORMYaroslav Muravskyi
 
HTML Semantic Tags
HTML Semantic TagsHTML Semantic Tags
HTML Semantic TagsBruce Kyle
 

Tendances (20)

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...
 
Introduction to BOOTSTRAP
Introduction to BOOTSTRAPIntroduction to BOOTSTRAP
Introduction to BOOTSTRAP
 
CSS Day: CSS Grid Layout
CSS Day: CSS Grid Layout CSS Day: CSS Grid Layout
CSS Day: CSS Grid Layout
 
CSS
CSSCSS
CSS
 
PHP Workshop Notes
PHP Workshop NotesPHP Workshop Notes
PHP Workshop Notes
 
Django for Beginners
Django for BeginnersDjango for Beginners
Django for Beginners
 
Flask Introduction - Python Meetup
Flask Introduction - Python MeetupFlask Introduction - Python Meetup
Flask Introduction - Python Meetup
 
Advanced Cascading Style Sheets
Advanced Cascading Style SheetsAdvanced Cascading Style Sheets
Advanced Cascading Style Sheets
 
Introduction to Django
Introduction to DjangoIntroduction to Django
Introduction to Django
 
Introduction to JavaScript (1).ppt
Introduction to JavaScript (1).pptIntroduction to JavaScript (1).ppt
Introduction to JavaScript (1).ppt
 
Angular 2.0 forms
Angular 2.0 formsAngular 2.0 forms
Angular 2.0 forms
 
Grails Controllers
Grails ControllersGrails Controllers
Grails Controllers
 
Introduction to Spring's Dependency Injection
Introduction to Spring's Dependency InjectionIntroduction to Spring's Dependency Injection
Introduction to Spring's Dependency Injection
 
HTML presentation for beginners
HTML presentation for beginnersHTML presentation for beginners
HTML presentation for beginners
 
PHP slides
PHP slidesPHP slides
PHP slides
 
The effective use of Django ORM
The effective use of Django ORMThe effective use of Django ORM
The effective use of Django ORM
 
PHP
PHPPHP
PHP
 
HTML Semantic Tags
HTML Semantic TagsHTML Semantic Tags
HTML Semantic Tags
 
CSS Basics
CSS BasicsCSS Basics
CSS Basics
 
Bootstrap
BootstrapBootstrap
Bootstrap
 

Similaire à Intro to Jinja2 Templates - San Francisco Flask Meetup

Jinja2 Templates - San Francisco Flask Meetup
Jinja2 Templates - San Francisco Flask MeetupJinja2 Templates - San Francisco Flask Meetup
Jinja2 Templates - San Francisco Flask MeetupAlan Hamlett
 
Django Templates
Django TemplatesDjango Templates
Django TemplatesWilly Liu
 
QCon 2015 - Thinking in components: A new paradigm for Web UI
QCon 2015 - Thinking in components: A new paradigm for Web UIQCon 2015 - Thinking in components: A new paradigm for Web UI
QCon 2015 - Thinking in components: A new paradigm for Web UIOliver Häger
 
How to Create A Magento Adminhtml Controller in Magento Extension
How to Create A Magento Adminhtml Controller in Magento ExtensionHow to Create A Magento Adminhtml Controller in Magento Extension
How to Create A Magento Adminhtml Controller in Magento ExtensionHendy Irawan
 
引き出しとしてのDjango - SoozyCon7
引き出しとしてのDjango - SoozyCon7引き出しとしてのDjango - SoozyCon7
引き出しとしてのDjango - SoozyCon7makoto tsuyuki
 
Your Custom WordPress Admin Pages Suck
Your Custom WordPress Admin Pages SuckYour Custom WordPress Admin Pages Suck
Your Custom WordPress Admin Pages SuckAnthony Montalbano
 
Technical Preview: The New Shopware Admin
Technical Preview: The New Shopware AdminTechnical Preview: The New Shopware Admin
Technical Preview: The New Shopware AdminPhilipp Schuch
 
Understanding form helpers
Understanding form helpersUnderstanding form helpers
Understanding form helpersBruno Almeida
 
카카오커머스를 지탱하는 Angular
카카오커머스를 지탱하는 Angular카카오커머스를 지탱하는 Angular
카카오커머스를 지탱하는 Angularif kakao
 
Action View Form Helpers - 1, Season 2
Action View Form Helpers - 1, Season 2Action View Form Helpers - 1, Season 2
Action View Form Helpers - 1, Season 2RORLAB
 
Vue.js - zastosowanie i budowa komponentów
Vue.js - zastosowanie i budowa komponentówVue.js - zastosowanie i budowa komponentów
Vue.js - zastosowanie i budowa komponentówLaravel Poland MeetUp
 

Similaire à Intro to Jinja2 Templates - San Francisco Flask Meetup (20)

Jinja2 Templates - San Francisco Flask Meetup
Jinja2 Templates - San Francisco Flask MeetupJinja2 Templates - San Francisco Flask Meetup
Jinja2 Templates - San Francisco Flask Meetup
 
Flask – Python
Flask – PythonFlask – Python
Flask – Python
 
Django Templates
Django TemplatesDjango Templates
Django Templates
 
QCon 2015 - Thinking in components: A new paradigm for Web UI
QCon 2015 - Thinking in components: A new paradigm for Web UIQCon 2015 - Thinking in components: A new paradigm for Web UI
QCon 2015 - Thinking in components: A new paradigm for Web UI
 
How to Create A Magento Adminhtml Controller in Magento Extension
How to Create A Magento Adminhtml Controller in Magento ExtensionHow to Create A Magento Adminhtml Controller in Magento Extension
How to Create A Magento Adminhtml Controller in Magento Extension
 
引き出しとしてのDjango - SoozyCon7
引き出しとしてのDjango - SoozyCon7引き出しとしてのDjango - SoozyCon7
引き出しとしてのDjango - SoozyCon7
 
iWebkit
iWebkitiWebkit
iWebkit
 
Polymer
PolymerPolymer
Polymer
 
Your Custom WordPress Admin Pages Suck
Your Custom WordPress Admin Pages SuckYour Custom WordPress Admin Pages Suck
Your Custom WordPress Admin Pages Suck
 
1cst
1cst1cst
1cst
 
Technical Preview: The New Shopware Admin
Technical Preview: The New Shopware AdminTechnical Preview: The New Shopware Admin
Technical Preview: The New Shopware Admin
 
JSP
JSPJSP
JSP
 
Understanding form helpers
Understanding form helpersUnderstanding form helpers
Understanding form helpers
 
카카오커머스를 지탱하는 Angular
카카오커머스를 지탱하는 Angular카카오커머스를 지탱하는 Angular
카카오커머스를 지탱하는 Angular
 
Fcr 2
Fcr 2Fcr 2
Fcr 2
 
Geb qa fest2017
Geb qa fest2017Geb qa fest2017
Geb qa fest2017
 
Introduction to Html5
Introduction to Html5Introduction to Html5
Introduction to Html5
 
Action View Form Helpers - 1, Season 2
Action View Form Helpers - 1, Season 2Action View Form Helpers - 1, Season 2
Action View Form Helpers - 1, Season 2
 
Vue.js - zastosowanie i budowa komponentów
Vue.js - zastosowanie i budowa komponentówVue.js - zastosowanie i budowa komponentów
Vue.js - zastosowanie i budowa komponentów
 
Bootstrap
BootstrapBootstrap
Bootstrap
 

Dernier

FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756dollysharma2066
 
Java Programming :Event Handling(Types of Events)
Java Programming :Event Handling(Types of Events)Java Programming :Event Handling(Types of Events)
Java Programming :Event Handling(Types of Events)simmis5
 
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...ranjana rawat
 
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Bookingdharasingh5698
 
PVC VS. FIBERGLASS (FRP) GRAVITY SEWER - UNI BELL
PVC VS. FIBERGLASS (FRP) GRAVITY SEWER - UNI BELLPVC VS. FIBERGLASS (FRP) GRAVITY SEWER - UNI BELL
PVC VS. FIBERGLASS (FRP) GRAVITY SEWER - UNI BELLManishPatel169454
 
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...Call Girls in Nagpur High Profile
 
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Bookingdharasingh5698
 
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Christo Ananth
 
Thermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - VThermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - VDineshKumar4165
 
notes on Evolution Of Analytic Scalability.ppt
notes on Evolution Of Analytic Scalability.pptnotes on Evolution Of Analytic Scalability.ppt
notes on Evolution Of Analytic Scalability.pptMsecMca
 
Generative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPTGenerative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPTbhaskargani46
 
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...roncy bisnoi
 
Online banking management system project.pdf
Online banking management system project.pdfOnline banking management system project.pdf
Online banking management system project.pdfKamal Acharya
 
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...SUHANI PANDEY
 
data_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdfdata_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdfJiananWang21
 
Call Girls In Bangalore ☎ 7737669865 🥵 Book Your One night Stand
Call Girls In Bangalore ☎ 7737669865 🥵 Book Your One night StandCall Girls In Bangalore ☎ 7737669865 🥵 Book Your One night Stand
Call Girls In Bangalore ☎ 7737669865 🥵 Book Your One night Standamitlee9823
 

Dernier (20)

FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
 
Java Programming :Event Handling(Types of Events)
Java Programming :Event Handling(Types of Events)Java Programming :Event Handling(Types of Events)
Java Programming :Event Handling(Types of Events)
 
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
 
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
 
PVC VS. FIBERGLASS (FRP) GRAVITY SEWER - UNI BELL
PVC VS. FIBERGLASS (FRP) GRAVITY SEWER - UNI BELLPVC VS. FIBERGLASS (FRP) GRAVITY SEWER - UNI BELL
PVC VS. FIBERGLASS (FRP) GRAVITY SEWER - UNI BELL
 
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
 
Roadmap to Membership of RICS - Pathways and Routes
Roadmap to Membership of RICS - Pathways and RoutesRoadmap to Membership of RICS - Pathways and Routes
Roadmap to Membership of RICS - Pathways and Routes
 
NFPA 5000 2024 standard .
NFPA 5000 2024 standard                                  .NFPA 5000 2024 standard                                  .
NFPA 5000 2024 standard .
 
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
 
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
 
Thermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - VThermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - V
 
notes on Evolution Of Analytic Scalability.ppt
notes on Evolution Of Analytic Scalability.pptnotes on Evolution Of Analytic Scalability.ppt
notes on Evolution Of Analytic Scalability.ppt
 
Generative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPTGenerative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPT
 
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
 
Online banking management system project.pdf
Online banking management system project.pdfOnline banking management system project.pdf
Online banking management system project.pdf
 
(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7
(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7
(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7
 
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...
 
data_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdfdata_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdf
 
(INDIRA) Call Girl Meerut Call Now 8617697112 Meerut Escorts 24x7
(INDIRA) Call Girl Meerut Call Now 8617697112 Meerut Escorts 24x7(INDIRA) Call Girl Meerut Call Now 8617697112 Meerut Escorts 24x7
(INDIRA) Call Girl Meerut Call Now 8617697112 Meerut Escorts 24x7
 
Call Girls In Bangalore ☎ 7737669865 🥵 Book Your One night Stand
Call Girls In Bangalore ☎ 7737669865 🥵 Book Your One night StandCall Girls In Bangalore ☎ 7737669865 🥵 Book Your One night Stand
Call Girls In Bangalore ☎ 7737669865 🥵 Book Your One night Stand
 

Intro to Jinja2 Templates - San Francisco Flask Meetup

  • 2. Blocks ( templates/common/base.html ) Blocks name parts of your template, and can be re-used in child templates. <html> <title>{% block title %}My Website{% endblock %}</title> <body> {% block body %} {% endblock %} </body> </html>
  • 3. Inheritance ( templates/login.html ) {% extends "common/base.html" %} {% block title %}super() - Login{% endblock %} {% block body %} <form method="POST"> <p><input type="text" name="username" /></p> <p><input type="password" name="password" /></p> <p><button type="submit">Login</button></p> </form> {% endblock %}
  • 4. Variable Scope ( templates/common/base.html ) <html> <title>{% block title %}My Website{% endblock %}</title> <body> {% with %} {% set variable = "value" %} {% block body %} {% endblock %} {% endwith %} </body> </html>
  • 5. Variable Scope ( templates/login.html ) {% extends "common/base.html" %} {% block title %}super() - Login{% endblock %} {% block body %} <form method="POST"> <p><input type="hidden" name="variable" value="{{variable}}" /></p> <p><input type="text" name="username" /></p> <p><input type="password" name="password" /></p> <p><button type="submit">Login</button></p> </form> {% endblock %}
  • 6. Rendering Templates ( __init__.py ) from flask import Flask app = Flask(__name__) from flask import render_template @app.route("/login") def login(): return render_template('login.html') if __name__ == "__main__": app.run()
  • 7. Rendering Templates ( __init__.py ) from flask import Flask app = Flask(__name__) from . import views if __name__ == "__main__": app.run()
  • 8. Rendering Templates ( views.py ) from . import app from flask import render_template @app.route("/login") def login(): context = { 'features': [ {'icon': 'free.png', 'name': 'Free'}, {'icon': 'easy.png', 'name': 'Easy'}, {'icon': 'powerful.png', 'name': 'Powerful'}, ], } return render_template('login.html', **context)
  • 9. Rendering Variables ( templates/login.html ) {% extends "common/base.html" %} {% block title %}super() - Login{% endblock %} {% block body %} <h1>Included Features:</h1> <ul> {% for feature in features %} <li><img src="{{STATIC_URL}}img/icons/{{feature.icon}}" /> {{feature.name}}</li> {% endfor %} </ul> <form method="POST"> <p><input type="text" name="username" /></p> <p><input type="password" name="password" /></p> <p><button type="submit">Login</button></p> </form> {% endblock %}
  • 10.
  • 11. Filters ( templates/login.html ) {% extends "common/base.html" %} {% block title %}super() - Login{% endblock %} {% block body %} <h1>Included Features:</h1> <ul> {% for feature in features %} <li><img src="{{STATIC_URL}}img/icons/{{feature.icon}}"/> {{feature.name|lower}}</li> {% endfor %} </ul> <form method="POST"> <p><input type="text" name="username" /></p> <p><input type="password" name="password" /></p> <p><button type="submit">Login</button></p> </form> {% endblock %}
  • 12. Flask-WTF ( forms.py ) from flask.ext.wtf import Form from wtforms import StringField, PasswordField from wtforms.validators import DataRequired, Email, Length class LoginForm(Form): username = StringField('name', validators=[DataRequired(), Email()]) username = PasswordField('name', validators=[DataRequired(), Length(min=6)])
  • 13. Flask-WTF ( views.py ) from . import app from .forms import LoginForm from flask import render_template, request @app.route("/login", methods=('GET', 'POST')) def login(): form = LoginForm(request.form) if request.method == 'POST' and form.validate(): return redirect('/myprofile') return render_template('login.html', form=form)
  • 14. Flask-WTF ( templates/login.html ) {% extends "common/base.html" %} {% block title %}super() - Login{% endblock %} {% block body %} <form method="POST"> <p>Username <input type="text" name="username" value="{{form.data.username or ''}}" /></p> <p>Password <input type="password" name="password" value="{{form.data.password or ''}}" /></p> <p><button type="submit">Login</button></p> </form> {% endblock %}
  • 15. Flask-WTF ( templates/login.html ) ... {% block body %} <form method="POST"> {% for field in form._fields.values() %} < div class="form-group" > {{ field.label(class="col-sm-3 control-label") }} < div class="col-sm-6 col-md-4" > {{ field(class="form-control") }} {% for error in field.errors %} < p>{{error}}</ p> {% endfor %} </ div> </ div> {% endfor %} < div class="form-group" > < div class="col-sm-6 col-md-4 col-sm-offset-3" > < button type="submit">Login</button> </ div> </ div> </form> {% endblock %} ...
  • 17. Flask-Admin ( admin.py ) from . import app from .models import db, User from flask.ext.admin import Admin from flask.ext.admin.contrib.sqla import ModelView admin = Admin(app) admin.add_view(ModelView(User, db.session))
  • 18. Flask-Admin ( __init__.py ) from flask import Flask app = Flask(__name__) from . import views from . import admin if __name__ == "__main__": app.run()
  • 19. Flask-Admin Extend these Flask-Admin classes to protect your Admin pages: ● flask.ext.admin.AdminIndexView ● sqla.ModelView
  • 20. Flask-Admin ( admin.py ) from . import app from .models import db, User from flask.ext.admin import Admin, AdminIndexView as UnsafeAdminIndexView, expose from flask.ext.admin.contrib.sqla import ModelView class AdminIndexView(UnsafeAdminIndexView): @expose('/') def index(self): if not app.current_user.is_authenticated(): return redirect('/login') if not app.current_user.is_admin: abort(403) return super(AdminIndexView, self).index() @expose('/login/') def login_view(self): return redirect('/login') @expose('/logout/') def logout_view(self): return redirect('/logout') admin = Admin(app, index_view=AdminIndexView(), template_mode='bootstrap3', base_template='admin/custom_base.html') admin.add_view(ModelView(User, db.session))
  • 21. Flask-Admin ( admin.py )... class ModelView(sqla.ModelView): edit_template = 'admin/model/edit.html' create_template = 'admin/model/create.html' list_template = 'admin/model/custom_list.html' def __init__(self, *args, **kwargs): if 'exclude' in kwargs: self.form_excluded_columns = kwargs['exclude'] del kwargs['exclude'] if 'include' in kwargs: self.column_list = kwargs['include'] del kwargs['include'] pass_through = [ 'can_create', 'can_edit', 'can_delete', ] for item in pass_through: if item in kwargs: setattr(self, item, kwargs[item]) del kwargs[item] super(ModelView, self).__init__(*args, **kwargs) def is_accessible(self): return app.current_user.is_authenticated() and app.current_user.is_admin admin.add_view(ModelView(User, db.session, category='Users', exclude=['password', 'heartbeats'], can_delete=False)) ...
  • 22. Now go build something cool! Alan Hamlett @alanhamlett on Twitter & GitHub alan@wakatime.com View this online at http://slidesha.re/1wfDzrv