flask Flashcards
Flask: To import the flask class, type
from flask import Flask
Flask: To create an instance of the Flask class, type
app = Flask(__name__)
Flask: To make an app run but automatically use changes to the server code, type
app.run(debug=True)
Flask: To create the route for an app, type
@app.route("/") def index(): return "This is my route"
Flask: To import the request library, type
form flask import request
@app.route("/") def index(name_var="Default Name"): name = request.args.get("name", name_var) return name note: .get returns either the value on query string and if none present, returns whatever is after the comma.
Yes e.g.
@app.route(“/route_one”)
@app.route(“/route_two”)
from flask import Flask
app = Flask(__name__)
@app.route("//") def my_function(name, age): return "Im {}, {}".format(name, age)
Flask: Values pulled from the url are automatically the type
string
name the parameter in the function the same as what you are naming the url slash index, e.g.
@app.route("/") def my_function(name): return "Im {}".format(age)
Flask: To run a flask app on the local host, type
from flask import Flask
app = Flask(__name__)
@app.route('/') def hello_world(): return 'Hello World!'
if __name__ == ‘__main__’:
app.run()
Then save it and run it in python from the command line.
Flask: Triple quotes allow you to
Use line breaks by pressing enter
Flask: Flask automatically looks for a directory in the same directory as the app called
Templates. And it will automatically serve whats in it when you reference templates in your view.
Flask: To import templates in the app, type
from flask import render_template
Flask: To make a view return a template and pass it the variables, type
@app.route("/") def my_function(): return render_template("name.html", var_1=name, var_2=age)
Flask: When making views, make sure to always
pass in all of the variables you declare in the view.
Flask: To make the html template pull variables from the view, type
{{ var_name }}
Flask: html templates can be altered in just a small portion, by changing a
block
Flask: To imbed blocks inside the html templates, type
{% block block_name %}{% endblock %}
Flask: To create an extends html block, type
{% extends “layout.html” %}
Flask: The extends block
Imports all of the html of the file you link to except what is contained in the blocks which you need to replace with your own block contents (using the same block names).
Flask: To use the contents of a block from the html file you are extending, type
{{ super() }}
Flask: Static files should be saved in
A directory called “static” in the same directory as the app.
Flask: An example of a static file that goes in the static directory is
styles.css, javascript, images