Basics of Flask Flashcards

1
Q

Flask-WTF what is it used for?

A

Is used to render and validate web forms in a safe and flexible way in Flask.

It deliver CSRF protection and data validation.

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

Flask what is it used for?

A

when we install e.g Flask == 0.10.1 we need it for managing the request / response cycle

In general, Flask is a web framework that provides you with tools, libraries and technologies that allow you to build a web application.

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

Flask-SQLAlchemy what is it used for?

A

Is for database connection pooling and object / relational mapper

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

ORM

A

Object–relational mapping - technique for converting data between a relational database and object-oriented programming language. Flask-SQLAlchemy is an example of object/relational mapper.

Object-Relational Mapping (ORM) is a technique that lets you query and manipulates data from a database using an object-oriented paradigm. An ORM library is a completely ordinary library written in your language of choice that encapsulates the code needed to manipulate the data, so you don’t use SQL anymore, you interact directly with an object in the same language you’re using.

Flask-SQLAlchemy is an extension for Flask that adds support for SQLAlchemy to your application.

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

In the main python file of your app, you’ll see information like this:

_cwd = dirname(abspath(__file__))

SECRET_KEY = ‘flask-session-insecure-secret-key’
SQLALCHEMY_DATABASE_URI = ‘sqlite:///’ + join(_cwd, ‘flask-tracking.db’)
SQLALCHEMY_ECHO = True
WTF_CSRF_SECRET_KEY = ‘this-is-not-random-but-it-should-be’

app = Flask(__name__)
app.config.from_object(__name__)

db = SQLAlchemy(app)

what do these lines mean?

A

SECRET_KEY = is used to sign session cookies for protection against cookie data tampering. It’s very important that an attacker doesn’t know the value of this secret key.

SQLALCHEMY_DATABASE_URI = is the path to our database (we are using SQLite)

WTF_CSRF_SECRET_KEY = is used to sign WTForms’ CSRF tokens.

app = Flask(__name__)
app.config.from_object(__name__)

Above initialize a new Flask application and tell it to configure itself (with our app.config.from_object call)

db = SQLAlchemy(app) here we initialize our Flask-SQLAlchemy extension with our application.

Podsumowując:
aby startując aplikację we Flasku musimy:
- ją zanicjować app = Flask(__name__),

  • wskazać na bazę danych jakiej będziemy używać (np. SQLAlchemy),
  • podać ścieżkędla tej bazy w naszym projekcie

oraz

  • podać SECRET_KEY do podpisywania sesji ciasteczek (ochrona przed ich zewnętrzną manipulacją)

a także
- podać WTF_SECRET_KEY dla formularzy internetowych, które będziemy chcieli bezpiecznie renderować w naszej aplikacji.

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

CSRF

A

Cross-Site Request Forgery (fałszowanie żądań HTTP między stronami)

A CSRF attack forces a logged-on victim’s browser to send a forged HTTP request, including the victim’s session cookie and any other automatically included authentication information, to a vulnerable web application. This allows the attacker to force the victim’s browser to generate requests the vulnerable application thinks are legitimate requests from the victim.

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

Oprócz głownego pliku zawierającego konfigurację naszej aplikacji (
inicjację aplikacji app = Flask(__name__), SECRET_KEY dla cookies session, wskazanie bazy danych i jej ścieżk oraz secret key dla WTF Forms
)
musimy również stworzyć (wymień 3 pliki konieczne dla działania aplikacji)

A
  1. models.py
    Model to klasa reprezentująca tabelę w bazie danych, w której każdy atrybut klasy jest polem tej tabeli.
  2. forms.py
    plik z formularzami służy do pobierania danych od użytkownika w odpowiednim formacie (tak aby te dane można było wpisać potem do tabeli)

Formularz jest podstawowym elementem umożliwiającym interakcję użytkownika z naszą aplikacją internetową. Formularze operują na klasach, których instancje to wpisy od użytkowników.

  1. routes.py
    tutaj znajdują się endpointy (końcówki adresów) dostępne w naszej aplikacji
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

In the following example of creating a model in Flask:

Please translate for human this snippet line by line:

from flask import Flask
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config[‘SQLALCHEMY_DATABASE_URI’]=’mysql://root:root@localhost/demo’
db = SQLAlchemy(app)

class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(80), unique=True, nullable=False)
email = db.Column(db.String(120), unique=True, nullable=False)

def \_\_repr\_\_(self):
    return '<User %r>' % self.usern
A

Importujemy Flask oraz Flask SQL Alchemy

Inicjujemy aplikację + określamy jej konfigurację. Wskazujemy też, że baza danych to będzie SQL

Tworzymy klasę definiującą model:
class User(db.Model):

Klasa reprezentuje tabelę, w której każde pole to atrybut tej klasy.

Określamy jak mają wyglądać pola tej tabeli:
db.Column - definiuje jakie mamy mieć kolumny w tej tabeli, tu mamy takie kolumny jak id, username

db.Integer, db.String - deginiuje jakiego typu dane będą storowane w tej tabeli np. w kolumnę id będziemy wpisywać integery, a w kolumnę username będziemy wpisywać stringi

primary_key=True każdy kolejny rekord w tabeli ma swój unikatowy identyfikator

unique=True nie możemy wpisywać kilka razy tych samych dany

nullable=True oznacza, że kolumna może pozostać pusta

W modelach możemy deklarować parent, child tables oraz deklarować relacje pomiędzy różnymi tabelami np. One-to-Many Relationships

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

Jinja

A

is an template engine that allows data to be passed between backend and frontend

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

What is a development server? This kind of server is is available in Flask.

A

Flask provides a run command to run the application with a development server. In debug mode, this server provides an interactive debugger and will reload when code is changed. Warning. Do not use the development server when deploying to production.

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

Flask support secure cookies. Why?

A

because cookies are essentially trackers that remember use user information

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

The first step to every flask application is to import the _______

The next step is to create ______

Then we can finish, the app by defining route of our website. We use _____ decorator to do this

A

odp1 flask class,
from flask import Flask

odp 2 an instance of the Flask class,
app = Flask(__name__)

odp 3 @app.route decorator,
@app.route(“/”):
def hello_world():
return “Hello world. This is my app”

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

What if statement should be at the end of the main app file (necessary for the app to run)?

A

if __name__ == “ __main__”:
app.run(host=”0.0.0.0”, debug=True)

This is basically just saying, if this app is inside the main directory (if __name__ == “ __main__”)

Then we run the app (app.run()) with some variables:
- host default value for address
eg. in this case we will run our website on local host http://0.0.0.0.5000
- debug= True (debugging refreshes the server for you whenever you make the change.
So you wouldn’t have to stop the server, save the file, restart your server just to see any changes)

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

How to add a variable section to a URL of your Flask application?

A

by using <> brackets for your variable
e.g

@app.route(“/user/<username>")
def user(username):
return f"Welcome user "</username>

to do this we need to import :

from, markupsafe import escape

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

Web applications use different _____ _________ when accessing URL

A

HTTP methods

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

By default a route only answers _____ _________

A

GET methods

17
Q

To handle different HTTP methods in your app pass them as _____

A

argument to your @app.route function
e.g
from flask import request

@app.route(“/login”, methods=[“GET”, “POST”])
def login():
if request.method == “POST”
return do_the_login()
else:
return show_the_login_form()

18
Q

Flask application usually contains static files that contains ____

A

images and/or style files for your application

19
Q

To generate URLs for static files use _______ ____________ _______

A

the static endpoint name
e.g

url_for(“static”, filename=”style.css”)

20
Q

To render a HTML you can use ____ flask method

A

render_template()
e.g

from flask import render_template

@app.route(“/hello”)
@app.route(“/hello/<name>")
def hello (name=None):
return render_template("hello.html", name=name)</name>

21
Q

In order for Flask to recognise your HTML files you have to store them in _________ ________

A

template directory

22
Q

You can use request.form to _________________

A

collect data from POST on a page. You can store this data in variable and put from Python to HTML file in a future use:

@app.route(“/login”, methods=[“POST”, “GET”])
def login():
error = None
if request.method == “POST”:
if valid_login(request.form[“username”], request.form[“password”]):
return log_the_user_in(request.form[“username”])
else: error. = “Invalid username/password”
return render_template(“login.html”, error=error

23
Q

You can store files uploaded by user in the temporary file o the web server. Each file is stored as ______

A

dictionary

24
Q

To save files uploaded by user, you need to use _____ ___________

A

f.save function
e.g

@app.route (“/upload”, methods = [“GET”, “POST”])
def upload_file():
if request.method == “POST”:
f = request.files[“the_fille”]
f.save (“/var/www/uploads/uploaded_file.txt”)*

here we change name of the user file from “the_file” for “uploaded_file.txt”

To store file under username name you will have to use Werkzeug library’s secure_filename() method

25
Q

To redirect a user from one endpoint to another you can use ___________

A

redirect() function
e.g

from flask import abort, redirect, url_for

@app.route(“/”)
def index():
return redirect(url_for(“login”))

26
Q

url_for() function

A

The url_for() function is used to build a URL to the specific function dynamically.

It accepts the name of the function which url it wants to provide and redirect to.Besides this, it optionally it accepts any number of keyword arguments, each corresponding to a variable part of the URL rule

e.g

from flask import Flask, url_for
from markupsafe import escape

app = Flask(__name__)

@app.route(‘/’)
def index():
return ‘index’

@app.route(‘/login’)
def login():
return ‘login’

@app.route(‘/user/<username>')
def profile(username):
return '{}\'s profile'.format(escape(username))</username>

with app.test_request_context():
print(url_for(‘index’))
print(url_for(‘login’))
print(url_for(‘login’, next=’/’))
print(url_for(‘profile’, username=’John Doe’))

> /
/login
/login?next=/
/user/John%20Doe

27
Q

If you want to customize your error page, you can user the ________

A

@app.errorhandler decorator

e.g
@app.errorhandler(404)
def page_nor_found(error):
return render_template(“funny_error_ppage.html”), 404

28
Q

To access cookies using Flask you can use _________________ and ________________ methods

A

Reading cookies:

request.cookies.get() and
resp.set_cookie()

Cookies are set on response objects

To access cookies you can use the cookies attribute. To set cookies you can use the set_cookie method of response objects. The cookies attribute of request objects is a dictionary with all the cookies the client transmits.

e.g from flask import request

@app.route(‘/’)
def index():
username = request.cookies.get(‘username’)

from flask import make_response

@app.route(‘/’)
def index():
resp = make_response(render_template(…))
resp.set_cookie(‘username’, ‘the username’)
return resp

29
Q

What are sessions?

A

Sessions allow you to store one information specific to a user from one request to the next.

This is implemented on top of cookies for you and signs the cookies cryptographically. What this means is that the user could look at the contents of your cookie but not modify it, unless they know the secret key used for signing.

Basically, they’re just more advanced and cookies are kind of like the next level or the next step above using just cookies.