SlideShare une entreprise Scribd logo
1  sur  24
Télécharger pour lire hors ligne
Flask intro
             rosedu web workshops



27/03/2013                            alex@grep.ro
                                    alex@eftimie.ro
prerequisites              what we'll do
●   python      ●   set-up a working environment
●   bash        ●   run a local server
●   HTTP        ●   write a twitter clone in a single
                    python file
                ●   use templates
                ●   use an ORM
was ist flask?
●   micro web framework
●   WSGI (same as django, webapp2)
●   decoupled
●   werkzeug routing
●   jinja2 templates
●   wtf forms
●   many extensions
●   write web applications not web scripts (such as PHP does)
virtualenv, pip
# install system-wide
apt-get install python-virtualenv
# create new
virtualenv env
# activate
source env/bin/activate
# install flask
pip install flask

# pip freeze
pip freeze > requirements.txt
basic flask app
#!/usr/bin/env python         (env)student@intel:~$ python mini.
                              py
import flask                   * Running on http://127.0.0.1:
                              5000/
app = flask.Flask(__name__)   127.0.0.1 - - [27/Mar/2013 01:13:
app.config['DEBUG'] = True    28] "GET / HTTP/1.1" 200 -


@app.route( '/')
def home():
    return "Hello World!"


if __name__ == '__main__' :
    app.run()
new message form
●     create a file new.html inside a templates/ folder

    <h1>New message </h1>

    <form method="post">
        <textarea rows="4" cols="80" name="message"></textarea>
        <br>
        <button type="submit">send</button>
    </form>


●     route /new to a view function rendering the template

...
      return flask.render_template( 'new.html' )


                                                                  (see home())
form submit; redirect
●   check request method (one of 'GET' or 'POST')

    flask.request.method == 'POST'

●   get post data, print it

    print flask.request.form['message']

●   redirect to home page

    flask.redirect(flask .url_for('home'))


                              @app.route('/new', methods=['GET', 'POST'])
                              def new():
                                   if flask.request.method == 'POST':
                                        print "msg:", flask.request.form['message']
                                        return flask.redirect(flask.url_for('home'))
                                   return flask.render_template('new.html')
db; message model
 ● in a terminal:
pip install SQLAlchemy Flask-SQLAlchemy

●   in mini.py

from flask.ext.sqlalchemy import SQLAlchemy
...
app.config['SQLALCHEMY_DATABASE_URI' ] = 'sqlite:////tmp/test.db'
db = SQLAlchemy(app)
...

class Message(db.Model):
    id = db.Column(db.Integer, primary_key =True)
    text = db.Column(db.String)
    time = db.Column(db.DateTime)
save to db
●   create db before app.run()
    db.create_all()


●   replace print with insert statement, in new()
    text = flask.request.form[ 'message']
    message = Message(text =text, time =datetime.utcnow())
    db.session.add(message)
    db.session.commit()


●   sqlite3 /tmp/test.db 'select * from message'
fetch from db
                                                        messages.html
●   change print "Hello World" with
    template rendering and context      <h1>Mini Twitter </h1>

                                        <p>
flask.render_template( 'messages.         <a href="{{ url_for('new') }}" >new msg</a>
html',                                  </p>
       messages =Message.query.all())
                                        {% for message in messages %}
                                        <article>
●   create html file in templates/        <p>{{ message.text }} </p>
                                          <footer>
                                             <time>{{message.time}} </time>
●   use {{ variable }} to display         </footer>
                                        </article>
    variable value in template          {% endfor %}

●   call url_for for view permalink
●   use {% for %} to iterate through
    messages
template filters
Usage:                     You:
{{ variable |filter }}      ● display message time in local
                              time
Custom:
@app.template_filter()
def tolower(value):
    return value.lower()
common layout template
layout.html
    <!doctype html>
    <html>
    ...
    {% block content %}
    {% endblock %}
    </html>


messages.html
    {% extends 'layout.html' %}
    {% block content %}
    goodies...
    {% endblock %}
config file
●   move configuration to a file

    app.config.from_pyfile( 'settings.py' )


●   settings

    DEBUG = True
    ...
flash messages
●   use session to display messages in the next view
    flask.flash("I have a message for you" )

●   display messages in template
    {% for message in get_flashed_messages() %}
         <p class="msg"> ...
    {% endfor %}
●   put it in header.html then include it before content block in the layout
    template
    {% include 'other_template.html' %}
login
●   view + template the same as new() - new.html
●   handle the submitted username
    if flask.request.method == 'POST':
        username = flask.request.form['username' ]
        ...
●   print username or flash it


                                 {% extends 'layout.html' %}


                                 {% block content %}
                                     <form method="post">
                                         <input name="username" >
                                         <button type="submit"
                                 >login</button>
                                     </form>
                                 {% endblock %}
session
●   store something in session
    flask.session['username' ] = username
●   fetch and expose in templates
    @app.before_request
    def get_user():
        flask.g.username = flask.session.get('username' )
●   use in header
    {% if g.username %}
        logged in as {{ g.username }}
    {% else %}
        <a href="{{ url_for('login') }}" >login</a>
    {% endif %}
logout
●   clean the session in style
flask.session.pop('variable' , '')

●   you
     ○    write a view logout()
     ○    route /logout to it
     ○    delete username from session
     ○    flash the message "bye bye"
     ○    redirect to home page
     ○    link to it in header
login required decorator
●   redirect to login if not authenticated
    def login_required(func):
        @wraps(func)
        def wrapper(*args, **kwargs):
            if flask.g.username is None:
                return flask.redirect('login')
            return func(*args, **kwargs)
        return wrapper
●   use
    @app.route('/private')
    @login_required
    def private_view():
        ...
●   you: decorate new()
person model
●   db model with id (Integer, primary_key) and username
    (String)
●   message author
    class Message(db.Model):
        ...
        person_id = db.Column(db.Integer, db .ForeignKey( 'person.id' ))
        person = db.relationship( 'Person',
                         backref=db.backref('messages' , lazy='dynamic'))
●   get or create Person
    @classmethod
    def get_or_create(cls, username):
        person = cls.query.filter_by(username =username).first()
        if person is None:
            person = cls(username =username)
        ...
message and person
●   when adding a message to db
    text = flask.request.form['message']
    person = Person.get_or_create(flask .g.username)
    message = Message(text =text, time =datetime.utcnow(), person =person)
●   when displaying in template
    <p>
           <strong>{{ message.person.username }}: </strong>
           {{ message.text }}
    </p>
person and messages
●   add view for a person's feed
●   route it to /<username>
@app.route( '/<username>' )

●   get person or raise http 404
person = Person.query.filter_by(username =username).first_or_404()

●   display messages in template
flask.render_template( 'messages.html' , messages =person.messages)

●   show link to person's feed
    ...
    {% set username = message.person.username %}
    {% set url = url_for('person_feed', username=username) %}
    <strong><a href="{{ url }}" >{{ username }} </a>:</strong>
    ...
static assets
●      create a folder static/
●      add style.css and some ninja CSS
●      link to it in layout.html
<link rel="stylesheet" href="{{ url_for('static', filename='style.css')
}}">
                                          /* style.css */
●      wrap {% block content %} in <div class="container"> </div>
                                   * { font-family: Ubuntu, arial }
                                   body { background-color: #efefef }
                                   .container {
                                     width: 800px; margin: 0 auto;
                                     background-color: #fff; }
                                   p.msg {
                                     background-color: #99ff99;
                                     border-radius: 20px;
                                     border: 1px solid green;
                                     color: green: }
                                   a { text-decoration: none }
wrapping up
we learned about:                 file structure:
●   web application
                                  mini.py
●   url routing                   settings.py
                                  static/
●   templates
                                      style.css
●   sql                           templates/
                                      header.html
●   sessions
                                      layout.html
                                      messages.html
                                      new.html


next:
●   deployment options
●   security, social extensions
see more
● full source code
  https://github.com/mgax/minitwitter


● flask documentation
  http://flask.pocoo.org/docs/

Contenu connexe

Tendances

Building Web Apps with Express
Building Web Apps with ExpressBuilding Web Apps with Express
Building Web Apps with ExpressAaron Stannard
 
Hash Signaling Made Easy
Hash Signaling Made EasyHash Signaling Made Easy
Hash Signaling Made Easydavidgouldin
 
Introduction to Nodejs
Introduction to NodejsIntroduction to Nodejs
Introduction to NodejsGabriele Lana
 
DrupalCon Dublin 2016 - Automated browser testing with Nightwatch.js
DrupalCon Dublin 2016 - Automated browser testing with Nightwatch.jsDrupalCon Dublin 2016 - Automated browser testing with Nightwatch.js
DrupalCon Dublin 2016 - Automated browser testing with Nightwatch.jsVladimir Roudakov
 
Improving the performance of Odoo deployments
Improving the performance of Odoo deploymentsImproving the performance of Odoo deployments
Improving the performance of Odoo deploymentsOdoo
 
Web Components With Rails
Web Components With RailsWeb Components With Rails
Web Components With RailsBoris Nadion
 
Django Rest Framework and React and Redux, Oh My!
Django Rest Framework and React and Redux, Oh My!Django Rest Framework and React and Redux, Oh My!
Django Rest Framework and React and Redux, Oh My!Eric Palakovich Carr
 
Introduzione JQuery
Introduzione JQueryIntroduzione JQuery
Introduzione JQueryorestJump
 
Node.js in action
Node.js in actionNode.js in action
Node.js in actionSimon Su
 
Learning django step 1
Learning django step 1Learning django step 1
Learning django step 1永昇 陳
 
Moodle 3.3 - API Change Overview #mootieuk17
Moodle 3.3 - API Change Overview #mootieuk17Moodle 3.3 - API Change Overview #mootieuk17
Moodle 3.3 - API Change Overview #mootieuk17Dan Poltawski
 
Even faster django
Even faster djangoEven faster django
Even faster djangoGage Tseng
 
Building com Phing - 7Masters PHP
Building com Phing - 7Masters PHPBuilding com Phing - 7Masters PHP
Building com Phing - 7Masters PHPiMasters
 
Remy Sharp The DOM scripting toolkit jQuery
Remy Sharp The DOM scripting toolkit jQueryRemy Sharp The DOM scripting toolkit jQuery
Remy Sharp The DOM scripting toolkit jQuerydeimos
 
Joe Walker Interactivewebsites Cometand Dwr
Joe Walker Interactivewebsites Cometand DwrJoe Walker Interactivewebsites Cometand Dwr
Joe Walker Interactivewebsites Cometand Dwrdeimos
 
"The little big project. From zero to hero in two weeks with 3 front-end engi...
"The little big project. From zero to hero in two weeks with 3 front-end engi..."The little big project. From zero to hero in two weeks with 3 front-end engi...
"The little big project. From zero to hero in two weeks with 3 front-end engi...Fwdays
 

Tendances (20)

Express js
Express jsExpress js
Express js
 
Building Web Apps with Express
Building Web Apps with ExpressBuilding Web Apps with Express
Building Web Apps with Express
 
Hash Signaling Made Easy
Hash Signaling Made EasyHash Signaling Made Easy
Hash Signaling Made Easy
 
End-to-end testing with geb
End-to-end testing with gebEnd-to-end testing with geb
End-to-end testing with geb
 
Javascript
JavascriptJavascript
Javascript
 
Introduction to Nodejs
Introduction to NodejsIntroduction to Nodejs
Introduction to Nodejs
 
DrupalCon Dublin 2016 - Automated browser testing with Nightwatch.js
DrupalCon Dublin 2016 - Automated browser testing with Nightwatch.jsDrupalCon Dublin 2016 - Automated browser testing with Nightwatch.js
DrupalCon Dublin 2016 - Automated browser testing with Nightwatch.js
 
AJAX Transport Layer
AJAX Transport LayerAJAX Transport Layer
AJAX Transport Layer
 
Improving the performance of Odoo deployments
Improving the performance of Odoo deploymentsImproving the performance of Odoo deployments
Improving the performance of Odoo deployments
 
Web Components With Rails
Web Components With RailsWeb Components With Rails
Web Components With Rails
 
Django Rest Framework and React and Redux, Oh My!
Django Rest Framework and React and Redux, Oh My!Django Rest Framework and React and Redux, Oh My!
Django Rest Framework and React and Redux, Oh My!
 
Introduzione JQuery
Introduzione JQueryIntroduzione JQuery
Introduzione JQuery
 
Node.js in action
Node.js in actionNode.js in action
Node.js in action
 
Learning django step 1
Learning django step 1Learning django step 1
Learning django step 1
 
Moodle 3.3 - API Change Overview #mootieuk17
Moodle 3.3 - API Change Overview #mootieuk17Moodle 3.3 - API Change Overview #mootieuk17
Moodle 3.3 - API Change Overview #mootieuk17
 
Even faster django
Even faster djangoEven faster django
Even faster django
 
Building com Phing - 7Masters PHP
Building com Phing - 7Masters PHPBuilding com Phing - 7Masters PHP
Building com Phing - 7Masters PHP
 
Remy Sharp The DOM scripting toolkit jQuery
Remy Sharp The DOM scripting toolkit jQueryRemy Sharp The DOM scripting toolkit jQuery
Remy Sharp The DOM scripting toolkit jQuery
 
Joe Walker Interactivewebsites Cometand Dwr
Joe Walker Interactivewebsites Cometand DwrJoe Walker Interactivewebsites Cometand Dwr
Joe Walker Interactivewebsites Cometand Dwr
 
"The little big project. From zero to hero in two weeks with 3 front-end engi...
"The little big project. From zero to hero in two weeks with 3 front-end engi..."The little big project. From zero to hero in two weeks with 3 front-end engi...
"The little big project. From zero to hero in two weeks with 3 front-end engi...
 

En vedette

Prezentare Modul Utilizarea Computerului
Prezentare Modul Utilizarea ComputeruluiPrezentare Modul Utilizarea Computerului
Prezentare Modul Utilizarea Computeruluiolimpnetbz
 
Introducere în Linux
Introducere în LinuxIntroducere în Linux
Introducere în LinuxAlex Eftimie
 
Prezentare raport de cercetare
Prezentare raport de cercetarePrezentare raport de cercetare
Prezentare raport de cercetareAlex Eftimie
 
Esclarecimentos sobre União TAM e LAN
Esclarecimentos sobre União TAM e LANEsclarecimentos sobre União TAM e LAN
Esclarecimentos sobre União TAM e LANABRACORP
 
Linux/Unix-based Operating Systems
Linux/Unix-based Operating SystemsLinux/Unix-based Operating Systems
Linux/Unix-based Operating SystemsMihai Oaida
 

En vedette (7)

Android
AndroidAndroid
Android
 
Prezentare Modul Utilizarea Computerului
Prezentare Modul Utilizarea ComputeruluiPrezentare Modul Utilizarea Computerului
Prezentare Modul Utilizarea Computerului
 
Introducere în Linux
Introducere în LinuxIntroducere în Linux
Introducere în Linux
 
Instalare xampp xic
Instalare xampp xicInstalare xampp xic
Instalare xampp xic
 
Prezentare raport de cercetare
Prezentare raport de cercetarePrezentare raport de cercetare
Prezentare raport de cercetare
 
Esclarecimentos sobre União TAM e LAN
Esclarecimentos sobre União TAM e LANEsclarecimentos sobre União TAM e LAN
Esclarecimentos sobre União TAM e LAN
 
Linux/Unix-based Operating Systems
Linux/Unix-based Operating SystemsLinux/Unix-based Operating Systems
Linux/Unix-based Operating Systems
 

Similaire à Flask intro - ROSEdu web workshops

Build powerfull and smart web applications with Symfony2
Build powerfull and smart web applications with Symfony2Build powerfull and smart web applications with Symfony2
Build powerfull and smart web applications with Symfony2Hugo Hamon
 
Django - Framework web para perfeccionistas com prazos
Django - Framework web para perfeccionistas com prazosDjango - Framework web para perfeccionistas com prazos
Django - Framework web para perfeccionistas com prazosIgor Sobreira
 
Gae Meets Django
Gae Meets DjangoGae Meets Django
Gae Meets Djangofool2nd
 
Python Code Camp for Professionals 1/4
Python Code Camp for Professionals 1/4Python Code Camp for Professionals 1/4
Python Code Camp for Professionals 1/4DEVCON
 
The Django Web Application Framework 2
The Django Web Application Framework 2The Django Web Application Framework 2
The Django Web Application Framework 2fishwarter
 
The Django Web Application Framework 2
The Django Web Application Framework 2The Django Web Application Framework 2
The Django Web Application Framework 2fishwarter
 
The Django Web Application Framework 2
The Django Web Application Framework 2The Django Web Application Framework 2
The Django Web Application Framework 2fishwarter
 
The Django Web Application Framework 2
The Django Web Application Framework 2The Django Web Application Framework 2
The Django Web Application Framework 2fishwarter
 
Introduction to Django
Introduction to DjangoIntroduction to Django
Introduction to DjangoJoaquim Rocha
 
TurboGears2 Pluggable Applications
TurboGears2 Pluggable ApplicationsTurboGears2 Pluggable Applications
TurboGears2 Pluggable ApplicationsAlessandro Molina
 

Similaire à Flask intro - ROSEdu web workshops (20)

Flask – Python
Flask – PythonFlask – Python
Flask – Python
 
Django crush course
Django crush course Django crush course
Django crush course
 
Build powerfull and smart web applications with Symfony2
Build powerfull and smart web applications with Symfony2Build powerfull and smart web applications with Symfony2
Build powerfull and smart web applications with Symfony2
 
Tornadoweb
TornadowebTornadoweb
Tornadoweb
 
Django - Framework web para perfeccionistas com prazos
Django - Framework web para perfeccionistas com prazosDjango - Framework web para perfeccionistas com prazos
Django - Framework web para perfeccionistas com prazos
 
Mojolicious
MojoliciousMojolicious
Mojolicious
 
Gae Meets Django
Gae Meets DjangoGae Meets Django
Gae Meets Django
 
Python Code Camp for Professionals 1/4
Python Code Camp for Professionals 1/4Python Code Camp for Professionals 1/4
Python Code Camp for Professionals 1/4
 
The Django Web Application Framework 2
The Django Web Application Framework 2The Django Web Application Framework 2
The Django Web Application Framework 2
 
The Django Web Application Framework 2
The Django Web Application Framework 2The Django Web Application Framework 2
The Django Web Application Framework 2
 
The Django Web Application Framework 2
The Django Web Application Framework 2The Django Web Application Framework 2
The Django Web Application Framework 2
 
The Django Web Application Framework 2
The Django Web Application Framework 2The Django Web Application Framework 2
The Django Web Application Framework 2
 
PhpBB meets Symfony2
PhpBB meets Symfony2PhpBB meets Symfony2
PhpBB meets Symfony2
 
Introduction to Django
Introduction to DjangoIntroduction to Django
Introduction to Django
 
Django at the Disco
Django at the DiscoDjango at the Disco
Django at the Disco
 
Django at the Disco
Django at the DiscoDjango at the Disco
Django at the Disco
 
Django at the Disco
Django at the DiscoDjango at the Disco
Django at the Disco
 
Django at the Disco
Django at the DiscoDjango at the Disco
Django at the Disco
 
Django Vs Rails
Django Vs RailsDjango Vs Rails
Django Vs Rails
 
TurboGears2 Pluggable Applications
TurboGears2 Pluggable ApplicationsTurboGears2 Pluggable Applications
TurboGears2 Pluggable Applications
 

Dernier

ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
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 FMESafe Software
 
🐬 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
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdflior mazor
 
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
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MIND CTI
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingEdi Saputra
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodJuan lago vázquez
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024The Digital Insurer
 
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
 
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 Processorsdebabhi2
 
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
 
Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024SynarionITSolutions
 
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
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 

Dernier (20)

ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
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
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.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
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
+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...
 
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
 
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
 
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
 
Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024
 
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
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 

Flask intro - ROSEdu web workshops

  • 1. Flask intro rosedu web workshops 27/03/2013 alex@grep.ro alex@eftimie.ro
  • 2. prerequisites what we'll do ● python ● set-up a working environment ● bash ● run a local server ● HTTP ● write a twitter clone in a single python file ● use templates ● use an ORM
  • 3. was ist flask? ● micro web framework ● WSGI (same as django, webapp2) ● decoupled ● werkzeug routing ● jinja2 templates ● wtf forms ● many extensions ● write web applications not web scripts (such as PHP does)
  • 4. virtualenv, pip # install system-wide apt-get install python-virtualenv # create new virtualenv env # activate source env/bin/activate # install flask pip install flask # pip freeze pip freeze > requirements.txt
  • 5. basic flask app #!/usr/bin/env python (env)student@intel:~$ python mini. py import flask * Running on http://127.0.0.1: 5000/ app = flask.Flask(__name__) 127.0.0.1 - - [27/Mar/2013 01:13: app.config['DEBUG'] = True 28] "GET / HTTP/1.1" 200 - @app.route( '/') def home(): return "Hello World!" if __name__ == '__main__' : app.run()
  • 6. new message form ● create a file new.html inside a templates/ folder <h1>New message </h1> <form method="post"> <textarea rows="4" cols="80" name="message"></textarea> <br> <button type="submit">send</button> </form> ● route /new to a view function rendering the template ... return flask.render_template( 'new.html' ) (see home())
  • 7. form submit; redirect ● check request method (one of 'GET' or 'POST') flask.request.method == 'POST' ● get post data, print it print flask.request.form['message'] ● redirect to home page flask.redirect(flask .url_for('home')) @app.route('/new', methods=['GET', 'POST']) def new(): if flask.request.method == 'POST': print "msg:", flask.request.form['message'] return flask.redirect(flask.url_for('home')) return flask.render_template('new.html')
  • 8. db; message model ● in a terminal: pip install SQLAlchemy Flask-SQLAlchemy ● in mini.py from flask.ext.sqlalchemy import SQLAlchemy ... app.config['SQLALCHEMY_DATABASE_URI' ] = 'sqlite:////tmp/test.db' db = SQLAlchemy(app) ... class Message(db.Model): id = db.Column(db.Integer, primary_key =True) text = db.Column(db.String) time = db.Column(db.DateTime)
  • 9. save to db ● create db before app.run() db.create_all() ● replace print with insert statement, in new() text = flask.request.form[ 'message'] message = Message(text =text, time =datetime.utcnow()) db.session.add(message) db.session.commit() ● sqlite3 /tmp/test.db 'select * from message'
  • 10. fetch from db messages.html ● change print "Hello World" with template rendering and context <h1>Mini Twitter </h1> <p> flask.render_template( 'messages. <a href="{{ url_for('new') }}" >new msg</a> html', </p> messages =Message.query.all()) {% for message in messages %} <article> ● create html file in templates/ <p>{{ message.text }} </p> <footer> <time>{{message.time}} </time> ● use {{ variable }} to display </footer> </article> variable value in template {% endfor %} ● call url_for for view permalink ● use {% for %} to iterate through messages
  • 11. template filters Usage: You: {{ variable |filter }} ● display message time in local time Custom: @app.template_filter() def tolower(value): return value.lower()
  • 12. common layout template layout.html <!doctype html> <html> ... {% block content %} {% endblock %} </html> messages.html {% extends 'layout.html' %} {% block content %} goodies... {% endblock %}
  • 13. config file ● move configuration to a file app.config.from_pyfile( 'settings.py' ) ● settings DEBUG = True ...
  • 14. flash messages ● use session to display messages in the next view flask.flash("I have a message for you" ) ● display messages in template {% for message in get_flashed_messages() %} <p class="msg"> ... {% endfor %} ● put it in header.html then include it before content block in the layout template {% include 'other_template.html' %}
  • 15. login ● view + template the same as new() - new.html ● handle the submitted username if flask.request.method == 'POST': username = flask.request.form['username' ] ... ● print username or flash it {% extends 'layout.html' %} {% block content %} <form method="post"> <input name="username" > <button type="submit" >login</button> </form> {% endblock %}
  • 16. session ● store something in session flask.session['username' ] = username ● fetch and expose in templates @app.before_request def get_user(): flask.g.username = flask.session.get('username' ) ● use in header {% if g.username %} logged in as {{ g.username }} {% else %} <a href="{{ url_for('login') }}" >login</a> {% endif %}
  • 17. logout ● clean the session in style flask.session.pop('variable' , '') ● you ○ write a view logout() ○ route /logout to it ○ delete username from session ○ flash the message "bye bye" ○ redirect to home page ○ link to it in header
  • 18. login required decorator ● redirect to login if not authenticated def login_required(func): @wraps(func) def wrapper(*args, **kwargs): if flask.g.username is None: return flask.redirect('login') return func(*args, **kwargs) return wrapper ● use @app.route('/private') @login_required def private_view(): ... ● you: decorate new()
  • 19. person model ● db model with id (Integer, primary_key) and username (String) ● message author class Message(db.Model): ... person_id = db.Column(db.Integer, db .ForeignKey( 'person.id' )) person = db.relationship( 'Person', backref=db.backref('messages' , lazy='dynamic')) ● get or create Person @classmethod def get_or_create(cls, username): person = cls.query.filter_by(username =username).first() if person is None: person = cls(username =username) ...
  • 20. message and person ● when adding a message to db text = flask.request.form['message'] person = Person.get_or_create(flask .g.username) message = Message(text =text, time =datetime.utcnow(), person =person) ● when displaying in template <p> <strong>{{ message.person.username }}: </strong> {{ message.text }} </p>
  • 21. person and messages ● add view for a person's feed ● route it to /<username> @app.route( '/<username>' ) ● get person or raise http 404 person = Person.query.filter_by(username =username).first_or_404() ● display messages in template flask.render_template( 'messages.html' , messages =person.messages) ● show link to person's feed ... {% set username = message.person.username %} {% set url = url_for('person_feed', username=username) %} <strong><a href="{{ url }}" >{{ username }} </a>:</strong> ...
  • 22. static assets ● create a folder static/ ● add style.css and some ninja CSS ● link to it in layout.html <link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}"> /* style.css */ ● wrap {% block content %} in <div class="container"> </div> * { font-family: Ubuntu, arial } body { background-color: #efefef } .container { width: 800px; margin: 0 auto; background-color: #fff; } p.msg { background-color: #99ff99; border-radius: 20px; border: 1px solid green; color: green: } a { text-decoration: none }
  • 23. wrapping up we learned about: file structure: ● web application mini.py ● url routing settings.py static/ ● templates style.css ● sql templates/ header.html ● sessions layout.html messages.html new.html next: ● deployment options ● security, social extensions
  • 24. see more ● full source code https://github.com/mgax/minitwitter ● flask documentation http://flask.pocoo.org/docs/