4.2. SQLAlchemy Basics (190m) Flashcards
What is SQLAlchemy?
SQLAlchemy is an open-source Python library that provides a set of tools and abstractions for working with relational databases. It serves as an Object-Relational Mapping (ORM) tool, which means it allows you to interact with databases using object-oriented programming concepts.
SQLAlchemy provides a high-level API that allows you to define database models as Python classes, and then perform database operations on those objects without writing raw SQL queries. It abstracts away the differences between different database engines and provides a unified interface to work with various database systems, such as PostgreSQL, MySQL, SQLite, and Oracle.
With SQLAlchemy, you can define tables, columns, and relationships using Python classes and decorators, which closely mirror the structure of your database schema. It supports various data types and allows you to define constraints, indexes, and other database-specific features. SQLAlchemy also provides powerful querying capabilities, allowing you to construct complex database queries using a fluent, expressive syntax.
In addition to the ORM functionality, SQLAlchemy also provides a lower-level SQL expression language that allows you to construct SQL queries programmatically, providing a more flexible approach when needed.
Overall, SQLAlchemy simplifies the process of working with databases in Python by providing an intuitive and powerful toolkit for interacting with relational databases, making it easier to manage and manipulate data within your applications.
What does this do (inside terminal)?
~~~
python3 -m venv env
~~~
The command python3 -m venv env
is used to create a virtual environment in Python.
A virtual environment is an isolated Python environment that allows you to install packages and dependencies specific to a project, without interfering with the global Python environment or other projects. It helps to keep your project’s dependencies separate and ensures that each project can have its own set of packages and versions.
Here’s a breakdown of the command:
-
python3
: This is the command to invoke the Python interpreter. Depending on your system configuration, you may need to usepython
instead ofpython3
. -
-m venv
: This part of the command tells Python to run thevenv
module as a script. Thevenv
module is a built-in module in Python 3 that provides support for creating virtual environments. -
env
: This is the name of the directory where the virtual environment will be created. You can choose any name you like, butenv
is a common convention. You can replace it with a different name if desired.
When you run python3 -m venv env
, it will create a new directory called env
(or the name you provided) in the current directory. This directory will contain a self-contained Python environment with its own copy of the Python interpreter, pip (the package installer), and other necessary files.
To activate the virtual environment, you can use the following command:
- On Unix or Linux:
source env/bin/activate
- On Windows:
.\env\Scripts\activate.bat
After activating the virtual environment, any Python packages you install using pip
will be installed within the virtual environment, isolated from the global Python environment. This helps in managing project dependencies and keeping them separate from other projects you may have on your system.
What does this mean (inside terminal)?.\env\Scripts\activate
in Windows.source ./env/bin/activate
in Mac
The commands .\env\Scripts\activate
in Windows and source ./env/bin/activate
in macOS (or Linux/Unix) are used to activate a virtual environment created using the venv
module in Python.
When you create a virtual environment using python3 -m venv env
, it generates a set of scripts in the env
directory that enable you to activate and deactivate the virtual environment.
In Windows, the activation script is located at env\Scripts\activate.bat
. To activate the virtual environment, you use the command .\env\Scripts\activate
in the command prompt or PowerShell.
In macOS, Linux, or Unix-based systems, the activation script is located at env/bin/activate
. To activate the virtual environment, you use the command source ./env/bin/activate
in the terminal.
Activating the virtual environment modifies the system’s PATH
environment variable, so that when you run Python or pip
commands, they refer to the Python interpreter and packages installed within the virtual environment. This ensures that any packages you install or execute are isolated within the virtual environment, separate from the global Python environment or other virtual environments you may have.
Once the virtual environment is activated, you will typically see the name of the virtual environment in the command prompt or terminal prompt, indicating that you are working within the activated virtual environment.
What does this do inside terminal?
~~~
pip install sqlachemy
~~~
Inside the terminal, the command pip install sqlalchemy
is used to install the SQLAlchemy package via the pip package manager in Python.
When you execute the command pip install sqlalchemy
, it connects to the Python Package Index (PyPI), retrieves the latest version of the SQLAlchemy package, and installs it into your Python environment.
Here’s a breakdown of what happens when you run the command:
- The terminal or command prompt launches the pip package manager, which is a tool used to install and manage Python packages.
- The command
install
is passed as an argument to pip, indicating that you want to install a package. -
sqlalchemy
is provided as the package name. This tells pip to fetch the SQLAlchemy package from the PyPI repository. - Pip checks the installed packages and their dependencies to determine if SQLAlchemy requires any additional packages. If necessary, it automatically installs any missing dependencies.
- Pip proceeds to download the SQLAlchemy package and its dependencies from PyPI.
- Once the download is complete, pip installs SQLAlchemy and any required dependencies into your Python environment.
After the installation is finished, you can start using SQLAlchemy in your Python projects. You can import the SQLAlchemy module in your code and utilize its features for interacting with relational databases using an object-oriented approach.
Note that the success of the installation depends on your system’s configuration and network connectivity. It’s also recommended to run the command with appropriate permissions (e.g., using sudo on Linux or macOS) if your user account requires administrative privileges to install packages globally.
What does the following do inside terminal?
~~~
pip freeze > requirements.txt
~~~
The command pip freeze > requirements.txt
is used to generate a file named requirements.txt
that lists all the Python packages and their versions installed in your Python environment.
Here’s what happens when you execute this command in the terminal:
- The command
pip freeze
is invoked. It instructs pip to generate a list of installed packages and their versions. - The
>
symbol is a redirection operator that redirects the output of thepip freeze
command to a file. -
requirements.txt
is the name of the file where the output will be saved. If the file does not exist, it will be created. If it already exists, the command will overwrite its contents. - Pip executes the
pip freeze
command and retrieves a list of installed packages and their versions. - The output of the
pip freeze
command, which contains the package names and versions, is then written to therequirements.txt
file.
The resulting requirements.txt
file will typically have one line per package, with each line containing the package name followed by the version number in the format package==version
. This file can be used to document the specific package versions required for a project or to recreate the same Python environment on another system.
By convention, the requirements.txt
file is often used in Python projects to specify the project’s dependencies. Other developers or deployment environments can then use this file to install the same packages and versions by running pip install -r requirements.txt
. This ensures consistency across different environments and makes it easier to reproduce the project’s Python environment.
How will you create an ignore GIT file in Visual Code and what kind of text will you add in it?
To create a Git ignore file in Visual Studio Code and specify which files or directories should be ignored by Git, you can follow these steps:
- Open Visual Studio Code and navigate to the root directory of your project.
- Create a new file in the root directory and name it “.gitignore”. Note that the file name starts with a dot.
- Open the “.gitignore” file in the editor.
- Inside the file, you can add specific file names, file patterns, or directory names that you want Git to ignore. Each entry should be on a new line.Here’s an example of what you might include in a
.gitignore
file:```plaintext
# Ignore files generated by the operating system
.DS_Store# Ignore the virtual environment foldervenv/# Ignore log files*.log# Ignore compiled Python files*.pyc
*.pyo# Ignore cache or temporary files__pycache__/# Ignore sensitive or private informationsecret.txt
credentials.json
```In the example above, the.gitignore
file is configured to ignore the following:
- The.DS_Store
file typically created by macOS.
- Thevenv/
folder, which might contain the virtual environment.
- Any log files ending with.log
.
- Compiled Python files ending with.pyc
or.pyo
.
- The\_\_pycache\_\_/
directory created by Python.
- Specific sensitive or private files such assecret.txt
orcredentials.json
.You can customize the.gitignore
file based on the needs of your project. Consider excluding any files or directories that don’t need to be tracked by Git, such as build artifacts, temporary files, and personal configuration files. - Save the
.gitignore
file.
Once you’ve created and saved the .gitignore
file, Git will recognize it and automatically ignore the specified files and directories when tracking changes or staging files for commits. This helps keep your repository clean and avoids including unnecessary files or sensitive information.
Example:
.gitignore:
~~~
env
.vscode
.DS_Store
~~~
What does the following do in terminal?
~~~
python3
import sqlalchemy
sqlalchemy.__version__
~~~
The commands you provided are executed in the terminal to interact with the Python interpreter and check the version of the SQLAlchemy package. Here’s what each command does:
-
python3
: This command starts the Python interpreter in the terminal. It launches an interactive session where you can execute Python code. -
import sqlalchemy
: Once the Python interpreter is running, you use theimport
statement to import the SQLAlchemy package. This makes the SQLAlchemy module and its functionality available for use in the Python session. -
sqlalchemy.\_\_version\_\_
: After importing SQLAlchemy, this command retrieves the version of the SQLAlchemy package.sqlalchemy.\_\_version\_\_
is an attribute that holds the version information of the installed SQLAlchemy package.
By executing these commands in the terminal, you will launch the Python interpreter, import the SQLAlchemy package, and then retrieve and display the version of SQLAlchemy installed in your Python environment.
Note that the command python3
assumes that python3
is the command used to invoke the Python 3 interpreter on your system. Depending on your system’s configuration, you may need to use python
instead of python3
.
How will you setup SQLAlchemy?
Here are the local setup steps you can follow, with the code commands highlighted:
Local Setup Steps:
- 1.Create a folder for your project
- Create a directory where you want to keep your project files.
- 2.Open your folder in your IDE
- Open your preferred Integrated Development Environment (IDE) or code editor.
- Use the IDE’s file menu or command prompt to navigate to the project folder you created.
- 3.Open the terminal in your IDE
- In your IDE, locate the terminal or command prompt window.
- Open the terminal within your IDE to execute commands directly.
- 4.Install virtual environment
- For Mac:
python3 -m pip install --user virtualenv
- For Windows:
py -m pip install --user virtualenv
- For Mac:
- 5.Create a virtual environment
- For Mac:
python3 -m venv env
- For Windows:
python -m venv env
- For Mac:
- 6.Activate your environment
- For Mac:
source ./env/bin/activate
- For Windows:
.\env\Scripts\activate
- For Mac:
- 7.Install SQLAlchemy
pip install sqlalchemy
- 8.Create a requirements file
pip freeze > requirements.txt
Following these steps will help you set up your local development environment with a virtual environment, install SQLAlchemy, and create a requirements file.
Remember to adjust the commands based on your system’s configuration and use the appropriate Python command (python
or python3
) depending on how your system is set up.
What does the following code mean?
~~~
from sqlalchemy import create_engine()
engine = create_engine(‘sqlite:///users.db’, echo=True)
~~~
The code you provided demonstrates the usage of SQLAlchemy to create a database engine connected to a SQLite database. Here’s a breakdown of the code:
-
from sqlalchemy import create_engine()
: This line imports thecreate_engine
function from the SQLAlchemy library. Thecreate_engine
function is responsible for creating a database engine, which acts as the interface between SQLAlchemy and the database system. -
engine = create_engine('sqlite:///users.db', echo=True)
: This line creates an engine object using thecreate_engine
function. The engine is configured to connect to a SQLite database stored in the fileusers.db
.-
sqlite:///users.db
: This is the connection URL for SQLite, specifying the file path to the SQLite database. In this case, it connects tousers.db
in the current directory. -
echo=True
: This parameter enables logging and sets the echo flag toTrue
. Withecho=True
, SQLAlchemy will print the SQL statements it generates and executes, which can be useful for debugging and understanding the database operations being performed.
-
After executing this code, the engine
object represents a connection to the SQLite database specified by the URL. The engine can be used to interact with the database, including creating tables, executing SQL queries, and performing other database operations.
It’s worth noting that this code snippet demonstrates how to connect to a SQLite database specifically. If you want to connect to a different database system, such as MySQL or PostgreSQL, you would need to adjust the connection URL and potentially install additional database-specific SQLAlchemy dialects.
Explain the following code:
~~~
from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.orm import declarative_base
from sqlalchemy.ext.declarative import declarative_base
# As of SQLAlchemy version 1.4, declarative_base() should now be imported from the sqlalchemy.orm package instead of the declarative.ext package.
engine = create_engine(‘sqlite:///users.db’, echo=True)
Base = declarative_base()
class User(Base):
__tablename__ = ‘users’
id = Column(Integer, primary_key=True) name = Column(String) fullname = Column(String) nickname = Column(String) def \_\_repr\_\_(self): return f'<User(name={self.name}, fullname={self.fullname}, nickname={self.nickname})>'
if __name__ == “__main__”:
Base.metadata.create_all(engine)
~~~
Certainly! Here’s a line-by-line explanation of the code with complete details:
```python
from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.orm import declarative_base
~~~
- The sqlalchemy
library is imported.
- create_engine, Column, Integer, String
are specific components being imported from sqlalchemy
. These components will be used in the script.
- declarative_base
is imported from the sqlalchemy.orm
module. This function will be used to create a base class for declarative models.
```python
engine = create_engine(‘sqlite:///users.db’, echo=True)
~~~
- A database engine is created using the create_engine
function from SQLAlchemy.
- 'sqlite:///users.db'
is the connection URL for a SQLite database named users.db
.
- The echo=True
argument enables logging, causing SQLAlchemy to print the SQL statements it generates and executes.
```python
Base = declarative_base()
~~~
- declarative_base()
function is called to create a base class for declarative models.
- The Base
variable will be used as the superclass for all model classes defined in the script.
```python
class User(Base):
__tablename__ = ‘users’
id = Column(Integer, primary_key=True) name = Column(String) fullname = Column(String) nickname = Column(String) def \_\_repr\_\_(self): return f'<User(name={self.name}, fullname={self.fullname}, nickname={self.nickname})>' ~~~ - A model class named `User` is defined, inheriting from the `Base` class. - `\_\_tablename\_\_ = 'users'` specifies the table name as `'users'` for the `User` model class. - `id`, `name`, `fullname`, and `nickname` are defined as class attributes using the `Column` function. These attributes represent the columns in the `users` table. - `id = Column(Integer, primary_key=True)` defines the `id` column as an `Integer` type and specifies it as the primary key of the table. - `name`, `fullname`, and `nickname` are defined similarly as `String` columns. - The `\_\_repr\_\_` method is defined to provide a string representation of a `User` object. It returns a formatted string that includes the values of the `name`, `fullname`, and `nickname` attributes.
```python
if __name__ == “__main__”:
Base.metadata.create_all(engine)
~~~
- The code block within the if \_\_name\_\_ == "\_\_main\_\_":
statement ensures that the following code is only executed when the script is run directly, not when imported as a module.
- Base.metadata.create_all(engine)
is called to create the database table(s) based on the defined model classes. It utilizes the engine
object to establish a connection to the SQLite database and create the necessary table(s) if they don’t already exist.
Executing this script will create the users
table in the SQLite database specified by the connection URL. The table will have columns corresponding to the defined model attributes (id
, name
, fullname
, nickname
).
Challenge 1: You’re creating the model for a movie theater’s movie database. First, import create_engine
and declarative_base
correctly from SQLAlchemy.
Challenge 2: Now it’s time to put those imports to work. Create a variable called engine and set it equal to create_engine
. Use create_engine
to create a SQLite database called movies.db
and set echo to False. Next, create a variable named Base and set it equal to declarative_base
. Then create the model class. It should be called Movie
, and it takes Base
as an argument (it inherits from Base). Inside of the class, set the \_\_tablename\_\_
to ’movies’
.
Challenge 3: Finally, your table needs some columns. Add Column
, Integer
, and String
to your sqlalchemy imports. Create an id
column that holds numbers and is a primary key. Create two more columns called movie_title
and genre
. Both columns hold strings.
Answer to Challenge 1:
~~~
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
~~~
Answer to Challenge 2:
~~~
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
engine = create_engine(‘sqlite:///movies.db’, echo=False)
Base = declarative_base()
class Movie(Base):
__tablename__ = ‘movies’
~~~
Answer to Challenge 3:
~~~
from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
engine = create_engine(‘sqlite:///movies.db’, echo=False)
Base = declarative_base()
class Movie(Base):
__tablename__ = ‘movies’
id = Column(Integer, primary_key=True) movie_title = Column(String) genre = Column(String) ~~~
Explanation:
Certainly! Here’s a line-by-line explanation of the code:
```python
from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
~~~
- The sqlalchemy
library is imported.
- create_engine
, Column
, Integer
, and String
are specific components being imported from sqlalchemy
. These components will be used in the script.
- declarative_base
is imported from the sqlalchemy.ext.declarative
module. This function will be used to create a base class for declarative models.
```python
engine = create_engine(‘sqlite:///movies.db’, echo=False)
~~~
- A database engine is created using the create_engine
function from SQLAlchemy.
- 'sqlite:///movies.db'
is the connection URL for a SQLite database named movies.db
.
- The echo=False
argument disables logging, so SQLAlchemy will not print the SQL statements it generates and executes.
```python
Base = declarative_base()
~~~
- The declarative_base()
function is called to create a base class for declarative models.
- The Base
variable will be used as the superclass for all model classes defined in the script.
```python
class Movie(Base):
__tablename__ = ‘movies’
id = Column(Integer, primary_key=True) movie_title = Column(String) genre = Column(String) ~~~ - A model class named `Movie` is defined, inheriting from the `Base` class. - `\_\_tablename\_\_ = 'movies'` specifies the table name as `'movies'` for the `Movie` model class. - `id`, `movie_title`, and `genre` are defined as class attributes using the `Column` function. These attributes represent the columns in the `movies` table. - `id = Column(Integer, primary_key=True)` defines the `id` column as an `Integer` type and specifies it as the primary key of the table. - `movie_title` and `genre` are defined as `String` columns.
Overall, this code sets up SQLAlchemy for a SQLite database named movies.db
and defines a Movie
class representing the structure of the movies
table. The Movie
class inherits from the Base
class, and its attributes correspond to the columns in the table.
Explain the following code, in this explain sessionmaker and how meg_user is created, added in sequence:
from sqlalchemy import create_engine, Column, Integer, String from sqlalchemy.orm import declarative_base from sqlalchemy.orm import sessionmaker engine = create_engine('sqlite:///users.db', echo=False) Session = sessionmaker(bind=engine) session = Session() Base = declarative_base() class User(Base): \_\_tablename\_\_ = 'users' id = Column(Integer, primary_key=True) name = Column(String) fullname = Column(String) nickname = Column(String) def \_\_repr\_\_(self): return f'<User(name={self.name}, fullname={self.fullname}, nickname={self.nickname})>' if \_\_name\_\_ == "\_\_main\_\_": Base.metadata.create_all(engine) meg_user = User(name = 'Megan', fullname = 'Megan Amendola', nickname = 'Meg') print(meg_user.name) print(meg_user.id) session.add(meg_user) print(session.new) session.commit() print(meg_user.id)
This code snippet demonstrates the use of SQLAlchemy, a popular Object-Relational Mapping (ORM) library in Python, to create a SQLite database, define a table structure, and perform basic database operations.
Let’s go through the code step by step:
- The
create_engine
function from SQLAlchemy is used to create an engine object that represents the database connection. In this case, it creates a connection to a SQLite database file named “users.db” and setsecho
toFalse
to disable the SQL output. - The
sessionmaker
function from SQLAlchemy’s ORM module is used to create a Session class. This class will serve as a factory for individual session objects, which will be used to interact with the database. Thebind
parameter is set to the previously created engine, indicating that the session objects will be associated with that database connection. - An instance of the
Session
class is created, which represents a database session. This session will be used to execute database operations. - The
declarative_base
function from SQLAlchemy is called to create a base class for the declarative system. This base class will be used to define ORM classes that will be mapped to database tables. - The
User
class is defined, inheriting from theBase
class. This class represents the table structure and mapping for the “users” table. The\_\_tablename\_\_
attribute specifies the table name in the database. The class has four attributes:id
,name
,fullname
, andnickname
. These attributes are defined asColumn
objects, indicating their respective data types in the database. - The
\_\_repr\_\_
method is overridden to provide a human-readable representation of aUser
object. - The
if \_\_name\_\_ == "\_\_main\_\_":
block is used to ensure that the code inside it is executed only when the script is run directly, not when it is imported as a module. Within this block, thecreate_all
method ofBase.metadata
is called to create the table in the database based on the defined structure. In this case, it creates the “users” table. - An instance of the
User
class is created with the name, fullname, and nickname attributes set to specific values. This instance represents a new user, “Megan Amendola” with the nickname “Meg”. - The
name
attribute ofmeg_user
is printed, which outputs “Megan” to the console. - The
id
attribute ofmeg_user
is printed. Since this is a new user that has not been committed to the database yet, theid
attribute will still beNone
. - The
add
method of the session is called, passingmeg_user
as an argument. This adds themeg_user
object to the session’s pending list of changes. - The
new
attribute of the session is printed, which outputs[meg_user]
to the console. This indicates that there is one pending change in the session, represented by themeg_user
object. - The
commit
method of the session is called, which persists all pending changes to the database. In this case, it inserts themeg_user
object as a new row in the “users” table. - The
id
attribute ofmeg_user
is printed again. Since the user has been committed to the database, theid
attribute will now hold the auto-generated primary key value assigned by the database.
Overall, this code sets up a database connection, defines a table structure using SQLAlchemy’s ORM, creates a new user object, adds it to a session, commits the changes to the database, and
retrieves the auto-generated primary key assigned to the user after insertion.
What does the following command do in terminal?
sqlite3 users.db
in Macsqlite3.exe users.db
in Windows
What does the following sequence of code will do?
sqlite3 users.db .tables Select * FROM users; .exit
The command sqlite3 users.db
in Mac and sqlite3.exe users.db
in Windows are similar but are specific to the respective operating systems.
In both cases, the command launches the SQLite command-line shell, which provides an interactive environment for working with SQLite databases. The users.db
argument specifies the path to the SQLite database file that you want to open.
Once the SQLite shell is launched, you can enter various SQL commands to interact with the database file. For example, you can create tables, insert data, query data, update records, delete records, and perform other database operations using SQLite’s SQL syntax.
The specific differences between running sqlite3 users.db
on Mac and sqlite3.exe users.db
on Windows are related to the file paths and the executable name. The .exe
extension is used in Windows to denote an executable file, while it is not necessary in Mac or Unix-like systems. The sqlite3
command is typically available in the command line in both operating systems, but the executable name may vary depending on the system configuration and the location of the SQLite installation.
The sequence of commands you provided assumes that you are running the SQLite command-line shell (sqlite3
or sqlite3.exe
) in the terminal and that you are working with a SQLite database file named “users.db”.
Let’s break down the sequence step by step:
-
sqlite3 users.db
: This command launches the SQLite command-line shell and opens the “users.db” database file. It provides an interactive environment where you can execute SQL commands on the specified database. -
.tables
: Once you are in the SQLite command-line shell, entering the.tables
command will list all the tables in the currently opened database (“users.db”). This command will display the names of all the tables available in the database. -
Select * FROM users;
: This SQL query is used to retrieve all the rows and columns from the “users” table in the database. By executing this command, you will see the result set containing the data stored in the “users” table. The*
symbol inSELECT *
indicates that all columns should be selected, andusers
is the name of the table you want to query.
Overall, this sequence of code launches the SQLite command-line shell, opens the “users.db” database file, lists the tables available in the database, and performs a select query to retrieve all the data from the “users” table.
Explain the following code:
from sqlalchemy import create_engine, Column, Integer, String from sqlalchemy.orm import declarative_base from sqlalchemy.orm import sessionmaker engine = create_engine('sqlite:///users.db', echo=False) Session = sessionmaker(bind=engine) session = Session() Base = declarative_base() class User(Base): \_\_tablename\_\_ = 'users' id = Column(Integer, primary_key=True) name = Column(String) fullname = Column(String) nickname = Column(String) def \_\_repr\_\_(self): return f'<User(name={self.name}, fullname={self.fullname}, nickname={self.nickname})>' if \_\_name\_\_ == "\_\_main\_\_": Base.metadata.create_all(engine) # meg_user = User(name = 'Megan', fullname = 'Megan Amendola', nickname = 'Meg') # print(meg_user.name) # print(meg_user.id) # session.add(meg_user) # print(session.new) # session.commit() # print(meg_user.id) new_users = [ User(name='Grace', fullname='Grace Hopper', nickname='Pioneer'), User(name='Alan', fullname='Alan Turing', nickname='Computer Scientist'), User(name='Katherine', fullname='Katherine Johnson', nickname='') ] session.add_all(new_users) session.commit() for user in new_users: print(user.id)
This code snippet demonstrates the use of SQLAlchemy, a Python ORM library, to define a database schema, create an engine to connect to a SQLite database, and perform database operations.
Let’s go through the code step by step:
- The code imports necessary modules from SQLAlchemy:
create_engine
,Column
,Integer
,String
,declarative_base
, andsessionmaker
. These modules provide the necessary functionality to interact with the database. - The
create_engine
function is called with the argument'sqlite:///users.db'
to create an engine object. This object represents the connection to the SQLite database named “users.db”. Theecho
parameter is set toFalse
to disable the SQL output. - The
sessionmaker
function is called with the argumentbind=engine
to create a Session class. This class acts as a factory for individual session objects, which are used to interact with the database. The session objects created from this class will be bound to the engine created in the previous step. - An instance of the
Session
class is created, representing a database session. This session will be used to execute database operations. - The
declarative_base
function is called to create a base class,Base
, for the declarative system. This base class will be used to define ORM classes that will be mapped to database tables. - The
User
class is defined, inheriting from theBase
class. This class represents the table structure and mapping for the “users” table. The\_\_tablename\_\_
attribute specifies the name of the table in the database. The class has four attributes:id
,name
,fullname
, andnickname
. These attributes are defined asColumn
objects, indicating their respective data types in the database. - The
\_\_repr\_\_
method is overridden to provide a human-readable representation of aUser
object. - The code checks if the script is being run directly by using the
if \_\_name\_\_ == "\_\_main\_\_":
block. This ensures that the following code is only executed when the script is run directly, not when it is imported as a module. -
Base.metadata.create_all(engine)
is called within theif \_\_name\_\_ == "\_\_main\_\_":
block. This command creates the table structure in the database based on the defined ORM classes. In this case, it creates the “users” table in the “users.db” database. - A list
new_users
is created, containing threeUser
objects with different values for thename
,fullname
, andnickname
attributes. These objects represent new users to be added to the database. -
session.add_all(new_users)
is called to add all the objects innew_users
to the session’s pending list of changes. -
session.commit()
is called to persist the pending changes to the database. This operation inserts the new users into the “users” table. - A loop is used to iterate over the
new_users
list, and for each user, theid
attribute is printed. Since the users have been committed to the database, theid
attribute will hold the auto-generated primary key values assigned by the database.
Overall, this code sets up the database connection, defines a table structure using SQLAlchemy’s ORM, adds multiple new user objects to a session, commits the changes to the database, and prints the auto-generated primary key values assigned to the new users after insertion.
How to import declarative_base
in Python with SQLAlchemy?
To import the declarative_base
function from SQLAlchemy, you have two options:
Option 1: Importing from sqlalchemy.ext.declarative
:
```python
from sqlalchemy.ext.declarative import declarative_base
~~~
Option 2: Importing from sqlalchemy.orm
:
```python
from sqlalchemy.orm import declarative_base
~~~
Both import statements bring in the declarative_base
function from the respective modules. The declarative_base
function is used to create a base class for declarative SQLAlchemy models. This base class serves as a foundation for defining ORM classes that will be mapped to database tables.
Once imported, you can use the declarative_base
function to create the base class for your declarative models. Here’s an example:
```python
from sqlalchemy import Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
class User(Base):
__tablename__ = ‘users’
id = Column(Integer, primary_key=True) name = Column(String) email = Column(String) ~~~
In this example, we import declarative_base
from either sqlalchemy.ext.declarative
or sqlalchemy.orm
and create the Base
class using the declarative_base()
function. Then, we define a User
class that inherits from Base
, indicating that it is a declarative model. The User
class represents a table named ‘users’ with three columns: id
, name
, and email
.
Both options achieve the same result, and the choice between them depends on personal preference or the specific import style used in your codebase.