SlideShare a Scribd company logo
2
Most read
3
Most read
Flask, for people who like to have
       a little drink at night
                Areski Belaid
            <areski@gmail.com>
              21th March 2013

            slideshare.net/areski/
Flask Introduction

What is Flask?
Flask is a micro web development framework
for Python

What is MicroFramework?
Keep the core simple but extensible

“Micro” does not mean that your whole web
application has to fit into one Python file
Installation
Dependencies: Werkzeug and Jinja2

      $ sudo pip install virtualenv
      $ virtualenv venv
      $ . venv/bin/activate
      $ pip install Flask

If you want to work with databases you will need:

      $ pip install Flask-SQLAlchemy
QuickStart
A minimal Flask application looks something like this:
1.    from flask import Flask
2.    app = Flask(__name__)

3.    @app.route('/')
4.    def hello_world():
        return 'Hello World!'

5.    if __name__ == '__main__':
          app.debug = True
          app.run()

Save and run it with your Python interpreter:
      $ python hello.py
      * Running on http://127.0.0.1:5000/
This is the end...




   You can now write a Flask application!
URLs
The route() decorator is used to bind a function to a URL:
    @app.route('/')
    def index():
      return 'Index Page'

    @app.route('/hello')
    def hello():
      return 'Hello World'

We can add variable parts:
    @app.route('/user/<username>')
    def show_user_profile(username):
      # show the user profile for that user
      return 'User %s' % username

    @app.route('/post/<int:post_id>')
    def show_post(post_id):
      return 'Post %d' % post_id
HTTP Method
By default, a route only answers GET requests, but this can be changed by
providing the methods argument to the route() decorator:

    @app.route('/login', methods=['GET', 'POST'])
    def login():
      if request.method == 'POST':
          do_the_login()
      else:
          show_the_login_form()

We can ask Flask do the hard work and use decorator:
   @app.route ( ’/login ’ , methods =[ ’ GET ’ ])
   def show_the_login_form ():
   ...
   @app.route ( ’/login’ , methods =[ ’ POST ’ ])
   def do_the_login ():
   ...
Rendering templates
To render a template you can use the render_template() method:

         from flask import render_template

         @app.route('/hello/')
         @app.route('/hello/<name>')
         def hello(name=None):
           return render_template('hello.html', name=name)


Let's say you want to display a list of blog posts, you will connect to your DB and
push the “posts” list to your template engine:

         @app.route('/posts/')
         def show_post():
              cur = g.db.execute('SELECT title, text FROM post')
              posts = [dict(title=row[0], text=row[1]) for row in cur.fetchall()]
                   return render_template('show_post.html', posts=posts)
Rendering templates (next)
The show_posts.html template file would look like:

         <!doctype html>
         <title>Blog with Flask</title>
         <div>
         <h1>List posts</h1>
         <ul>
         {% for post in posts %}
               <li><h2>{{ post.title }}</h2>{{ post.text|safe }}
         {% else %}
               <li><em>Unbelievable, there is no post!</em>
         {% endfor %}
         </div>
More and more and more...
  ○   Access request data

  ○   Cookies

  ○   Session

  ○   File Upload

  ○   Cache

  ○   Class Base View

  ○   …



                Flask has incredible documentation...
Flask vs Django
                                  Flask               Django

     Template                     Jinja2                Own

     Signals                     Blinker                Own

     i18N                         Babel                 Own

     ORM                           Any                  Own

     Admin                     Flask-Admin           Builtin-Own




* Django is large and monolithic
     Difficult to change / steep learning curve

* Flask is Small and extensible
     Add complexity as necessary / learn as you go
Lots of extensions
http://flask.pocoo.org/extensions/


    ●   YamlConfig
    ●   WTForm
    ●   MongoDB flask
    ●   S3
    ●   Resful API
    ●   Admin
    ●   Bcrypt
    ●   Celery
    ●   DebugToolbar
Admin
https://pypi.python.org/pypi/Flask-Admin

Very simple example, how to use Flask/SQLalchemy and create an admin
https://github.com/MrJoes/Flask-Admin/tree/master/examples/sqla
Conclusion

- Flask is a strong and flexible web framework

- Still micro, but not in terms of features

- You can and should build Web applications with Flask
Hope you enjoyed it!
       Questions?

    slideshare.net/areski/

    github.com/areski/

    twitter.com/areskib




Contact email : areski@gmail.com

More Related Content

What's hot (20)

PPTX
Python/Flask Presentation
Parag Mujumdar
 
PPTX
Flask
Mamta Kumari
 
PPT
Learn flask in 90mins
Larry Cai
 
PPTX
Web development with django - Basics Presentation
Shrinath Shenoy
 
PPTX
AngularJS Directives
Eyal Vardi
 
PPTX
Django - Python MVC Framework
Bala Kumar
 
PDF
A Basic Django Introduction
Ganga Ram
 
PPTX
Introduction to Django
Knoldus Inc.
 
PDF
Introduction to django
Ilian Iliev
 
PPTX
Pytest KT.pptx
RameshN849679
 
PPT
JavaScript
Sunil OS
 
PDF
Rest api with Python
Santosh Ghimire
 
PDF
Django Tutorial | Django Web Development With Python | Django Training and Ce...
Edureka!
 
PPTX
Sling models by Justin Edelson
AEM HUB
 
PDF
JavaScript - Chapter 8 - Objects
WebStackAcademy
 
PDF
Web develop in flask
Jim Yeh
 
PDF
Hacking Adobe Experience Manager sites
Mikhail Egorov
 
PPTX
Build RESTful API Using Express JS
Cakra Danu Sedayu
 
PDF
Python RESTful webservices with Python: Flask and Django solutions
Solution4Future
 
Python/Flask Presentation
Parag Mujumdar
 
Learn flask in 90mins
Larry Cai
 
Web development with django - Basics Presentation
Shrinath Shenoy
 
AngularJS Directives
Eyal Vardi
 
Django - Python MVC Framework
Bala Kumar
 
A Basic Django Introduction
Ganga Ram
 
Introduction to Django
Knoldus Inc.
 
Introduction to django
Ilian Iliev
 
Pytest KT.pptx
RameshN849679
 
JavaScript
Sunil OS
 
Rest api with Python
Santosh Ghimire
 
Django Tutorial | Django Web Development With Python | Django Training and Ce...
Edureka!
 
Sling models by Justin Edelson
AEM HUB
 
JavaScript - Chapter 8 - Objects
WebStackAcademy
 
Web develop in flask
Jim Yeh
 
Hacking Adobe Experience Manager sites
Mikhail Egorov
 
Build RESTful API Using Express JS
Cakra Danu Sedayu
 
Python RESTful webservices with Python: Flask and Django solutions
Solution4Future
 

Viewers also liked (20)

PPT
Flask - Python microframework
André Mayer
 
PDF
Flask admin vs. DIY
dokenzy
 
PDF
Python web frameworks
NEWLUG
 
PPTX
Flask vs. Django
Rachel Sanders
 
PDF
Building Automated REST APIs with Python
Jeff Knupp
 
PDF
Developing RESTful Web APIs with Python, Flask and MongoDB
Nicola Iarocci
 
PDF
Lightweight web frameworks
Jonathan Holloway
 
PDF
Kyiv.py #17 Flask talk
Alexey Popravka
 
PDF
Flask - Backend com Python - Semcomp 18
Lar21
 
PDF
Nikola, a static blog & site generator python meetup 19 feb2014
Areski Belaid
 
PDF
Newfies dialer - autodialer : freeswitch weekly conference 13 march2013
Areski Belaid
 
PDF
Whitepaper newfies-dialer Autodialer
Areski Belaid
 
PPTX
Flask
Elita Lobo
 
PDF
Newfies dialer Brief Introduction
Areski Belaid
 
PDF
Newfies dialer Auto dialer Software
Areski Belaid
 
PDF
CDR-Stats : VoIP Analytics Solution for Asterisk and FreeSWITCH with MongoDB
Areski Belaid
 
PDF
What The Flask? and how to use it with some Google APIs
Bruno Rocha
 
PDF
Django para portais de alta visibilidade. tdc 2013
Bruno Rocha
 
PDF
Build website in_django
swee meng ng
 
PDF
Writing your first web app using Python and Flask
Danielle Madeley
 
Flask - Python microframework
André Mayer
 
Flask admin vs. DIY
dokenzy
 
Python web frameworks
NEWLUG
 
Flask vs. Django
Rachel Sanders
 
Building Automated REST APIs with Python
Jeff Knupp
 
Developing RESTful Web APIs with Python, Flask and MongoDB
Nicola Iarocci
 
Lightweight web frameworks
Jonathan Holloway
 
Kyiv.py #17 Flask talk
Alexey Popravka
 
Flask - Backend com Python - Semcomp 18
Lar21
 
Nikola, a static blog & site generator python meetup 19 feb2014
Areski Belaid
 
Newfies dialer - autodialer : freeswitch weekly conference 13 march2013
Areski Belaid
 
Whitepaper newfies-dialer Autodialer
Areski Belaid
 
Flask
Elita Lobo
 
Newfies dialer Brief Introduction
Areski Belaid
 
Newfies dialer Auto dialer Software
Areski Belaid
 
CDR-Stats : VoIP Analytics Solution for Asterisk and FreeSWITCH with MongoDB
Areski Belaid
 
What The Flask? and how to use it with some Google APIs
Bruno Rocha
 
Django para portais de alta visibilidade. tdc 2013
Bruno Rocha
 
Build website in_django
swee meng ng
 
Writing your first web app using Python and Flask
Danielle Madeley
 
Ad

Similar to Flask Introduction - Python Meetup (20)

PDF
Flask intro - ROSEdu web workshops
Alex Eftimie
 
PDF
Introduction to Flask Micro Framework
Mohammad Reza Kamalifard
 
PPTX
Flask-Python
Triloki Gupta
 
PDF
Python Web Applications With Flask Handon Your Flask Skills2024 Jeffrey Leon ...
keyroreagan
 
KEY
LvivPy - Flask in details
Max Klymyshyn
 
PPTX
Flask Application ppt to understand the flask
vijoho5545
 
PPTX
Intro to flask2
Mohamed Essam
 
PPTX
Intro to flask
Mohamed Essam
 
PDF
Flask Web Development 1st Edition Miguel Grinberg
cjvsgfu2766
 
PDF
BUILDING MODERN PYTHON WEB FRAMEWORKS USING FLASK WITH NEIL GREY
CodeCore
 
PDF
Python and Flask introduction for my classmates Презентация и введение в flask
Nikita Lozhnikov
 
PDF
Web Server and how we can design app in C#
caohansnnuedu
 
PDF
Flask patterns
it-people
 
PDF
CollegeDiveIn presentation
Karambir Singh Nain
 
PDF
Python master class part 1
Chathuranga Bandara
 
PDF
An Introduction to Tornado
Gavin Roy
 
PDF
django_introduction20141030
Kevin Wu
 
PPTX
Building a local web application with Flask
Hoffman Lab
 
PDF
Intro to Jinja2 Templates - San Francisco Flask Meetup
Alan Hamlett
 
Flask intro - ROSEdu web workshops
Alex Eftimie
 
Introduction to Flask Micro Framework
Mohammad Reza Kamalifard
 
Flask-Python
Triloki Gupta
 
Python Web Applications With Flask Handon Your Flask Skills2024 Jeffrey Leon ...
keyroreagan
 
LvivPy - Flask in details
Max Klymyshyn
 
Flask Application ppt to understand the flask
vijoho5545
 
Intro to flask2
Mohamed Essam
 
Intro to flask
Mohamed Essam
 
Flask Web Development 1st Edition Miguel Grinberg
cjvsgfu2766
 
BUILDING MODERN PYTHON WEB FRAMEWORKS USING FLASK WITH NEIL GREY
CodeCore
 
Python and Flask introduction for my classmates Презентация и введение в flask
Nikita Lozhnikov
 
Web Server and how we can design app in C#
caohansnnuedu
 
Flask patterns
it-people
 
CollegeDiveIn presentation
Karambir Singh Nain
 
Python master class part 1
Chathuranga Bandara
 
An Introduction to Tornado
Gavin Roy
 
django_introduction20141030
Kevin Wu
 
Building a local web application with Flask
Hoffman Lab
 
Intro to Jinja2 Templates - San Francisco Flask Meetup
Alan Hamlett
 
Ad

Recently uploaded (20)

PDF
Go Concurrency Real-World Patterns, Pitfalls, and Playground Battles.pdf
Emily Achieng
 
PDF
“Squinting Vision Pipelines: Detecting and Correcting Errors in Vision Models...
Edge AI and Vision Alliance
 
PDF
“Computer Vision at Sea: Automated Fish Tracking for Sustainable Fishing,” a ...
Edge AI and Vision Alliance
 
PDF
The 2025 InfraRed Report - Redpoint Ventures
Razin Mustafiz
 
PDF
Mastering Financial Management in Direct Selling
Epixel MLM Software
 
PPT
Ericsson LTE presentation SEMINAR 2010.ppt
npat3
 
PPTX
AI Penetration Testing Essentials: A Cybersecurity Guide for 2025
defencerabbit Team
 
DOCX
Cryptography Quiz: test your knowledge of this important security concept.
Rajni Bhardwaj Grover
 
PPTX
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
PDF
Automating Feature Enrichment and Station Creation in Natural Gas Utility Net...
Safe Software
 
PDF
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
PDF
Newgen Beyond Frankenstein_Build vs Buy_Digital_version.pdf
darshakparmar
 
DOCX
Python coding for beginners !! Start now!#
Rajni Bhardwaj Grover
 
PPTX
MuleSoft MCP Support (Model Context Protocol) and Use Case Demo
shyamraj55
 
PDF
Peak of Data & AI Encore AI-Enhanced Workflows for the Real World
Safe Software
 
PDF
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
PDF
“NPU IP Hardware Shaped Through Software and Use-case Analysis,” a Presentati...
Edge AI and Vision Alliance
 
PDF
POV_ Why Enterprises Need to Find Value in ZERO.pdf
darshakparmar
 
PDF
Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
PPTX
Designing_the_Future_AI_Driven_Product_Experiences_Across_Devices.pptx
presentifyai
 
Go Concurrency Real-World Patterns, Pitfalls, and Playground Battles.pdf
Emily Achieng
 
“Squinting Vision Pipelines: Detecting and Correcting Errors in Vision Models...
Edge AI and Vision Alliance
 
“Computer Vision at Sea: Automated Fish Tracking for Sustainable Fishing,” a ...
Edge AI and Vision Alliance
 
The 2025 InfraRed Report - Redpoint Ventures
Razin Mustafiz
 
Mastering Financial Management in Direct Selling
Epixel MLM Software
 
Ericsson LTE presentation SEMINAR 2010.ppt
npat3
 
AI Penetration Testing Essentials: A Cybersecurity Guide for 2025
defencerabbit Team
 
Cryptography Quiz: test your knowledge of this important security concept.
Rajni Bhardwaj Grover
 
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
Automating Feature Enrichment and Station Creation in Natural Gas Utility Net...
Safe Software
 
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
Newgen Beyond Frankenstein_Build vs Buy_Digital_version.pdf
darshakparmar
 
Python coding for beginners !! Start now!#
Rajni Bhardwaj Grover
 
MuleSoft MCP Support (Model Context Protocol) and Use Case Demo
shyamraj55
 
Peak of Data & AI Encore AI-Enhanced Workflows for the Real World
Safe Software
 
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
“NPU IP Hardware Shaped Through Software and Use-case Analysis,” a Presentati...
Edge AI and Vision Alliance
 
POV_ Why Enterprises Need to Find Value in ZERO.pdf
darshakparmar
 
Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
Designing_the_Future_AI_Driven_Product_Experiences_Across_Devices.pptx
presentifyai
 

Flask Introduction - Python Meetup

  • 1. Flask, for people who like to have a little drink at night Areski Belaid <[email protected]> 21th March 2013 slideshare.net/areski/
  • 2. Flask Introduction What is Flask? Flask is a micro web development framework for Python What is MicroFramework? Keep the core simple but extensible “Micro” does not mean that your whole web application has to fit into one Python file
  • 3. Installation Dependencies: Werkzeug and Jinja2 $ sudo pip install virtualenv $ virtualenv venv $ . venv/bin/activate $ pip install Flask If you want to work with databases you will need: $ pip install Flask-SQLAlchemy
  • 4. QuickStart A minimal Flask application looks something like this: 1. from flask import Flask 2. app = Flask(__name__) 3. @app.route('/') 4. def hello_world(): return 'Hello World!' 5. if __name__ == '__main__': app.debug = True app.run() Save and run it with your Python interpreter: $ python hello.py * Running on http://127.0.0.1:5000/
  • 5. This is the end... You can now write a Flask application!
  • 6. URLs The route() decorator is used to bind a function to a URL: @app.route('/') def index(): return 'Index Page' @app.route('/hello') def hello(): return 'Hello World' We can add variable parts: @app.route('/user/<username>') def show_user_profile(username): # show the user profile for that user return 'User %s' % username @app.route('/post/<int:post_id>') def show_post(post_id): return 'Post %d' % post_id
  • 7. HTTP Method By default, a route only answers GET requests, but this can be changed by providing the methods argument to the route() decorator: @app.route('/login', methods=['GET', 'POST']) def login(): if request.method == 'POST': do_the_login() else: show_the_login_form() We can ask Flask do the hard work and use decorator: @app.route ( ’/login ’ , methods =[ ’ GET ’ ]) def show_the_login_form (): ... @app.route ( ’/login’ , methods =[ ’ POST ’ ]) def do_the_login (): ...
  • 8. Rendering templates To render a template you can use the render_template() method: from flask import render_template @app.route('/hello/') @app.route('/hello/<name>') def hello(name=None): return render_template('hello.html', name=name) Let's say you want to display a list of blog posts, you will connect to your DB and push the “posts” list to your template engine: @app.route('/posts/') def show_post(): cur = g.db.execute('SELECT title, text FROM post') posts = [dict(title=row[0], text=row[1]) for row in cur.fetchall()] return render_template('show_post.html', posts=posts)
  • 9. Rendering templates (next) The show_posts.html template file would look like: <!doctype html> <title>Blog with Flask</title> <div> <h1>List posts</h1> <ul> {% for post in posts %} <li><h2>{{ post.title }}</h2>{{ post.text|safe }} {% else %} <li><em>Unbelievable, there is no post!</em> {% endfor %} </div>
  • 10. More and more and more... ○ Access request data ○ Cookies ○ Session ○ File Upload ○ Cache ○ Class Base View ○ … Flask has incredible documentation...
  • 11. Flask vs Django Flask Django Template Jinja2 Own Signals Blinker Own i18N Babel Own ORM Any Own Admin Flask-Admin Builtin-Own * Django is large and monolithic Difficult to change / steep learning curve * Flask is Small and extensible Add complexity as necessary / learn as you go
  • 12. Lots of extensions http://flask.pocoo.org/extensions/ ● YamlConfig ● WTForm ● MongoDB flask ● S3 ● Resful API ● Admin ● Bcrypt ● Celery ● DebugToolbar
  • 13. Admin https://pypi.python.org/pypi/Flask-Admin Very simple example, how to use Flask/SQLalchemy and create an admin https://github.com/MrJoes/Flask-Admin/tree/master/examples/sqla
  • 14. Conclusion - Flask is a strong and flexible web framework - Still micro, but not in terms of features - You can and should build Web applications with Flask
  • 15. Hope you enjoyed it! Questions? slideshare.net/areski/ github.com/areski/ twitter.com/areskib Contact email : [email protected]