无法在flask中创建数据库

问题描述 投票:0回答:1

我是 Flask 新手。

我的代码是

    from flask import Flask,render_template
    from flask_sqlalchemy import SQLAlchemy
    from datetime import datetime

    app = Flask(__name__)
    app.config["SQLALCHEMY_DATABASE_URI"]= "sqlite:///todo.db"

    db=SQLAlchemy(app)

    class TODO(db.Model):
        sno =db.Column(db.Integer,primary_key=True)
        title=db.Column(db.String(200),nullable=False)
        decs=db.Column(db.String(500),nullable=False)
        date_created=db.Column(db.DateTime,default = "wrong data")

        def __repr__(self) -> str:
            return f"{self.sno}--{self.title}"

    @app.route("/")
    def hello_world():
        return render_template("index.html")

    @app.route("/products")
        def product():
        return "<p>this is product page</p>"


    if __name__ == "__main__":
        app.run (debug= True, port=7000)

我的Python文件工作正常。 我正在尝试在虚拟环境中创建数据库

我收到以下错误:


(env) PS C:\Flask> python
Python 3.11.2 (tags/v3.11.2:878ead1, Feb  7 2023, 16:38:35) [MSC v.1934 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.  
>>> from app import db
>>> db.create_all()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Flask\env\Lib\site-packages\flask_sqlalchemy\extension.py", line 884, in create_all
    self._call_for_binds(bind_key, "create_all")
  File "C:\Flask\env\Lib\site-packages\flask_sqlalchemy\extension.py", line 855, in _call_for_binds
    engine = self.engines[key]
             ^^^^^^^^^^^^
  File "C:\Flask\env\Lib\site-packages\flask_sqlalchemy\extension.py", line 636, in engines
    app = current_app._get_current_object()  # type: ignore[attr-defined]
          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Flask\env\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.  

我无法找出错误。

python flask flask-sqlalchemy
1个回答
0
投票

改用flask shell,在cmd上输入flask shell并运行普通命令来创建数据库

© www.soinside.com 2019 - 2024. All rights reserved.