烧瓶+;SQLAlchemy:通过运行python脚本加载带有记录的数据库

烧瓶+;SQLAlchemy:通过运行python脚本加载带有记录的数据库,python,flask,sqlalchemy,flask-sqlalchemy,Python,Flask,Sqlalchemy,Flask Sqlalchemy,我正在尝试在flask应用程序中使用SQLALchemy加载我的数据库一次。我以为我可以通过从terminal命令运行脚本来将记录添加到数据库中,但似乎我在执行python脚本时遇到了困难 通过运行export FLASK\u app=app/\uuuuu init\uuuuuu.py初始化应用程序,然后FLASK run甚至加载数据库吗 是否每次重新启动本地服务器 文件夹结构: app api __init__.py log.py tasks

我正在尝试在flask应用程序中使用SQLALchemy加载我的数据库一次。我以为我可以通过从terminal命令运行脚本来将记录添加到数据库中,但似乎我在执行python脚本时遇到了困难

  • 通过运行
    export FLASK\u app=app/\uuuuu init\uuuuuu.py
    初始化应用程序,然后
    FLASK run
    甚至加载数据库吗
  • 是否每次重新启动本地服务器
文件夹结构:

  app
    api
      __init__.py
      log.py
    tasks
      __init__.py
      test.py
    __init__.py
    models.py
    utils.py
app/api/log.py

from app import app
from app.models import Race, db
from app.utils  import * 

def historical_records():
    df_races, df_circuits, constructors, df_drivers, df_results = extract_to_df_race('results', seasons, races_round)
    # Check if row exists in table
    exists = db.session.query(db.exists().scalar())
    if exists is None:
        df_races, df_circuits, constructors, df_drivers, df_results = extract_to_df_race('results', seasons, races_round)
        save_races_to_db(df_races, db)
    else:
        print("The database already contains data of 2016 to current race")

def save_races_to_db(df_races, db):
    for idx,row in df_races.iterrows():
        r = Race()
        r.url = df_races.loc[idx,"url"]
        r.season = df_races.loc[idx,"season"]
        r.raceName = df_races.loc[idx,"raceName"]
        db.session.add(r)
        try:
            db.session.commit()
        except Exception as e:
            db.session.rollback()
            print(str(e))


historical_records()
我激活了虚拟环境,然后执行了
python app/api/log.py
,但遇到了以下错误:

  File "app/api/log.py", line 1, in <module>
    from app import app
ImportError: No module named app
文件“app/api/log.py”,第1行,在
从应用程序导入应用程序
ImportError:没有名为app的模块

通过运行
export FLASK\u app=app/\uuuuu init\uuuuuu.py
初始化应用程序,然后
FLASK run
甚至加载数据库吗

您的问题是,您正在使用包中的模块作为脚本;此时,顶级模块导入路径设置为
app/api/
目录。至少您可以将其作为
python-m app.api.log运行,以保持正确的上下文

但是,您应该改为将脚本设置为,因为这样可以提供一个活动的应用程序上下文

使用以下命令使您的
历史记录()

import click

from app import app
from app.models import Race, db
from app.utils  import * 

@app.cli.command()
def historical_records():
    # your function
从模块末尾删除
历史记录()
调用

然后,您可以使用

FLASK_APP=app flask historical_records
(您不需要将
/\uuuuu init\uuuu.py
添加到
FLASK\u APP


我们无法告诉您是否
flask run
将加载数据库,因为我们既看不到
\uuuu init\uuuuuuuupy
也看不到
db.py
,也不知道您是否运行了
create\u all()
函数。

您的应用程序不是python文件,您如何导入它。你可以试着从。。。导入模型
并从app import app
中删除该
。您的
\uuuu init\uuuuuuuuy.py
文件中有什么?
db.session.query(db.exists().scalar())
要么失败并出现错误,要么检查
NULL
是否存在(无法准确测试这两个文件中的哪一个),这不是一个有用的检查。它只是一个空的
EXISTS
语句。