我正在使用Flask开发REST API。其中一个表格建模如下:
class AudioSessionModel(db.Model):
__tablename__ = 'audio_session'
id = db.Column('audio_session_id', db.Integer, primary_key = True)
cs_id = db.Column(db.Integer)
session_id = db.Column(db.Integer)
facility = db.Column(db.Integer)
description = db.Column(db.String(400))
def __init__(self, cs_id, session_id, facility):
self.cs_id = cs_id
self.session_id = session_id
self.facility = facility
业务逻辑在DAO类中定义:
class AudioSessionDAO(object):
def update(self, data):
audio = AudioSessionModel.query.filter(cs_id == data['CSID'], session_id == data['Session'])
audio.description = data['Desc']
db.session.commit()
return audio
在upate
请求的端点中调用此PUT
函数:
@api.route('/OperatorAccessment')
class OperatorAssessment(Resource):
@api.expect(assessment)
def put(self):
as_dao = AudioSessionDAO()
as_dao.update(request.json)
模型assessment
如下所示:
assessment = api.model('Operator Assessment', {
'CSID': fields.Integer(required=True, description='Central Station ID'),
'Session': fields.Integer(required=True, description='Session ID'),
'Desc': fields.String(description='Description')
})
当我在请求正文中使用以下json测试PUT
请求时:
{
"CSID": 1,
"Session": 1,
"Desc": "Siren"
}
我收到以下错误:
File "C:\Users\xxx_app\model\dao.py", line 63, in update
audio = AudioSessionModel.query.filter(cs_id == data['CSID'], session_id == data['Session'])
NameError: name 'cs_id' is not defined
显然,cs_id
已定义。为什么我仍然会收到此错误?
答案 0 :(得分:1)
您必须使用该类的属性,即
AudioSessionModel.query.filter(
AudioSessionModel.cs_id == data['CSID'],
AudioSessionModel.session_id == data['Session'])
或filter_by
使用关键字参数仅使用=
:
AudioSessionModel.query.filter_by(
cs_id=data['CSID'],
session_id=data['Session'])
请参阅What's the difference between filter and filter_by in SQLAlchemy?