正如評論中所討論的,這是解決方案,因此對其他人有幫助:您需要定義一個會話并將其傳遞給 load 函數,如下所示:from sqlalchemy import engine #thanks to your commentfrom sqlalchemy.orm import scoped_session, sessionmakerclass UserRegister(Resource): @classmethod def post(cls): # the 'load' function in marshmallow will use the data to create usermodel object sess = scoped_session(sessionmaker(bind=engine)) user = user_schema.load(request.get_json(), sess)
2 回答

守著一只汪
TA貢獻1872條經驗 獲得超4個贊
您必須重命名函數參數以不與類屬性的名稱沖突:
def test_factory(b):
class Test:
a = b
return Test
>>> t1 = test_factory(1)
>>> t2 = test_factory(2)
>>> print(t1.a, t2.a)
1 2

蝴蝶不菲
TA貢獻1810條經驗 獲得超4個贊
解析class語句時,賦值將a其定義為臨時類命名空間的一部分,類似于函數定義中對局部變量的賦值。因此,該名稱a會在封閉函數范圍內隱藏參數的名稱。
您可以更改參數名稱(如schwobaseggl所示)
def test_factory(a_value):
class Test:
a = a_value
return Test
或者在定義之后設置屬性:
def test_factory(a):
class Test:
pass
Test.a = a
return Test
或type直接致電:
def test_factory(a):
return type('Test', (), {'a': a})
添加回答
舉報
0/150
提交
取消