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

PDF
Python Flask Tutorial For Beginners | Flask Web Development Tutorial | Python...
PPTX
Python/Flask Presentation
PDF
Quick flask an intro to flask
PPTX
Flask – Python
PDF
Web develop in flask
PDF
3. Java Script
PPTX
PDF
How to Avoid Common Mistakes When Using Reactor Netty
Python Flask Tutorial For Beginners | Flask Web Development Tutorial | Python...
Python/Flask Presentation
Quick flask an intro to flask
Flask – Python
Web develop in flask
3. Java Script
How to Avoid Common Mistakes When Using Reactor Netty

What's hot (20)

PDF
JavaScript - Chapter 8 - Objects
PPT
Angular 8
PPTX
Spring Boot and REST API
PDF
Rest api with Python
PPTX
PPT
PHP - DataType,Variable,Constant,Operators,Array,Include and require
PPTX
Django - Python MVC Framework
PDF
What is REST API? REST API Concepts and Examples | Edureka
PDF
JavaScript - Chapter 11 - Events
PDF
Chapter 1. java programming language overview
PDF
Data Persistence in Android with Room Library
PDF
Web Development with Python and Django
PDF
Retrofit
PPTX
Introduction to Django
PDF
Flask Basics
PPTX
Angular js PPT
PPT
Web Development using HTML & CSS
PPSX
Sessions and cookies
PDF
Deep dive into Coroutines on JVM @ KotlinConf 2017
PPTX
Introduction to laravel framework
JavaScript - Chapter 8 - Objects
Angular 8
Spring Boot and REST API
Rest api with Python
PHP - DataType,Variable,Constant,Operators,Array,Include and require
Django - Python MVC Framework
What is REST API? REST API Concepts and Examples | Edureka
JavaScript - Chapter 11 - Events
Chapter 1. java programming language overview
Data Persistence in Android with Room Library
Web Development with Python and Django
Retrofit
Introduction to Django
Flask Basics
Angular js PPT
Web Development using HTML & CSS
Sessions and cookies
Deep dive into Coroutines on JVM @ KotlinConf 2017
Introduction to laravel framework
Ad

Viewers also liked (20)

PPT
Flask - Python microframework
PDF
Flask admin vs. DIY
PDF
Python web frameworks
PPTX
Flask vs. Django
PDF
Building Automated REST APIs with Python
PDF
Developing RESTful Web APIs with Python, Flask and MongoDB
PDF
Lightweight web frameworks
PDF
Kyiv.py #17 Flask talk
PDF
Flask - Backend com Python - Semcomp 18
PDF
Nikola, a static blog & site generator python meetup 19 feb2014
PDF
Newfies dialer - autodialer : freeswitch weekly conference 13 march2013
PDF
Whitepaper newfies-dialer Autodialer
PPTX
Flask
PDF
Newfies dialer Brief Introduction
PDF
Newfies dialer Auto dialer Software
PDF
CDR-Stats : VoIP Analytics Solution for Asterisk and FreeSWITCH with MongoDB
PPT
Learn flask in 90mins
PDF
What The Flask? and how to use it with some Google APIs
PDF
Django para portais de alta visibilidade. tdc 2013
PDF
Build website in_django
Flask - Python microframework
Flask admin vs. DIY
Python web frameworks
Flask vs. Django
Building Automated REST APIs with Python
Developing RESTful Web APIs with Python, Flask and MongoDB
Lightweight web frameworks
Kyiv.py #17 Flask talk
Flask - Backend com Python - Semcomp 18
Nikola, a static blog & site generator python meetup 19 feb2014
Newfies dialer - autodialer : freeswitch weekly conference 13 march2013
Whitepaper newfies-dialer Autodialer
Flask
Newfies dialer Brief Introduction
Newfies dialer Auto dialer Software
CDR-Stats : VoIP Analytics Solution for Asterisk and FreeSWITCH with MongoDB
Learn flask in 90mins
What The Flask? and how to use it with some Google APIs
Django para portais de alta visibilidade. tdc 2013
Build website in_django
Ad

Similar to Flask Introduction - Python Meetup (20)

KEY
LvivPy - Flask in details
PPT
Building Single Page Application (SPA) with Symfony2 and AngularJS
PDF
Python RESTful webservices with Python: Flask and Django solutions
PDF
Intro to Laravel 4
ODP
Knolx session
PDF
Selenium & PHPUnit made easy with Steward (Berlin, April 2017)
ODP
Introduce Django
PDF
Building web framework with Rack
ODP
Exploring Symfony's Code
ODP
Drupal Best Practices
PDF
ElggCamp Santiago - Dev Edition
PDF
ElggCamp Santiago> For Developers!
ODP
Zen and the Art of Claroline Module Development
PDF
Symfony2 revealed
PPTX
Symfony2 Introduction Presentation
PDF
Mojolicious
PPTX
Flask-RESTPlusで便利なREST API開発 | Productive RESTful API development with Flask-...
PPS
Simplify your professional web development with symfony
PPTX
Laravel development (Laravel History, Environment Setup & Laravel Installatio...
PDF
JavaScript guide 2020 Learn JavaScript
LvivPy - Flask in details
Building Single Page Application (SPA) with Symfony2 and AngularJS
Python RESTful webservices with Python: Flask and Django solutions
Intro to Laravel 4
Knolx session
Selenium & PHPUnit made easy with Steward (Berlin, April 2017)
Introduce Django
Building web framework with Rack
Exploring Symfony's Code
Drupal Best Practices
ElggCamp Santiago - Dev Edition
ElggCamp Santiago> For Developers!
Zen and the Art of Claroline Module Development
Symfony2 revealed
Symfony2 Introduction Presentation
Mojolicious
Flask-RESTPlusで便利なREST API開発 | Productive RESTful API development with Flask-...
Simplify your professional web development with symfony
Laravel development (Laravel History, Environment Setup & Laravel Installatio...
JavaScript guide 2020 Learn JavaScript

Recently uploaded (20)

PPTX
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
PDF
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PPTX
Big Data Technologies - Introduction.pptx
PDF
AI And Its Effect On The Evolving IT Sector In Australia - Elevate
PPT
Teaching material agriculture food technology
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PPTX
Understanding_Digital_Forensics_Presentation.pptx
PPTX
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
PDF
KodekX | Application Modernization Development
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PDF
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
PDF
Empathic Computing: Creating Shared Understanding
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PPTX
Cloud computing and distributed systems.
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PDF
cuic standard and advanced reporting.pdf
PDF
Review of recent advances in non-invasive hemoglobin estimation
PPTX
MYSQL Presentation for SQL database connectivity
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
20250228 LYD VKU AI Blended-Learning.pptx
Big Data Technologies - Introduction.pptx
AI And Its Effect On The Evolving IT Sector In Australia - Elevate
Teaching material agriculture food technology
Advanced methodologies resolving dimensionality complications for autism neur...
Understanding_Digital_Forensics_Presentation.pptx
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
KodekX | Application Modernization Development
Diabetes mellitus diagnosis method based random forest with bat algorithm
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
Empathic Computing: Creating Shared Understanding
“AI and Expert System Decision Support & Business Intelligence Systems”
Cloud computing and distributed systems.
The Rise and Fall of 3GPP – Time for a Sabbatical?
Reach Out and Touch Someone: Haptics and Empathic Computing
cuic standard and advanced reporting.pdf
Review of recent advances in non-invasive hemoglobin estimation
MYSQL Presentation for SQL database connectivity

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]