我正在建造一个名叫Adhury的聊天信使。
当我通过<代码>db.create_all()自动创建数据库时,出现以下错误:
>>> db.create_all()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:UsersPraktikant2AppDataLocalProgramsPythonPython311Libsite-packagesflask_sqlalchemyextension.py", line 887, in create_all
self._call_for_binds(bind_key, "create_all")
File "C:UsersPraktikant2AppDataLocalProgramsPythonPython311Libsite-packagesflask_sqlalchemyextension.py", line 858, in _call_for_binds
engine = self.engines[key]
^^^^^^^^^^^^
File "C:UsersPraktikant2AppDataLocalProgramsPythonPython311Libsite-packagesflask_sqlalchemyextension.py", line 639, in engines
app = current_app._get_current_object() # type: ignore[attr-defined]
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:UsersPraktikant2AppDataLocalProgramsPythonPython311Libsite-packageswerkzeuglocal.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.
>>>
I have following code:
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)
我做了什么错误,我如何纠正?