我在 vsc 和 windows 10 中的 flask 中创建数据库时遇到问题。有人可以帮助解决这个问题吗?

I am having trouble creating the database in flask in vsc and in windows 10. Can someone help solve the problem?

我需要创建数据库。

这是创建数据库时需要输入的内容。

from flaskblog import db
from flaskblog.models import User, Post, etc  
db.create_all()

我首先在 visual studio 代码的 powershell 中输入 python

然后我输入 from flaskblog import db 并得到错误

ImportError: 无法从 'flaskblog' 导入名称 'db' (C:\Users\n\OneDrive\Desktop\codingfiles2use\flaskblog_init_.py)

这是我的文件树。 file tree

我该如何解决这个问题?谢谢

app.py

from flask import Flask  
# make SQLAlchemy work 
from flask_sqlalchemy import SQLAlchemy
# make login work
from flask_login import LoginManager# user_loaded_from_header
# make crf protection work 
from flask_wtf.csrf import CSRFProtect





# setup databases
db = SQLAlchemy()
# Make Login user variable work ?
login_manager = LoginManager()
# Setup CSRF protection. This allows html forms to work and be secure.  
csrf = CSRFProtect()


# imports config from config.py
from flaskblog.config import Config


def create_app(config_class=Config): 
    app = Flask(__name__) 
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False 
    # what does this do?
    app.config.from_object(config_class)
    
    db.init_app(app)
    login_manager.init_app(app)
    csrf.init_app(app)
    
    from flaskblog.usersinfo.routes import usersinfo
    # why lowercse b in blueprints ?
    app.register_blueprint(usersinfo)
    return app 

from .models import User 

@login_manager.user_loader
def load_user(user_id):
    return User.get_by_id(user_id)

run.py

from flaskblog.app import create_app
app = create_app()
if __name__ == '__main__': 
    app.run(debug=True)

config.py

import os     

class Config:
    # Setup CSRF secret key
    SECRET_KEY = os.urandom(32)
    SQLALCHEMY_DATABASE_URI = 'sqlite:///tmp/test.db'

当我输入时

from flaskblog import db
from flaskblog.models import User   
db.create_all()

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Users\nmyle\AppData\Local\Programs\Python\Python39\lib\site-packages\flask_sqlalchemy\__init__.py", line 1094, in create_all
    self._execute_for_all_tables(app, bind, 'create_all')
  File "C:\Users\nmyle\AppData\Local\Programs\Python\Python39\lib\site-packages\flask_sqlalchemy\__init__.py", line 1071, in _execute_for_all_tables   
    app = self.get_app(app)
  File "C:\Users\nmyle\AppData\Local\Programs\Python\Python39\lib\site-packages\flask_sqlalchemy\__init__.py", line 1042, in get_app
    raise RuntimeError(
RuntimeError: No application found. Either work inside a view function or push an application context. See http://flask-sqlalchemy.pocoo.org/contexts/.

我尝试通过添加一个不同的代码块来完成代码,但它不起作用,我仍然收到错误消息。我尝试了所有代码块,我该如何解决这个问题?

http://flask-sqlalchemy.pocoo.org/contexts/.

您需要使用app_context

运行 终端中的所有这些命令

from flaskblog.app import db,create_app
from flaskblog.models import User  
app = create_app()
with app.app_context():
    db.create_all()