Intro
Flask is a great Python microframework that can make building web sites and applications much faster. It offers some handy and reliable shortcuts and tools that’ll make your web development life a lot easier.
We call a Flask script an App.
View: A view is a function that returns an HTTP response. This response has to be a string but can be any string you want.
Route: A route is the URL path to a view. They always start with a forward slash / and can end with one if you want.
The Request/Response Cycle
1. The app gets all the requests from the people on the internet
2. The app looks at all the routes and figures out which function (i.e. View) to call
3. The view then sends back a response which can be in HTML, JSON, XML, etc.
Creating First App
After installing Flask on your Virtual Environment simply via pip, write your first app through the following steps:
- Import the framework
- Create framework app instance
- Create view(s)
- Create route(s) for view – for Requests & Responds.
- Run app
#[simple_app.py]:
from flask import Flask
app = Flask(__name__)
@app.route('/')
def index():
return "Hello from Treehouse"
app.run(debug=True, port=8000, host='0.0.0.0')
app = Flask(__name__) Create an app instance
__name__
Using this magic variable means: Use whatever our current name space is.
So if we run this file: “python simple_app.py” then the name space is: “__main__” which means it is being run directly.
If we import “simple_app.py” to another file then the name space is “simple_app”
app.run( ) Run the app
debug=True Automatically restart on new added changes
port=8000, host=’0.0.0.0′ Just for Treehouse
@app.route(‘/’) Decorator: wraps a function. Gives a route that turns a function into a View
def index(): A function that will be our View