Apps Development, Cloud Computing, Data Analytics

3 Mins Read

Empowering Python Developers with an Elegant ORM: SQLAlchemy

Voiced by Amazon Polly

Introduction

A library called SQLAlchemy makes it easier for Python applications and databases to communicate together. This library is typically an Object Relational Mapper (ORM) tool to instantly translate function calls into SQL statements and convert Python classes to tables in relational databases.

With the help of the standard interface SQLAlchemy offers, programmers can write code that can interact with a broad range of database engines, regardless of the database used.

Pioneers in Cloud Consulting & Migration Services

  • Reduced infrastructural costs
  • Accelerated application deployment
Get Started

Creating an Engine

We must build an Engine each time we want to use SQLAlchemy to communicate with a database. On SQLAlchemy, engines handle Pools and Dialects, two important components. These two ideas will be explained in more detail in the following two sections, but for the time being, it is sufficient to know that SQLAlchemy employs them to communicate with DBAPI functions.

We must import and execute the create_engine function from the sqlalchemy library to create an engine and begin working with databases:

In this example, a PostgreSQL engine is created to connect to a local instance operating on port 5432. (the default one). Additionally, it specifies that to access the sqlalchemy database. It will use the user of the password and pass. Building an engine does not immediately establish a connection to the database. When necessary (such as when we submit a query or create/update a row in a table), this procedure is delayed.

Data Types for SQLAlchemy

We can be confident that when using SQLAlchemy, we will receive support for the most prevalent data types found in relational databases. Among the kinds, SQLAlchemy offers abstractions, booleans, dates, times, strings, and numeric values are just a few examples. In addition to these fundamental types, SQLAlchemy supports a few vendor-specific types (such as JSON) and allows developers to build new types and redefine existing ones.

Creating a Table

Let’s examine the following example to see how we can use SQLAlchemy data types to convert Python class properties into fields on a relational database table:

SQLAlchemy is informed by the __tablename__ property that the rows of the products table must be mapped to this class.

By using the engine now that SQA can build tables!

The Book model specification is contained in the metadata of the Base class from which our models inherited it, so to create a table, we execute the create_all method with the engine.

Instead, we would use the drop_all function to delete this table as well as every other table in the database:

This presumes that we, as is typically the case, have an engine in the global realm.

The engine and other database operations are typically located in a file with the name db.py or crud.py, where CRUD stands for Create, Read, Update, and Delete.

Using Session:

Let us create a session object as global

A factory for individual sessions, the global Session object enables us to connect our engine just once and have clear session states whenever we need them. Every time we want to interact with the database, we import Session and create a new s to work with; you’ll see a better way to do this in the last section. Session and engine are typically specified globally at the beginning of the db.py or crud.py.

To free up connections and resources, you must always end the session when you are finished using it.

Inserting Data:

Using our model class this time, we’ll make the same book that we did in the SQLite example:

All we’re doing here is instantiating the class like in Python. You’ll see that passing a DateTime is possible without first converting it to a timestamp. SQA will change the Postgres Date column style to match the Python datetime. Now we are prepared to add a book to the database using the session object.

Basic Querying rows:

The model we want to query is passed to the query function from the session object, which then returns the first() item, which is the only item currently available:

Output:

Conclusion

Most data collection, web scraping, and web application projects are created using SQLAlchemy. One difference is that Flask is usually the web framework of choice in web applications, and SQLAlchemy is paired into the flask-sqlalchemy library. In that case, this library makes projects simple for migrations.

Making IT Networks Enterprise-ready – Cloud Management Services

  • Accelerated cloud migration
  • End-to-end view of the cloud environment
Get Started

About CloudThat

CloudThat is a leading provider of Cloud Training and Consulting services with a global presence in India, the USA, Asia, Europe, and Africa. Specializing in AWS, Microsoft Azure, GCP, VMware, Databricks, and more, the company serves mid-market and enterprise clients, offering comprehensive expertise in Cloud Migration, Data Platforms, DevOps, IoT, AI/ML, and more.

CloudThat is the first Indian Company to win the prestigious Microsoft Partner 2024 Award and is recognized as a top-tier partner with AWS and Microsoft, including the prestigious ‘Think Big’ partner award from AWS and the Microsoft Superstars FY 2023 award in Asia & India. Having trained 850k+ professionals in 600+ cloud certifications and completed 500+ consulting projects globally, CloudThat is an official AWS Advanced Consulting Partner, Microsoft Gold Partner, AWS Training PartnerAWS Migration PartnerAWS Data and Analytics PartnerAWS DevOps Competency PartnerAWS GenAI Competency PartnerAmazon QuickSight Service Delivery PartnerAmazon EKS Service Delivery Partner AWS Microsoft Workload PartnersAmazon EC2 Service Delivery PartnerAmazon ECS Service Delivery PartnerAWS Glue Service Delivery PartnerAmazon Redshift Service Delivery PartnerAWS Control Tower Service Delivery PartnerAWS WAF Service Delivery PartnerAmazon CloudFront Service Delivery PartnerAmazon OpenSearch Service Delivery PartnerAWS DMS Service Delivery PartnerAWS Systems Manager Service Delivery PartnerAmazon RDS Service Delivery PartnerAWS CloudFormation Service Delivery PartnerAWS ConfigAmazon EMR and many more.

FAQs

1. How to configure DB login?

ANS: – For any SQLAlchemy program, the Engine serves as the foundation. The SQLAlchemy application receives the real database and its DBAPI from this “home base” via a connection pool and a dialect, which outlines how to communicate with a particular class of database/DBAPI combination.

2. How do I set up a column that contains a reserved term in Python or something similar?

ANS: – In the mapping, column-based attributes can be assigned any name you like.

WRITTEN BY Imraan Pattan

Imraan is a Software Developer working with CloudThat Technologies. He has worked on Python Projects using the Flask framework. He is interested in participating in competitive programming challenges and Hackathons. He loves programming and likes to explore different functionalities for creating backend applications.

Share

Comments

    Click to Comment

Get The Most Out Of Us

Our support doesn't end here. We have monthly newsletters, study guides, practice questions, and more to assist you in upgrading your cloud career. Subscribe to get them all!