Checkout how to create organized python flask project.
I have made pretty good progress in creating APIs using the Python Flask web framework. As we require a database to store the different types of data. Nowadays, we can use the ORM (Object-relational mapping) technique to communicate with the database.
What is ORM?
If you don't know what ORM is, refer to this article for more details: What is an ORM and Why You Should Use it. Here's the short description: Object-relational-mapping is the idea of being able to write queries, even complicated ones, using the object-oriented paradigm of your preferred programming language.
How to use ORM in Python?
In python, you can use SQLAlchemy library. SQLAlchemy is a popular SQL toolkit and Object Relational Mapper. It gives full power and flexibility of SQL to an application developer and using that which classes can be mapped to the database.
Can we use it in Flask web-framework?
Yes, Of course. Also, there's a Flask library (Flask-SQLAlchemy) which is an extension for Flask that adds support for SQLAlchemy to the application. So, SQLAlchemy is much simpler to use in Flask.
Before you start using it, you need to understand some basic topics to work with Flask-SQLAlchemy.
This is the important concept of ORM to start working with it. You need to understand how to define your database models in your program.
Relationships
In a larger applications, there will be multiple relationships in the database design. So, you have to tell your program that these tables are connected with each other.
Relationship links
To connect different database fields, you need to specify links between them in the program. There are two concepts known as backref and back_populate in SQLAlchemy. back_populates informs each relationship about the other so that they are kept in sync. So, you need to use in Parent and child class as well. If you use backref, it needs to go on one of them only.
Join Type
After defining the relationships between your data models, you need to specify how to join them when getting the data from those models. There are multiple types of joining in SQLAlchemy like: select, dynamic, joined, subquery etc. Each of those have different meanings, you have to figure out how you need your data.
The four concepts above are extremely important before you start using the SQLAlchemy. I'm providing the best tutorials to helps you understand those concepts faster.
Keyul Patel is a 23-year-old computing student who enjoys eating out, relaxing and outdoor activities. He is helpful and loveable. He is currently at college studying computing. He is obsessed with programming.