首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >烧瓶教程。FileNotFoundError

烧瓶教程。FileNotFoundError
EN

Stack Overflow用户
提问于 2022-04-03 19:44:39
回答 2查看 181关注 0票数 -1

我是Python和烧瓶的初学者。我正在通过瓶教程,直到定义和访问数据库部分。

编写所有代码,保存,并执行下面的命令,以使DB无效。flask init-db

但是,我在终端上得到了流的错误。

FileNotFoundError: [Errno 2] No such file or directory: /Desktop/flask-tutorial/instance/schema.sql'

我反复检查代码,找出出了什么问题,搜索了StackOverflow,w,并发现了一些类似的问题,但它们最终没有为我工作。

--加法--

__init__py

代码语言:javascript
复制
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 app

db.py

代码语言:javascript
复制
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)

代码语言:javascript
复制
.
├── flaskr
│   ├── db.py
│   ├── __init__.py
│   ├── __pycache__
│   │   ├── db.cpython-39.pyc
│   │   └── __init__.cpython-39.pyc
│   └── schema.sql
├── instance
│   └── flaskr.sqlite
EN

回答 2

Stack Overflow用户

发布于 2022-04-03 19:53:26

您的代码有open_instance_resource,它正在寻找instance/schema.sql,但是您的schema.sql不在那里。原始代码有open_resource,它看起来相对于root_path

票数 1
EN

Stack Overflow用户

发布于 2022-04-03 19:51:15

我认为您已经在虚拟env中下载了该文件,并试图在您的env.When之外访问它--您创建了虚拟env,文件是在该env中下载的,而不管您必须首先输入env中的全部system.So,然后运行代码。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71729307

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档