将数据插入数据库时​​,如何解决“ TypeError:无法腌制_thread._local对象”?

时间:2019-04-16 12:59:34

标签: python sql postgresql flask adminer

尝试在PostgreSQL数据库表中插入用户名和密码时,出现以下错误:

TypeError
TypeError: can't pickle _thread._local objects

Traceback (most recent call last)
File "c:\users\alex\appdata\local\programs\python\python37-32\lib\site-packages\flask\app.py", line 2309, in __call__
return self.wsgi_app(environ, start_response)
File "c:\users\alex\appdata\local\programs\python\python37-32\lib\site-packages\flask\app.py", line 2295, in wsgi_app
response = self.handle_exception(e)
File "c:\users\alex\appdata\local\programs\python\python37-32\lib\site-packages\flask\app.py", line 1741, in handle_exception
reraise(exc_type, exc_value, tb)
File "c:\users\alex\appdata\local\programs\python\python37-32\lib\site-packages\flask\_compat.py", line 35, in reraise
raise value
File "c:\users\alex\appdata\local\programs\python\python37-32\lib\site-packages\flask\app.py", line 2292, in wsgi_app
response = self.full_dispatch_request()
File "c:\users\alex\appdata\local\programs\python\python37-32\lib\site-packages\flask\app.py", line 1816, in full_dispatch_request
return self.finalize_request(rv)
File "c:\users\alex\appdata\local\programs\python\python37-32\lib\site-packages\flask\app.py", line 1833, in finalize_request
response = self.process_response(response)
File "c:\users\alex\appdata\local\programs\python\python37-32\lib\site-packages\flask\app.py", line 2114, in process_response
self.session_interface.save_session(self, ctx.session, response)
File "c:\users\alex\appdata\local\programs\python\python37-32\lib\site-packages\flask_session\sessions.py", line 355, in save_session
total_seconds(app.permanent_session_lifetime))
File "c:\users\alex\appdata\local\programs\python\python37-32\lib\site-packages\werkzeug\contrib\cache.py", line 839, in set
pickle.dump(value, f, pickle.HIGHEST_PROTOCOL)
TypeError: can't pickle _thread._local objects

我不确定这是什么意思,但是假设这是引起问题的代码:

user_id = db.execute("INSERT INTO users (username, password) VALUES(:username, :password)", {"username": username, "password": password})

if not user_id:
   return render_template("error.html", message="username already taken")

# stores users id
session["user_id"] = user_id

return redirect("/")

我的数据库有三个字段:用户名(文本),密码(文本)和user_id(整数)

在我的python文件中,application.py使用以下代码将flask应用程序连接到数据库。

# Set up database
engine = create_engine(os.getenv("DATABASE_URL"))
db = scoped_session(sessionmaker(bind=engine)) 

1 个答案:

答案 0 :(得分:1)

我知道这已经很晚了,但是以防万一仍然有人遇到此问题,我认为您忘记了包含fetchone()fetchall()。因此,假设您对表中的每个用户都有唯一的用户ID,user_id行应读为user_id = db.execute("SELECT user_id FROM users WHERE username = :username", {"username": username}).fetchone()或类似的内容。

类似地,我相信您希望在试图向表中插入行的任何行之后运行db.commit()

并且会话行应显示为session["user_id"] = user_id[0]。希望这会有所帮助。