![](/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.