![](/img/trans.png)
[英]I am having a bit of trouble with this hangman program. Can someone help me figure it out?
[英]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 代码中将python
输入到 powershell 中。
然后我输入from flaskblog import db
并得到错误
导入错误:无法从 'flaskblog' 导入名称 'db' (C:\\Users\\n\\OneDrive\\Desktop\\codingfiles2use\\flaskblog_ init _.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)
运行文件
from flaskblog.app import create_app
app = create_app()
if __name__ == '__main__':
app.run(debug=True)
配置文件
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/.
我尝试通过添加不同的代码块之一来完成代码,但它不起作用我仍然收到错误。 我尝试了所有代码块我该如何解决这个问题?
您需要使用 app_context
在终端中运行所有这些命令
from flaskblog.app import db,create_app
from flaskblog.models import User
app = create_app()
with app.app_context():
db.create_all()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.