Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Data access object (DAO) in Python Flask SQLAlchemy

Does the Python (Flask) SQL Alchemy uses both DAO and ORM design, or simply just ORM? I am learning design strategies and I thought of SQLAlchemy. Is it considered a DAO (clearly ORM) as well?

By default, it does not look like DAO.

What if I defined a class for an existing model class , for example given I have the following class:

class User(db.model):
    id = db.Column(db.Integer, primary_key=True)
    email = db.Column(db.String(120), unique=True, nullable=False)
    verified= db.Column(db.String(5), unique=False, nullable=False)

I define another class, UserDao

class UserDao:
    def addNewUser(user):
         pass
    def retrieveAllUsers(user):
         users = User.query.limit(5).all()

And I instantitate and object of this UserDao class and call the respective methods to do some database operations through the respective method, does this make it a "DAO Pattern"?

like image 513
xineta5158 Avatar asked Jun 20 '26 16:06

xineta5158


1 Answers

Regarding your question "And I instantitate and object of this UserDao class and call the respective methods to do some database operations through the respective method, does this make it a "DAO Pattern"?" I would say yes, it is in that direction however you need to look at your whole application overall to answer that question.

The idea of a DAO is to keep the code of your application that does the business logic separate from the code that handles how you get and store the data. So the easiest way to answer your question is to look at your whole application and ask yourself "if tomorrow I want to work with mongodb (for example) instead of mysql (whether you are using sqlachemy or not) what code of my application would I need to change?". If you need to change code from the business logic code then it means you don't have a dao or at least not a strong one. If you only need to touch the code that handles database operations then you have a DAO. You can also look it in another way: what if tomorrow you decide that you are better off using django instead of sqlachemy? what code would you need to change? would you need to touch the code that does the business logic?

like image 59
alect Avatar answered Jun 23 '26 05:06

alect



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!