Build Python Web Apps with Flask Flashcards

1
Q

Introduction to Flask

Creating Flask App Object

A

The Python flask module contains all the classes and functions needed for building a Flask app. The Flask class can be imported to create the main application object. It takes the name of the app as an argument.

# Import Flask class
from flask import Flask

Create Flask object
app = Flask(\_\_name\_\_)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Introduction to Flask

Running Flask App

A

A Flask app can be run by exporting the FLASK_APP environment variable and running flask run in the terminal.

$ export FLASK_APP=app.py
$ flask run
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Introduction to Flask

Creating a Route

A

Routes in a Flask app can be created by defining a view function and associating a URL with it using the route() decorator. Routes specify how the Flask app handles requests it receives, such as what to display on the webpage at a certain URL.

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

Output: The text `Hello, World!` is displayed at the URL path '/'
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Introduction to Flask

Returning HTML From Route

A

In a Flask app, HTML can be returned from a view function to be rendered on a webpage. The HTML can be returned as a string.

@app.route('/')
def hello_world():
    return '<h1>Hello, World!</h1>'

Output: The text `Hello, World!` is displayed as a level 1 heading at the URL path '/'
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Introduction to Flask

Variable Rules

A

Responds to /page/1, /page/20, etc.

Variable rules allow a Flask app to respond to dynamic URLs. Variable sections of a URL can be indicated by angular brackets and an optional converter: <converter:variable_name>. These variable parts will then be passed to the view function as arguments.</converter:variable_name>

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Jinja2 Templates and Forms

Flask Templates

A

Flask uses templates to expand the functionality of a web application while maintaining a simple and organized file structure. Templates are enabled using the Jinja2 template engine and allow data to be shared and processed before being turned in to content and sent back to the client.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

render_template Function

A

The render_template() function renders HTML files for display in the web browser using the Jinja2 template engine. Its sole positional argument is the name of the template to be rendered. Keyword arguments can be added to support application variables within the template.

where render_template processes template files in the “templates” directory. The “templates” directory located inside the running application directory.

├── app_dir │ ├── templates │ │ ├── my_template.html │ ├── app.py

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Jinja2 Templates and Forms

Template Variables

A

Template variables are representations of application data that are used inside templates. Created using keyword arguments in render_template, template variables are substituted into a template when using expression delimiters {{ }}

Used in Jinja templates, expression delimiters {{ }} surround expressions such as variables to be identified by the template engine.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Jinja2 Templates and Forms

Template Variable Filters

A

Filters are applied to template variables and perform a small focused action. Filters follow a variable and are separated by the pipe, |, character. This syntax works inside expression {{ }} and statement {% %}delimiters.

More information on filters can be found in the Jinja documentation.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Jinja2 Templates and Forms

Template if Statements

A

{% if condition %} statements are used in templates to control the content that is returned from Flask routes. Content associated with an if statement is enclosed in blocks starting with {% if condition %} and closing with {% endif %}. else and elif can be used with if statements to further control the content.

Statement delimiters {% %} surround control statements such as if and for to be identified by the Jinja 2 template engine.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Jinja2 Templates and Forms

Template for Loops

A

For loops are used in templates to repeat content or iterate through data during Jinja2 template engine processing. For loops are contained inside statement delimiters with the following syntax {% for local_var in iterator %}. Content inside the block is repeated where the block start with the for statement and is closed by {% endfor %}.

Statement delimiters {% %} surround control statements such as if and for to be identified by the Jinja 2 template engine.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

Jinja2 Templates and Forms

Template Inheritance

A

Jinja templates use inheritance to share content from one template across multiple templates.

The block statement is used to identify the location in each file to establish inheritance. In the parent file {% block identifier %} and {% endblock %} are used to identify what line to substitute inherited content. In the child file {% block identifier %} and {% endblock %} surround the content to be substituted.

The extends statement identifies the parent file another template will share content with. Inserted at the top of the child file, {% extends filename %} identifies which parent file to insert the block content into.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

Jinja2 Templates and Forms

Flask Web Forms

A

Flask provides a simple workflow to implement web forms and gather data while ensuring proper form validation. Using the modules WTForms and Flask-WTF, forms can be created using a class structure to create form elements and collect their data through inherited functionality. Requests can be analyzed using Flasks request object.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

Jinja2 Templates and Forms

request Object

A

When it comes to HTML web forms, the Flask request object provides a way to collect data through the client POST request. The data from a form field can be accessed using the field name as a key to the request objects form attribute.

A Flask route must add “POST” to its methods keyword argument. By default methods is set to [“GET”].

## accessing data from "first_name" field

@app.route('/', methods=["GET", "POST"])
def index():
  if len(request.form) > 0:
    name_data =  request.form["first_name"]
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

Jinja2 Templates and Forms

url_for Function

A

The function url_for() is used within a template to navigate a site through the route function names and not the possibly volatile URL strings. Calling url_for() with the route function name as it’s parameter is safer way to indicate routes within templates since URL strings can change based on a sites changing file structure.

The url_for() function needs to be called within expression delimiters {{ }} in order to be processed by the Jinja2 template engine. Keyword arguments can be added to the function call to pass variables to the Flask app route.

<a href="{{ url_for('index') }}">Link To Index</a>

<a href="{{ url_for('another_route', route_var=some_template_var) }}">Another Route With Variable</a>
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

Jinja2 Templates and Forms

FlaskForm Class

A

Inheriting from the FlaskForm class gives an app defined class the functionality such as template representation, gathering data and providing validation. Used in conjunction with WTForm Fields, FlaskForm functionality gives an easy path over how forms are displayed and how valid data is collected within an application. FlaskForm is imported through the flask_wtf module.

The “SECRET_KEY” variable in the Flask application’s configuration must be set in order to enable CSRF protection. This is necessary to create forms using FlaskForm.

from flask import Flask
from flask_wtf import FlaskForm

app = Flask(\_\_name\_\_)
app.config["SECRET_KEY"] = "secret_string"

class MyForm(FlaskForm):
  ## Form elements initialized here
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

Jinja2 Templates and Forms

WTForm Fields

A

WTForm field objects are a simple way to implement web form fields such as text fields and submit buttons. Imported from the wtforms module and initialized inside a FlaskForm subclass, field objects provide the representation and functionality of web form elements. Some common tasks of field objects are label management, field validation and data handling.

Here is a detailed list of WTForm fields and their functionality. Some common fields used are:

  • StringField()
  • SubmitField()
  • TextAreaField()
  • BooleanField()
  • RadioField()
18
Q

Jinja2 Templates and Forms

WTForm Fields

A

WTForm field objects are a simple way to implement web form fields such as text fields and submit buttons. Imported from the wtforms module and initialized inside a FlaskForm subclass, field objects provide the representation and functionality of web form elements. Some common tasks of field objects are label management, field validation and data handling.

Here is a detailed list of WTForm fields and their functionality. Some common fields used are:

  • StringField()
  • SubmitField()
  • TextAreaField()
  • BooleanField()
  • RadioField()
19
Q

Jinja2 Templates and Forms

Form Validation

A

Web form validation is the process of ensuring the correct data is collected by the form before it is sent to the server for processing.

In a web form, validators are used to identify the fields that require specifc data or formats upon submitting the form. This can be as simple as requiring data to be present, to more specific formats such as dates, phone numbers and email addresses. Form field validators can be added to the field’s instantiation and are imported from the wtforms.validators module. Check the WTForms Validators documentation for more information.

The validate_on_submit() function is part of the FlaskForm class and is used with a route to indicate when valid form data has been submitted. This creates an additional branch in the route where data processing can occur.

20
Q

INTRODUCTION TO FLASK-SQLALCHEMY

Flask application with Flask-SQLAlchemy

A
21
Q

Introduction to Flask-SQLAlchemy

Declaring a simple model: Book

A
22
Q

Introduction to Flask-SQLAlchemy

part1: declaring relationships (one-to-many)
图中红线部分,现有两张表,一张Book,一张Reader,book的ID连Review中的book_id,Reader中的id连Review中的reader_id

A
23
Q

Introduction to Flask-SQLAlchemy

Part II: declaring relationships (Foreign keys)

A
24
Q

Introduction to Flask-SQLAlchemy

Putting it all together: initializing the database

A
25
Q

Introduction to Flask-SQLAlchemy

Creating database entries: entities

A
26
Q

Introduction to Flask-SQLAlchemy

Creating database entries: relationships

A
27
Q

DATABASES IN FLASK - READING, UPDATING AND DELETING

Queries: query.all() and query.get()

A
28
Q

DATABASES IN FLASK - READING, UPDATING AND DELETING

Queries: retrieve related objects

A
29
Q

DATABASES IN FLASK - READING, UPDATING AND DELETING

Queries: filtering

A
30
Q

DATABASES IN FLASK - READING, UPDATING AND DELETING

Queries: more advanced filtering

A
31
Q

DATABASES IN FLASK - READING, UPDATING AND DELETING

Session: add and rollback

A
32
Q

DATABASES IN FLASK - READING, UPDATING AND DELETING

Session: updating existing entries

A
33
Q

DATABASES IN FLASK - READING, UPDATING AND DELETING

Session: Removing database entries

A
34
Q

DATABASES IN FLASK - READING, UPDATING AND DELETING

Queries and templates

A
35
Q

INTRODUCTION TO ACCOUNTS

Introduction to Hashing

A
36
Q

INTRODUCTION TO ACCOUNTS

Modeling Accounts w/ SQLAlchemy

A
37
Q

INTRODUCTION TO ACCOUNTS

Signing up with WTForms

A
38
Q

INTRODUCTION TO ACCOUNTS

Login in with Flask

A
39
Q

INTRODUCTION TO ACCOUNTS

Associating User Actions

A
40
Q

INTRODUCTION TO ACCOUNTS

Success and Error Handling

A