我是Python和烧瓶的初学者。我正在通过瓶教程,直到定义和访问数据库部分。
编写所有代码,保存,并执行下面的命令,以使DB无效。flask init-db
但是,我在终端上得到了流的错误。
FileNotFoundError: [Errno 2] No such file or directory: /Desktop/flask-tutorial/instance/schema.sql'
我反复检查代码,找出出了什么问题,搜索了StackOverflow,w,并发现了一些类似的问题,但它们最终没有为我工作。
--加法--
__init__py
import os
from flask import Flask
def create_app(test_config=None):
# create and configure the app
app = Flask(__name__, instance_relative_config=True)
app.config.from_mapping(
SECRET_KEY='dev',
DATABASE=os.path.join(app.instance_path, 'flaskr.sqlite'),
)
if test_config is None:
# load the instance config, if it exists, when not testing
app.config.from_pyfile('config.py', silent=True)
else:
# load the test config if passed in
app.config.from_mapping(test_config)
# ensure the instance folder exists
try:
os.makedirs(app.instance_path)
except OSError:
pass
# a simple page that says hello
@app.route('/hello')
def hello():
return 'Hello, world! this is my first flask app'
from . import db
db.init_app(app)
return appdb.py
import sqlite3
import click
from flask import current_app, g
from flask.cli import with_appcontext
def init_db():
db = get_db()
with current_app.open_instance_resource('schema.sql') as f:
db.executescript(f.read().decode('utf8'))
@click.command('init-db')
@with_appcontext
def init_db_command():
"""Clear the existing data and create new tables."""
init_db()
click.echo('Initialized the database.')
def get_db():
if 'db' not in g:
g.db = sqlite3.connect(
current_app.config['DATABASE'],
detect_types=sqlite3.PARSE_DECLTYPES
)
g.db.row_factory = sqlite3.Row
return g.db
def close_db(e=None):
db = g.pop('db', None)
if db is not None:
db.close()
def init_app(app):
app.teardown_appcontext(close_db)
app.cli.add_command(init_db_command)树
.
├── flaskr
│ ├── db.py
│ ├── __init__.py
│ ├── __pycache__
│ │ ├── db.cpython-39.pyc
│ │ └── __init__.cpython-39.pyc
│ └── schema.sql
├── instance
│ └── flaskr.sqlite发布于 2022-04-03 19:53:26
您的代码有open_instance_resource,它正在寻找instance/schema.sql,但是您的schema.sql不在那里。原始代码有open_resource,它看起来相对于root_path。
发布于 2022-04-03 19:51:15
我认为您已经在虚拟env中下载了该文件,并试图在您的env.When之外访问它--您创建了虚拟env,文件是在该env中下载的,而不管您必须首先输入env中的全部system.So,然后运行代码。
https://stackoverflow.com/questions/71729307
复制相似问题