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

查看:216
本文介绍了在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)并在实体User上进行操作.在这种情况下,实体(表)为用户".

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 doc中所拥有的:

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 import relationship, 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下的初始化构造函数是否需要实例化 数据库会话?

2. Does my init constructor under class BaseAPI need to instantiate the DB session?

在您的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..

注意:这只是一个示例代码,我没有执行,您只需遵循此代码即可structure您的代码.

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天全站免登陆