在 sqlalchemy 中跨不同模块访问相同的 db.session [英] Accessing same db.session across different modules in sqlalchemy

查看:20
本文介绍了在 sqlalchemy 中跨不同模块访问相同的 db.session的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对 sqlalchemy 非常陌生,正在尝试弄清楚如何让事情变得更干净和连接.

I am very new to sqlalchemy and am trying to figure out how to get things cleaner and connecting.

我创建了一个/model base.py 文档,我在其中创建了一个会话并在表中建立了我的所有实体(以及关系等).我想创建另一个模块,在其中对 base.py 中的实体(表)进行 CRUD 操作.该文件名为 object.py,具有 BaseAPI(object) 类,并具有不同的功能创建"读取"更新"和删除".我想确保我在 object.py 中连接到我的表 (base.py) 并对实体用户进行操作.对于这种情况,实体(表)是用户.

I have created a /model base.py doc where I have created a session and established all my entities in tables (along with relationships and etc.). I want to create another module in which I operate CRUD operations on the entities (tables) in base.py. This file is called object.py and has the class BaseAPI(object) and has the different functions "create" "read" "update" and "delete". I want to make sure that I am connecting to my table (base.py) in object.py and operating on the entity User. For this case, the entity (table) is Users.

这是我在 API object.py 文档中的内容:

This is what I have in the API object.py doc:

#!/usr/bin/env python

from sqlalchemy import create_engine
from sqlalchemy.orm import relationship, backref, sessionmaker
from datetime import datetime, timedelta
import notssdb.model
from base import User #importing from the module base.py -- doesn't work

engine = create_engine('sqlite:///./notssdb.db', echo=True) #in-memory sql engine 

# create a Session
Session = sessionmaker(bind=engine)


class BaseAPI(object):
#    DBSession = scoped_session(sessionmaker(engine))
#    users = DBSession.query(User).all()

    def __init__ (self):
       session = Session()


# CREATE USER 

    def create_user(self, username, password, fullname):
        new_user = User(username, password, fullname)
        self.session.commit(new_user)
        print(username, password, fullname)

我是否导入了太多东西?我需要导入所有的 sqlalchemy 工具吗?我在 BaseAPI 类下的 init 构造函数是否需要实例化数据库会话?

Am I importing too many things? Do I need to import all the sqlalchemy tools? Does my init constructor under class BaseAPI need to instantiate the DB session?

推荐答案

1.我是不是进口了太多东西?我需要导入所有的 sqlalchemy 工具吗?

Sqlalchemy 没有自己的编码风格,你必须遵循 Python 编码风格.如果您不使用任何模块,则没有必要导入它.

Sqlalchemy doesn't have it's own coding style, you've to follow Python coding style. If you don't use any module there is no point of importing it.

我没有看到这已经被使用 from sqlalchemy.orm 导入关系,backref 并且这应该在定义 models 时使用,因此你不需要导入这些模块.

I don't see this has been used from sqlalchemy.orm import relationship, backref and this should be used while defining models, hence you don't need to import these modules.

2.我的类 BaseAPI 下的 init 构造函数是否需要实例化数据库会话?

没有硬性规定您必须在 BaseAPI 中启动 session,您甚至可以像这样编写程序..

There is no hard rule that you've initiate session in your BaseAPI, you can even write your programme like this..

#!/usr/bin/env python

from sqlalchemy import create_engine
from sqlalchemy.orm import relationship, backref, sessionmaker
from datetime import datetime, timedelta
import notssdb.model
from base import User #importing from the module base.py -- doesn't work

engine = create_engine('sqlite:///./notssdb.db', echo=True) #in-memory sql engine 

# create a Session
Session = sessionmaker(bind=engine)
session = Session()


class BaseAPI(object):

# CREATE USER 

    def create_user(self, username, password, fullname):
        new_user = User(username, password, fullname)
        session.commit(new_user)
        print(username, password, fullname)

但是将您的 connection 生成部分与 user manager 放在一起并不是一个好习惯,我建议您遵循这种方式..

But it's not good practice to club your connection generation part with user manager, I would suggest you follow this way..

注意:这只是一个示例代码,我没有执行它,你只需要按照这个来结构你的代码.

Note: This is just a sample code and I didn't execute this, you just have to follow this to structure your code.

首先创建单独的连接管理模块,可能类似于connection_manager.py,内容如下.

First create seperate module for connection management, may be like connection_manager.py with the below content.

from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker

engine = create_engine('sqlite:///./notssdb.db', echo=True)

# create a Session
Session = sessionmaker(bind=engine)

class SessionManager(object):
    def __init__(self):
        self.session = Session()

然后在此处创建您的 user_manger.py 并导入您的 SessionManager.

And the create your user_manger.py and import your SessionManager here.

from base import User # this is your User model
from connection_manager import SessionManager

class UserManager(SessionManager):

    def create_user(self, username, password, fullname):
        new_user = User(username, password, fullname)
        self.session.commit(new_user)
        print(username, password, fullname)

    def delete_user(self, *args):
        pass # your code

通过这种方式,您可以使代码更简洁.

This way you can make your code cleaner.

这篇关于在 sqlalchemy 中跨不同模块访问相同的 db.session的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆