SEI-Example
  • Introduction
  • About These Notes
  • Syllabus
  • Development Workflow
    • Installfest
      • Mac OSX
      • Linux
      • Git Configuration
      • Sublime Packages
    • Command Line
      • The Terminal
      • Filesystem Navigation
      • File Manipulation
      • Additional Topics
    • Intro to Git
      • Version Control
      • Local Git
      • Remote Git
      • Git Recipes
    • Group Collaboration
      • Git Workflows
      • Project Roles and Tools
    • VS Code Tips & Tricks
  • HTML/CSS
    • HTML
    • CSS Selectors
    • CSS Box Model and Positioning
      • Box Model
      • Display and Positioning
      • Flexbox
      • Grid
      • Flexbox & Grid Games
      • Floats and Clears
      • Additional Topics
    • Advanced CSS
      • Responsive Design
      • Pseudo-Classes/Elements
      • Vendor Prefixes
      • Custom Properties
      • Additional Topics
    • Bootstrap
    • CSS Frameworks
    • Accessibility
  • JavaScript
    • Primitives
    • Arrays
    • Objects
    • Control Flow
      • Boolean Expressions
      • Conditionals
      • Loops
      • Promises
    • Functions
      • Callbacks
      • Timing Functions
      • Iterators
    • DOM and Events
    • DOM Manipulation
    • HTML5 Canvas
    • How To Reduce Redundancy
    • (2019) JavaScript OOP
    • (2016) OOP with Classes
    • (1995) OOP with Prototypes
      • Constructors
      • Prototypes
    • Intro to TDD
    • Scoping
    • Inheritance
      • Prototypal Inheritance
      • Call, Apply, and other Functions
      • ES6 Inheritance
      • Resources
    • Custom Node Modules
    • Additional Topics
      • AJAX, Fetch, and Async/Await
      • AJAX w/JSON and Localstorage
        • AJAX w/JSON
        • Local Storage
      • Async module
      • Data Scraping
  • jQuery
    • Intro
      • DOM Manipulation
      • Reddit Practice
      • Styling
      • Events
    • Plugins
    • AJAX
  • APIs
    • Fetch
    • AJAX w/jQuery
    • AJAX w/Fetch
  • Databases
    • Intro to SQL
    • Advanced SQL
    • MongoDB
      • Intro to NoSQL
      • CRUD in MongoDB
      • Data Modeling
      • Intermediate Mongo
  • Node/Express
    • Node
      • Intro to Node
      • Node Modules
      • Node Package Manager (NPM)
    • Express
      • Intro to Express
        • Routes
        • Views
        • Templates
        • Layouts and Controllers
        • CRUD & REST
          • Get and Post
          • Put and Delete
      • APIs with Express (request)
      • APIs with Express (axios)
    • Sequelize
      • Terminology
      • Setup
      • Using Models
      • Seeding Data
      • Validations and Migrations
      • Resources
      • 1:M Relationships
      • N:M Relationships
    • Express Authentication
      • Research Components
      • Code Components
      • Auth in Theory
        • Sessions
        • Passwords
        • Middleware
        • Hooks
      • Auth in Practice
        • Create the User
        • User Signup
        • Sessions
        • User Login
        • Authorization and Flash messages
    • Testing with Mocha and Chai
    • Mongoose
      • Mongoose Associations
    • JSON Web Tokens
      • Codealong
    • Additional Topics
      • oAuth
      • Geocoding with Mapbox
      • Geocoding and Google Maps
      • Cloudinary
      • Websockets with Socket.io
      • SASS
  • Ruby
    • Intro to Ruby
    • Ruby Exercises
    • Ruby Classes
    • Ruby Testing with Rspec
    • Ruby Inheritance
    • Ruby Data Scraping
  • Ruby on Rails
    • Intro to Rails
    • APIs with Rails
    • Asset Pipeline
    • Rails Auth and 1-M
      • Auth Components
    • Rails N:M
    • ActiveRecord Polymorphism
    • Additional Topics
      • oAuth
      • SASS
      • Rails Mailers
      • Cloudinary
      • Jekyll
  • React (Updated 2019)
    • ES6+/ESNext
      • Const and Let
      • Arrow Functions
      • Object Literals and String Interpolation
      • ES6 Recap
      • ES6 Activity
    • Intro to React
      • Create React App
      • Components and JSX
      • Virtual DOM
      • Props
      • Dino Blog Activity
      • Nested Components
      • Lab: LotR
    • React State
      • Code-Along: Mood Points
      • Code-Along: Edit Dino Blog
      • Lab: Simple Calc
      • Lifting State
    • React Router
      • Browser History/SPAs
      • React Router (lesson and full codealong)
      • Router Lab
    • Fetch and APIs
      • APIs with Fetch and Axios
      • Fetch the Weather
    • React Hooks
    • React LifeCycle
      • Lab: Component LifeCycle
    • React Deployment
    • Additional Topics
      • React Frameworks
        • Material UI Theming
      • Typescript
        • More Types and Syntax
        • Tsconfig and Declaration Files
        • Generics with Linked List
      • Redux
      • TypeScript
      • Context API
      • React Native
  • Meteor
  • Deployment and Config
    • Deploy - Github Pages
    • Deploy - Node/Sequelize
    • Deploy - Node/MongoDB
    • Deploy React
    • Deploy - Rails
      • Foreman (Environment Variables)
    • Deploy - AWS Elastic Beanstalk
    • Deploy - S3 Static Sites
    • Deploy - Django
    • Deploy - Flask
  • Data Structures and Algorithms
    • Recursion
    • Problem Solving - Array Flatten
    • Binary Search
    • Algorithm Complexity
    • Stacks and Queues
    • Bracket Matching
    • Ruby Linked Lists
      • Sample Code
      • Beginner Exercises
      • Advanced Exercises
    • JS Linked Lists
      • Sample Code
      • Beginner Exercises
      • Beginner Solutions
    • Hash Tables
    • Intro to Sorting
    • Insertion Sort
    • Bucket Sort
    • Bubble Sort
    • Merge Sort
    • Quick Sort
    • Heap Sort
    • Sorting Wrapup
    • Hashmaps
    • Trees and Other Topics
  • Python
    • Python Installation
    • Intro to Python
    • Python Lists
    • Python Loops
    • Python Dictionaries
    • Python Sets and Tuples
    • Python Cheatsheet
    • Python Functions
    • Python Classes
    • Python Class Inheritance
    • Intro to Flask
    • Intro to SQLAlchemy
      • Flask and SQLAlchemy
    • Using PyMongo
    • Intro to Django
    • CatCollector CodeAlong
      • URLs, Views, Templates
      • Models, Migrations
      • Model Form CRUD
      • One-to-Many Relations
      • Many-to-Many Relations
      • Django Auth
    • Django Cheatsheet
    • Django Auth
    • Django Polls App Tutorial
    • Django School Tool Tutorial
    • Django 1:M Relationships
    • Custom Admin Views
    • Data Structures and Algorithms
      • Recursion
      • Binary Search
      • Stacks and Queues
      • Linked Lists
      • Binary Trees
      • Bubble Sort
      • TensorFlow & Neural Networks
    • Adjacent Topics
      • Raspberry Pi
      • Scripting
  • Assorted Topics
    • History of Computer Science
    • Regular Expressions
    • Intro to WDI (Course Info)
    • Being Successful in WDI
    • Internet Fundamentals
      • Internet Lab
    • User Stories and Wireframing
      • Wireframing Exercise: Build an Idea
    • Post WDI
      • Learning Resources
      • Deliverables -> Portfolio
      • FAQ
  • Projects
    • Project 1
    • Project 2
    • Project 3
      • Project 3 Pitch Guidelines
    • Project 4
    • Past Projects
      • Project 1
      • Project 2
      • Project 3
      • Project 4
      • Portfolios
    • Post Project 2
    • MEAN Hackathon
      • Part 1: APIs
      • Part 2: Angular
    • Portfolio
  • Web Development Trends
  • Resources
    • APIs and Data
    • Tech Websites
    • PostgreSQL Cheat Sheet
    • Sequelize Cheat Sheet
    • Database Administration
  • Archived Section
    • (Archived) ReactJS
      • Intro to React
        • Todo List Codealong
        • Additional Topics
      • Deploy React
      • React with Gulp and Browserify
        • Setting up Gulp
        • Additional Gulp Tasks
      • React Router
        • OMDB Router
        • OMDB Search
        • Additional Resources
      • React Animations
        • CSS Animations
    • AngularJS
      • Intro to AngularJS
        • Components and SPA
        • Create an Angular App
      • Angular Directives and Filters
      • Angular Animation
      • Angular Bootstrap Directives
        • Bootstrap Modals
      • Angular $http
      • Angular Services
        • Service Recipes
        • ngResource
        • Star Wars Codealong
      • Angular Routing
      • Angular + Express
      • Angular Authentication
        • Additional Topics
      • Angular Components
      • Angular Custom Filters
      • Angular Custom Directives
Powered by GitBook
On this page
  • Intro to Flask
  • Objectives
  • What is Flask?
  • Install Flask and Create a Minimal Server
  • Configure Route Variables
  • Serve Static Content
  • Last Remarks
  • Microframework vs Monolithic Framework
  1. Python

Intro to Flask

PreviousPython Class InheritanceNextIntro to SQLAlchemy

Last updated 3 years ago

Intro to Flask

Objectives

  • Use the Flask microframework to create a Python web server

  • Configure a GET route to send raw data

  • Configure a GET route accept query parameters

  • Configure the server to serve static content

What is Flask?

Flask describes itself as a microframework. It comes with a small set of utilities that will help you define routes on a server, and send files back to a browser.

Flask acts a lot like Express in that it imports lots of little single-use packages. We describe this as a "microframework." The framework relies on all of the little packages developers choose to pull in themselves and the framework just deals with allowing those packages to be used in a server environment easily.

Install Flask and Create a Minimal Server

Use your terminal's pip3 command to install Flask for Python3.

pip3 install Flask

Now that Flask is install, create a file server.py that imports Flask and configures a simple GET route at the server's root. You'll notice the way Flask defines routes is very similar to how routes are defined in Express!

It's this simple:

from flask import Flask
app = Flask(__name__)

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

if __name__ == "__main__":
  app.run()

Configure Route Variables

Like Express, Flask allows us to bake valuable information into our URL structure. Embedding information into our URLs allows our web applications to have beautiful URLs that users can remember easily.

Flask extracts the string in the part of the URL and passes it to the route function as a parameter. It will automatically keep the value as a string unless you specify another type, like int. If you specify a type Flask runs the value through what it calls a "convertor". Flask comes with a few convertors out of the box.

IMPORTANT: Flask expects every route to eventually return a String. Look at the multiply route example. Although it specifies that it accepts two ints as route variables it still must manually convert the mathematical result into a String before the server sends a response.

Convertor Name
Description

string

accepts any text without a slash (the default)

int

accepts integers

float

like int but for floating point values

path

like the default but also accepts slashes

any

matches one of the items provided

uuid

accepts UUID strings

from flask import Flask
app = Flask(__name__)

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

@app.route("/profile/<username>")
def profile(username):
  return "You're viewing {}'s profile.".format(username)

@app.route("/r/<subreddit>")
def profile(subreddit):
  return "Welcome to the {} subreddit!".format(subreddit)


@app.route("/multiply/<int:num1>/<int:num2>")
def multiply(num1, num2):
  result = num1 * num2
  return str(result)

if __name__ == "__main__":
  app.run()

Serve Static Content

The app = Flask() function includes useful parameters to customize how static content is served. These two parameters define where your static directory is located, and where that directory is made available as a URL on your server.

  • static_folder defines the name of the directory containing static content.

  • static_url_path defines what URL you have to direct your browser to to access the static content.

  • if static_url_path is set to 'public' then your index page would be

  • if static_url_path is set to an empty string '' then your index page

    likely what you want.)

You can serve a simple index.html file that includes a script tag link to Angular and now you've got a simple server serving an Angular app!

Application directory structure:

~/Code/my_flask_server/
--server.py
--static/
----index.html

server.py

from flask import Flask
app = Flask(__name__, static_folder='static', static_url_path='')

if __name__ == "__main__":
  app.run()

Last Remarks

There you go! That's the basics of using Python together with Flask. Remember, Flask calls itself a "microframework". It tries to do provide developers with just what they need to create a simple web server and nothing more. It stays out of the way of making major development decisions for you and relies on developers creating powerful web servers by choosing their own components to deal with things like Database management and whatever else you'd need.

Here's a summary of the Unix Philosophy:

  • Write programs that do one thing and do it well.

  • Write programs to work together.

  • Write programs to handle text streams, because that is a universal interface.

Microframework vs Monolithic Framework

In contrast, we'll also learn about another Python web framework: Django. Django is a "monolithic" framework that involves itself in much more in the configuration and operation of a web server. Whereas Flask makes zero decisions for you and relies on developers importing lots of Third-party libraries, Django comes with LOTS of tools in it's box. Django uses it's own template system, has it's own Object Relation Model (ORM) that it uses to interact with databases and even includes it's own administrative tools, that are actually really awesome and allow you to easily build websites where you get an administrative panel where you can edit entries in your database within the website.

Both frameworks have their advantages. If you're looking to pop something up quick and light, then use Flask and follow their motto of bringing in dependencies, "drop by drop." If you're looking to build a site that would benefit from already-integrated user accounts, and batteries-included administrative tools, then Django might be a better choice.

Happy developing.

if static_url_path is not defined then it defaults to 'static' and an index.html in the static directory would be accessible at

available at

is available at the server root: (this is most

Flask adheres to the where they "strive to do one thing and do it well."

Flask Docs
Mongo Tutorial
http://127.0.0.1:5000/static/index.html
http://127.0.0.1:5000/public/index.html
http://127.0.0.1:5000/
Unix Philosphy