将autoincrement在SQLAlchemy的说法似乎是唯一的True和False,但我想设置预先定义的值aid = 1001时,通过自动增量aid = 1002时,下一个插入完成.
在SQL中,可以更改为:
ALTER TABLE article AUTO_INCREMENT = 1001;
Run Code Online (Sandbox Code Playgroud)
我正在使用MySQL,我尝试过,但它不起作用:
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
class Article(Base):
__tablename__ = 'article'
aid = Column(INTEGER(unsigned=True, zerofill=True),
autoincrement=1001, primary_key=True)
Run Code Online (Sandbox Code Playgroud)
那么,我该怎么做呢?提前致谢!
我使用sqlalchemy在我的Python项目中访问MySQL.sqlalchemy的conf是这样的:
dialect=mysql
driver=mysqlconnector
Run Code Online (Sandbox Code Playgroud)
所以我需要通过pip安装Python模块mysql连接器.有帮助吗?
首先我创建一个会话如下:
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
some_engine = create_engine('my_engine_string')
Session = sessionmaker(bind=some_engine)
session = Session()
Run Code Online (Sandbox Code Playgroud)
然后我将此会话作为参数发送给方法
def example(session):
print("you created a session!")
Run Code Online (Sandbox Code Playgroud)
是否可以some_engine从方法session内部获取的值example?没有实际传递some_engine或my_engine_string到example方法。
如下:
def example(session):
print("you created a session!")
engine = <using session get the value of `some_engine`>
print("the engine is retrieved from session")
Run Code Online (Sandbox Code Playgroud) 从今天起,我在 GitHub CI 中收到如下错误:
File "/home/runner/.local/lib/python3.8/site-packages/fb4/login_bp.py", line 12, in <module>
from fb4.sqldb import db
File "/home/runner/.local/lib/python3.8/site-packages/fb4/sqldb.py", line 8, in <module>
db = SQLAlchemy()
File "/home/runner/.local/lib/python3.8/site-packages/flask_sqlalchemy/__init__.py", line 758, in __init__
_include_sqlalchemy(self, query_class)
File "/home/runner/.local/lib/python3.8/site-packages/flask_sqlalchemy/__init__.py", line 112, in _include_sqlalchemy
for key in module.__all__:
AttributeError: module 'sqlalchemy' has no attribute '__all__'
CRITICAL: Exiting due to uncaught exception <class 'ImportError'>
Run Code Online (Sandbox Code Playgroud)
不知道任何可能导致这种情况的重大提交。我的本地测试和 Jenkins CI 仍然有效。
我更改了矩阵以坚持使用 python 3.8,而不是尝试 3.9、3.10 和 3.11,还考虑到python 3.9 AttributeError: module 'posix' has no attribute '__all__'中的类似问题是由于缺少 3.9 支持。
如何调试和缓解上述错误?
我的假设是问题出在设置/环境中,或者 …
在表的SQLAlchemy类中是否有一种方法可以为该表定义/创建触发器和索引?
例如,如果我有一个基本的表...
class Customer(DeclarativeBase):
__tablename__ = 'customers'
customer_id = Column(Integer, primary_key=True,autoincrement=True)
customer_code = Column(Unicode(15),unique=True)
customer_name = Column(Unicode(100))
search_vector = Column(tsvector) ## *Not sure how do this yet either in sqlalchemy*.
Run Code Online (Sandbox Code Playgroud)
我现在想要创建一个触发器来更新"search_vector"
CREATE TRIGGER customers_search_vector_update BEFORE INSERT OR UPDATE
ON customers
FOR EACH ROW EXECUTE PROCEDURE
tsvector_update_trigger(search_vector,'pg_catalog.english',customer_code,customer_name);
Run Code Online (Sandbox Code Playgroud)
然后我想将该字段添加为索引...
create index customers_search_vector_indx ON customers USING gin(search_vector);
Run Code Online (Sandbox Code Playgroud)
现在我从我的应用程序执行任何类型的数据库重新生成后,我必须为tsvector列添加列,触发器定义,然后是psql的索引语句.不是世界末日,而是容易忘记一步.我全都是关于自动化的,所以如果我能在应用程序设置期间完成这一切,那么奖金!
我在Flask上有一个工作的Web应用程序与SqlAlchemy用于审核新闻,它有一些api方法来处理审核请求,例如批准,拒绝当前选择的新闻,列出它们等等.我想为这些方法编写单元测试,以及我让它们工作,但我不明白,如何在一个数据库会话中实现从测试用例执行的所有请求,以便我可以删除对数据库的所有更改.或者是否有其他更清洁或正确的方法来做到这一点?我发现可能我需要的只是SqlAlchemy中的"scoped_session",但实现它的所有工作都失败了.如果这是正确的方法,请告诉我在哪里使用这行代码(在设置中,或在测试用例set_up方法中).
from sqlalchemy.orm import scoped_session
from sqlalchemy.orm import sessionmaker
session_factory = sessionmaker()
Session = scoped_session(session_factory)
Run Code Online (Sandbox Code Playgroud) 我得到了这个奇怪的错误,我说的很奇怪,因为我改变了一个不相关的表.
我试图查询我的tDevice表,看起来像这样:
class TDevice(Base):
__tablename__ = 'tDevice'
ixDevice = Column(Integer, primary_key=True)
ixDeviceType = Column(Integer, ForeignKey('tDeviceType.ixDeviceType'), nullable=False)
ixSubStation = Column(Integer, ForeignKey('tSubStation.ixSubStation'), nullable=False)
ixModel = Column(Integer, ForeignKey('tModel.ixModel'), nullable=True)
ixParentDevice = Column(Integer, ForeignKey('tDevice.ixDevice'), nullable=True)
sDeviceName = Column(Unicode(255), nullable=False)#added
children = relationship('TDevice',
backref=backref('parent', remote_side=[ixDevice]))
device_type = relationship('TDeviceType',
backref=backref('devices'))
model = relationship('TModel',
backref=backref('devices'))
sub_station = relationship('TSubStation',
backref=backref('devices'))
Run Code Online (Sandbox Code Playgroud)
这就是我查询它的方式:
Device = DBSession.query(TDevice).filter(TDevice.ixDevice == device_id).one()
Run Code Online (Sandbox Code Playgroud)
一旦执行此行,我就会收到错误:
ArgumentError: relationship 'report_type' expects a class or a mapper argument (received: <class 'sqlalchemy.sql.schema.Table'>)
Run Code Online (Sandbox Code Playgroud)
我所做的唯一更改是在my中添加一个report_type关系tReportTable
,现在看起来像这样:
class TReport(Base):
__tablename__ …Run Code Online (Sandbox Code Playgroud) 我已经设法使用SQLAlchemy中的批量插入,如:
conn.execute(addresses.insert(), [
{'user_id': 1, 'email_address' : 'jack@yahoo.com'},
{'user_id': 1, 'email_address' : 'jack@msn.com'},
{'user_id': 2, 'email_address' : 'www@www.org'},
{'user_id': 2, 'email_address' : 'wendy@aol.com'},
])
Run Code Online (Sandbox Code Playgroud)
我现在需要的是等同于更新的东西.我试过这个:
conn.execute(addresses.insert(), [
{'user_id': 1, 'email_address' : 'jack@yahoo.com', 'id':12},
{'user_id': 1, 'email_address' : 'jack@msn.com', 'id':13},
{'user_id': 2, 'email_address' : 'www@www.org', 'id':14},
{'user_id': 2, 'email_address' : 'wendy@aol.com', 'id':15},
])
Run Code Online (Sandbox Code Playgroud)
期望每行根据'id'字段进行更新,但它不起作用.我假设这是因为我没有指定WHERE子句,但我不知道如何使用字典中包含的数据指定WHERE子句.
有人能帮助我吗?
我有一个正在运行的Flask应用程序,它是根据我们在网上和Miguel Grinberg的"Flask Web Development"一书中找到的最佳实践组合而建立的.
我们现在需要第二个Python应用程序,它不是Web应用程序,需要访问与Flask应用程序相同的模型.我们想重复使用相同的模型,因此两个应用程序都可以从共享代码中受益.
我们已经删除了对flask-sqlalchemy扩展(我们之前使用过Flask应用程序时)的依赖关系.并将其替换为此处描述的SQLalchemy Declarative扩展,这有点简单(Flask-SQLalchemy为标准SQLAlchemy添加了一些特定的东西)
根据示例,我们在根目录中创建了一个database.py文件.在我们的例子中,有两个与Declarative扩展示例不同的东西:我将引擎和会话放在一个类中,因为我们所有的模型都使用db.session而不是db_session,并且我将带有配置值的字典传递给init( ),以便我可以使用不同的配置从Flask和其他应用程序重新使用此database.py.它看起来像这样:
from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker
from sqlalchemy.ext.declarative import declarative_base
class Database(object):
def __init__(self, cfg):
self.engine = create_engine(cfg['SQLALCHEMY_DATABASE_URI'], convert_unicode=True)
self.session = scoped_session(sessionmaker(autocommit=False, autoflush=False, bind=self.engine))
class Model(object):
pass
Base = declarative_base()
Run Code Online (Sandbox Code Playgroud)
所以现在我们来解决实际问题.Flask创建一个包含配置选项的类字典对象,并将它们作为属性添加到app-instance.它从实例文件夹,站点根目录中的config.py和环境变量加载它们.我需要从Flask传递配置字典,所以我需要Flask来FIRST加载和组装配置,然后初始化数据库,并在app文件的根目录中有一个(配置的)db对象.但是,我们遵循应用工厂模式,因此我们可以针对不同情况(测试,生产,开发)使用不同的配置.
这意味着我们app/__init__.py看起来像这样(简化):
from flask import Flask
from database import Database
from flask.ext.mail import Mail
from flask_bcrypt import Bcrypt
from config import config …Run Code Online (Sandbox Code Playgroud) sqlalchemy ×10
python ×9
flask ×2
orm ×1
postgresql ×1
pyramid ×1
session ×1
sqlite ×1
testing ×1
turbogears ×1