0% found this document useful (0 votes)
18 views

Flask Part3

The document discusses SQL and NoSQL databases, Python database frameworks like Flask-SQLAlchemy, model definition, relationships between models, and basic database operations like creating tables, inserting rows, querying, updating and deleting in Flask applications.

Uploaded by

mamu shaik
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views

Flask Part3

The document discusses SQL and NoSQL databases, Python database frameworks like Flask-SQLAlchemy, model definition, relationships between models, and basic database operations like creating tables, inserting rows, querying, updating and deleting in Flask applications.

Uploaded by

mamu shaik
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 31

FLASK

z
DATABASE
2

z
SQL Databases
 Relational databases store data in tables.

 A table has a fixed number of columns and a variable number of rows.

 The columns define the data attributes of the entity represented by the
table.

 Each row in a table defines an actual data element that assigns values to
some or all the columns.

 Tables have a special column called the primary key, which holds a unique
identifier for each row stored in the table.
Faculty: Mrs.M.Lalitha, Assistant Professor, CSE

 Tables can also have columns called foreign keys, which reference the
primary key of a row in the same or another table.
5/27/2023
3

z
NoSQL Databases
 Databases that do not follow the relational are collectively
referred to as NoSQL databases.

 One common organization for NoSQL databases uses


collections instead of tables and documents instead of records.

 NoSQL databases are designed in a way that makes joins


difficult, so most of them do not support this operation at all.
Faculty: Mrs.M.Lalitha, Assistant Professor, CSE

 Example:
5/27/2023
4
Faculty: Mrs.M.Lalitha, Assistant Professor, CSE
5/27/2023
5

z
Python Database Frameworks

 Python has packages for most database engines, both open source and
commercial.

 Flask puts no restrictions on what database packages can be used, so you


can work with MySQL, Postgres, SQLite, Redis, MongoDB, CouchDB, or
DynamoDB.

 There are a number of factors to evaluate when choosing a database


framework:
Faculty: Mrs.M.Lalitha, Assistant Professor, CSE

 Ease of use
 Performance
 Portability
 Flask integration
5/27/2023
6

z
Database Management with Flask-
SQLAlchemy
 Flask-SQLAlchemy is a Flask extension that
simplifies the use of SQLAlchemy inside Flask
applications.

 SQLAlchemy is a powerful relational database


framework that supports several database
backends.
Faculty: Mrs.M.Lalitha, Assistant Professor, CSE

 Like most other extensions, Flask-SQLAlchemy


is installed with pip:

(venv) $ pip install flask-sqlalchemy

 In Flask-SQLAlchemy, a database is specified


5/27/2023

as a URL.
7

z
Model De€
nition

 The term model is used when referring to the persistent entities


used by the application.

 A model is typically a Python class with attributes that match the


columns of a corresponding database table.

 The database instance from Flask-SQLAlchemy provides a base


Faculty: Mrs.M.Lalitha, Assistant Professor, CSE

class for models as well as a set of helper classes and functions


that are used to define their structure.
5/27/2023
8
Faculty: Mrs.M.Lalitha, Assistant Professor, CSE
5/27/2023
9
Faculty: Mrs.M.Lalitha, Assistant Professor, CSE
5/27/2023
10
Faculty: Mrs.M.Lalitha, Assistant Professor, CSE
5/27/2023
11

z
Relationships

 Relational databases establish connections between rows in


different tables through the use of relationships.

 Example w.r.t user-role tables:


Faculty: Mrs.M.Lalitha, Assistant Professor, CSE
5/27/2023
12
Faculty: Mrs.M.Lalitha, Assistant Professor, CSE
5/27/2023
13

z
Database Operations
 the most common data‐ base operations in a shell started with
the flask shell command.

Creating the Tables


 The very first thing to do is to instruct Flask-SQLAlchemy to
create a database based on the model classes.

 The db.create_all() function locates all the subclasses of


Faculty: Mrs.M.Lalitha, Assistant Professor, CSE

db.Model and creates corresponding tables in the database.

 The db.create_all() function will not re-create or update a


database table if it already exists in the database.
5/27/2023
14

z
Inserting Rows

 The following example creates a few roles and users:

 The constructors for models accept initial values for the model
Faculty: Mrs.M.Lalitha, Assistant Professor, CSE

attributes as keyword arguments.

 The id attribute of these new objects is not set explicitly. The


objects exist only on the Python side so far; they have not been
written to the database yet. Because of that, their id values have
5/27/2023

not yet been assigned. So it print none for any id.


15

 Changes to the database are managed through a database


session, which Flask SQLAlchemy provides as db.session.

 To prepare objects to be written to the data‐ base, they must be


added to the session:
Faculty: Mrs.M.Lalitha, Assistant Professor, CSE
5/27/2023
16
 To write the objects to the database, the session needs to be
z committed by calling its commit() method:

 Check the id attributes again after having the data committed to


see that they are now set:
Faculty: Mrs.M.Lalitha, Assistant Professor, CSE

 Database sessions are extremely useful in keeping the database


consistent. The commit operation writes all the objects that were
added to the session atomically.
5/27/2023
17

z
Modifying Rows

 The add() method of the database session can also be used to


update models.

 Example:
Faculty: Mrs.M.Lalitha, Assistant Professor, CSE
5/27/2023
18

z
Deleting Rows

 The database session also has a delete() method.


Faculty: Mrs.M.Lalitha, Assistant Professor, CSE

 Note that deletions, like insertions and updates, are executed


only when the database session is committed.
5/27/2023
19

z
Querying Rows
 Flask-SQLAlchemy makes a query object available in each
model class.

 The most basic query for a model is triggered with the all()
method, which returns the entire contents of the corresponding
table:
Faculty: Mrs.M.Lalitha, Assistant Professor, CSE

 A query object can be configured to issue more specific


database searches through the use of ƒ
filters.
5/27/2023
20
Faculty: Mrs.M.Lalitha, Assistant Professor, CSE
5/27/2023
21
Faculty: Mrs.M.Lalitha, Assistant Professor, CSE
5/27/2023
22

z
Database Use in View Functions

 The database
operations described
in the previous
sections can be used
directly inside view
functions.
Faculty: Mrs.M.Lalitha, Assistant Professor, CSE

 Example:
5/27/2023
23

z
Database Use in View Functions

 The new version of the associated


template is shown in Example.

 This template uses the known


argument to add a second line to
the greeting that is different for
known and new users.
Faculty: Mrs.M.Lalitha, Assistant Professor, CSE
5/27/2023
24 Integration with the Python Shell
 Having to import the database instance and the models each time a shell
z
session is started is tedious work.

 To avoid having to constantly repeat these steps, the flask shell command
can be configured to automatically import these objects.

 To add objects to the import list, a shell context processor must be created
and regis‐ tered with the app.shell_context_processor decorator.

 The flask shell command will import these items auto‐ matically into the shell,
in addition to app, which is imported by default:
Faculty: Mrs.M.Lalitha, Assistant Professor, CSE
5/27/2023
25

z
Database Migrations with Flask-Migrate

 A database migration framework keeps track of changes to a


database schema, allowing incremental changes to be applied.

 Flask applications can use the Flask-Migrate extension, a


lightweight Alembic wrapper that integrates it with the flask
Faculty: Mrs.M.Lalitha, Assistant Professor, CSE

command.
5/27/2023
26
Creating a Migration Repository
z
 To begin, Flask-Migrate must be installed in the virtual environment:

 the extension is initialized:

 To expose the database migration commands, Flask-Migrate adds a flask db


command with several subcommands.
Faculty: Mrs.M.Lalitha, Assistant Professor, CSE
5/27/2023
27

z
Creating a Migration Script
 In Alembic, a database migration is represented by a migration script.

 This script has two functions called upgrade() and downgrade().

 The upgrade() function applies the database changes that are part of the migration.

 The downgrade() function removes them.

 Alembic migrations can be created manually or automatically using the revision and migrate
commands, respectively.

 A manual migration creates a migration skeleton script with empty upgrade() and
Faculty: Mrs.M.Lalitha, Assistant Professor, CSE

downgrade() functions that need to be implemented by the developer.

 An automatic migration attempts to generate the code for the upgrade() and downgrade()
functions by looking for differences between the model definitions and the current state of
the database.
5/27/2023
28

 To make changes to your database schema with Flask-Migrate, the


following procedure needs to be followed:

1. Make the necessary changes to the model classes.

2. Create an automatic migration script with the flask db migrate command.

3. Review the generated script and adjust it so that it accurately represents


the changes that were made to the models.

4. Add the migration script to source control.


Faculty: Mrs.M.Lalitha, Assistant Professor, CSE

5. Apply the migration to the database with the flask db upgrade command.

 The flask db migrate subcommand creates an automatic migration script:


5/27/2023
29

z
Upgrading the Database

 Once a migration script has been reviewed and accepted, it can


be applied to the data‐ base using the flask db upgrade
command:

 For a first migration, this is effectively equivalent to calling


Faculty: Mrs.M.Lalitha, Assistant Professor, CSE

db.create_all(), but in successive migrations the flask db


upgrade command applies updates to the tables without
affecting their contents.
5/27/2023
30

z
Adding More Migrations

 The procedure to introduce a change in the database is similar


to what was done to introduce the first migration:

1. Make the necessary changes in the database models.

2. Generate a migration with the flask db migrate command.

3. Review the generated migration script and correct it if it has any


Faculty: Mrs.M.Lalitha, Assistant Professor, CSE

inaccuracies.

4. Apply the changes to the database with the flask db upgrade


command.
5/27/2023
31

z
 If your last migration has not been committed to source control
yet, you can opt to expand it to incorporate new changes.

 The procedure to expand the last migration script is as follows:

1. Remove the last migration from the database with the flask db
downgrade command (note that this may cause some data to be
lost).

2. Delete the last migration script, which is now orphaned.

3. Generate a new database migration with the flask db migrate


Faculty: Mrs.M.Lalitha, Assistant Professor, CSE

command, which will now include the changes in the migration


script you just removed, plus any other changes you’ve made to the
models.

4. Review and apply the migration script as described previously.


5/27/2023

You might also like