flask_sqlalchemy:ImportError:无法导入名称数据库

时间:2018-08-05 19:02:19

标签: python flask flask-sqlalchemy

我无法解决此错误:

  

ImportError:无法导入名称db

,带有错误跟踪:

  

文件“ ../celery-scheduler/app/models.py”,第3行,在       从应用程序导入数据库

已安装的软件包版本:

celery==4.1.1
Flask==0.12.2
Flask-SQLAlchemy==2.3.2
SQLAlchemy==1.2.10

这是文件夹的结构:

celery-scheduler
  app
    tasks
      __init__.py
      test.py
    templates
      races.html
    __init__.py
    models.py

我猜想初始化和使用数据库的许多方法使我感到困惑。工作原理:Celery worker会定期从API提取数据,然后将其存储在数据库中,然后呈现结果。

celery-scheduler / config.py

from os import environ
import os
basedir = os.path.abspath(os.path.dirname(__file__))

REDIS_HOST = "0.0.0.0"
REDIS_PORT = 6379
BROKER_URL = environ.get('REDIS_URL', "redis://{host}:{port}/0".format(
    host=REDIS_HOST, port=str(REDIS_PORT)))
CELERY_RESULT_BACKEND = BROKER_URL
SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URL') or \
    'sqlite:///' + os.path.join(basedir, 'app.db')
SQLALCHEMY_TRACK_MODIFICATIONS = False

app / __ init __。py

from flask import Flask, render_template
from flask_sqlalchemy import SQLAlchemy
from celery import Celery
import celeryconfig

f1 = Flask(__name__)
f1.config.from_object('config')

db = SQLAlchemy(f1)

def make_celery(app):
    # create context tasks in celery
    celery = Celery(
        app.import_name,
        broker=app.config['BROKER_URL']
    )
    celery.config_from_object(celeryconfig)
    TaskBase = celery.Task

    class ContextTask(TaskBase):
        abstract = True

        def __call__(self, *args, **kwargs):
            with app.app_context():
                return TaskBase.__call__(self, *args, **kwargs)

    celery.Task = ContextTask

    return celery

celery = make_celery(f1)

@f1.route('/data/races/all', methods=['GET'])
def race():
    races_from_db = Race.query().all()
    return render_template('races.html', races_from_db=races_from_db)

app / models.py

from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from app import db

class Race(db.Model):
    __tablename__ = 'races'
    raceId = db.Column(db.Integer, primary_key=True)
    url = db.Column(db.String(50), unique=True)

    def __init__(self):
        self.raceId = raceId
        self.url = url

app / tasks / test.py

import celery
from celery.task.base import periodic_task
from app.models import Race
from app import db

@periodic_task(run_every=datetime.timedelta(seconds=300), bind=True)
def periodic_run_get_manifest():
    ...generates dataframe of data...
    races = df_races.to_json(orient='records')
    r = Race(races)
    db.session.add(r)
    db.session.commit()

0 个答案:

没有答案