我正在用 Python 构建一个聊天工具。
当我通过
db.create_all()
自动创建数据库时,出现以下错误:
>>> db.create_all()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Users\Praktikant2\AppData\Local\Programs\Python\Python311\Lib\site-packages\flask_sqlalchemy\extension.py", line 887, in create_all
self._call_for_binds(bind_key, "create_all")
File "C:\Users\Praktikant2\AppData\Local\Programs\Python\Python311\Lib\site-packages\flask_sqlalchemy\extension.py", line 858, in _call_for_binds
engine = self.engines[key]
^^^^^^^^^^^^
File "C:\Users\Praktikant2\AppData\Local\Programs\Python\Python311\Lib\site-packages\flask_sqlalchemy\extension.py", line 639, in engines
app = current_app._get_current_object() # type: ignore[attr-defined]
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Praktikant2\AppData\Local\Programs\Python\Python311\Lib\site-packages\werkzeug\local.py", line 508, in _get_current_object
raise RuntimeError(unbound_message) from None
RuntimeError: Working outside of application context.
This typically means that you attempted to use functionality that needed
the current application. To solve this, set up an application context
with app.app_context(). See the documentation for more information.
>>>
我有以下代码:
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from datetime import datetime
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///db.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)
class Message(db.Model):
id = db.Column(db.Integer, primary_key=True)
user = db.Column(db.String(200), nullable=True)
content = db.Column(db.String(500), nullable=True)
created_at = db.Column(db.DateTime(), default=datetime.utcnow)
with app.app_context():
db.create_all()
@app.route("/")
def start_page():
return "<h1>Hello World!</h1>"
if __name__ == "__main__":
app.run(debug=True)
我做错了什么以及如何解决它?
您所要做的就是强制应用程序的上下文。连接并实例化后,添加以下行:
app.app_context().push()
您的代码将是:
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///db.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)
app.app_context().push()
然后,在终端上:
1。 Python(或 Python3) 2.从应用程序导入应用程序 3.从应用程序导入数据库 4. db.create_all()