简体   繁体   English

Flask RESTful create_app使用芹菜问题

[英]Flask RESTful create_app using Celery Problem

I am new to Python Flask RESTful API. 我是Python Flask RESTful API的新手。 Now the project that I'm working on was pre built from the previous developers. 现在,我正在处理的项目是由以前的开发人员预先构建的。 I am able to put more logic into this project. 我可以在这个项目中加入更多的逻辑。 Now as requirements goes I need to use CELERY for extensive calculations. 现在,随着需求的增长,我需要使用CELERY进行大量计算。 I went through different articles in the WEB (eg https://blog.miguelgrinberg.com/post/celery-and-the-flask-application-factory-pattern ) and other articles here but still no luck on this. 我浏览了WEB上的其他文章(例如https://blog.miguelgrinberg.com/post/celery-and-the-flask-application-factory-pattern )和此处的其他文章,但在此方面仍然不走运。

[repo: tracker/]
   __init.py__
   app.py
   config.py
   models.py
   celery.py
   tasks.py
   /resources/locate.py
   /resources/create.py

init .py - has the following contents: init .py-具有以下内容:

from tracker import app

app.py - has the following contents: app.py-具有以下内容:

from tracker.resources.locate import Locate
from tracker.resources.create import Create

from .celery import create_celery
from .redis_repo import redis_store
from .config import app_config
from .models import db

import collections

def create_app(config_name):

    app = Flask(__name__)
    app.config.from_object(app_config[config_name])

    api = Api(app, catch_all_404s=True)
    api.add_resource(Locate, '/api/v1/locate/<string:ud>', methods=['GET'])
    api.add_resource(Create, '/api/v1/create/<string:ud>', methods=['GET','POST'])

    redis_store.init_app(app)
    db.init_app(app)

       return app

    app = create_app('development')

    if __name__ == '__main__':
        app.run(threaded=True, debug=False)

config.py - has the following contents: config.py-具有以下内容:

import tempfile

class DevelopmentConfig(Config):
    DEBUG = True
    SQLALCHEMY_POOL_SIZE = 10
    SQLALCHEMY_DATABASE_URI = 'postgres://xxx'
    REDIS_URL = "redis://127.0.0.1:32769/0" 
    CELERY_BROKER_URL = "redis://127.0.0.1:32769/0"
    CELERY_BACKEND = "db+postgresql://xxx" 

app_config = {'development': DevelopmentConfig}

models.py - has the following contents: models.py-具有以下内容:

from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import func, exc, or_
import datetime
from sqlalchemy_utils import UUIDType

import tracker

db = SQLAlchemy()

class T_Logs(db.Model)
      ....
      ....
      ....    

locate.py - has the following contents: locate.py-具有以下内容:

from flask import request, current_app, jsonify, after_this_request
from flask_restful import Resource
from sqlalchemy import exc

from tracker import models, config, redis_repo, utility
from datetime import datetime, timedelta

import uuid, json

class Locate(Resource):

    def get(self, ud):
    ....
    ....    

Using those documentations or tutorials, it's quite easy to run and understand how these works. 使用这些文档或教程,可以很容易地运行和了解它们的工作原理。 But putting it altogether in our implementations it doesnt seem to work. 但是将其完全放在我们的实现中似乎不起作用。

with celery.py 与celery.py

from celery import Celery

def create_celery(app=None):
    application = app or create_app
    celery = Celery(app.import_name,
                    broker=app.config['CELERY_BROKER_URL'])
    celery.conf.update(app.config)
    TaskBase = celery.Task

    class ContextTask(TaskBase):
        abstract = True

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

    celery.Task = ContextTask
    return celery

And sample tasks.py 和示例task.py

from app import create_celery

@celery.task(name="tasks.add")
def add(a,b):
    return a+ b

So when I run these via visual studio code, I dont see any errors or warnings. 因此,当我通过Visual Studio代码运行这些代码时,我看不到任何错误或警告。 But when i run this on the other command prompt to start the worker: 但是当我在另一个命令提示符下运行此命令以启动工作程序时:

celery -A app.tasks.add worker -l info -P eventlet

It saying from tracker.resources.locate import Locate ModuleNotFoundError: No module named 'tracker' 它说从tracker.resources.locate import定位到ModuleNotFoundError:没有名为“ tracker”的模块

It never get executed. 它永远不会被执行。 I'm not yet trying to call the tasks on the resources yet, But I cant proceed yet to understand how to do this. 我尚未尝试调用资源上的任务,但是我仍无法继续了解如何执行此操作。

If anyone could possibly enlighten me with this it would be greatly appreciated. 如果有人可以启发我,将不胜感激。

I have manage to solve the issue, it seems that the problem is on the absolute path. 我已经设法解决了这个问题,看来问题出在绝对的道路上了。

so made some relevant changes like: 因此进行了一些相关的更改,例如:

try:
   from tracker.resources.locate import Locate
except ImportError:
   from resources.locate import Locate

And so with the other import statements. 其他导入语句也是如此。

Now my next problem is, How can I call the task let say inside Locate Route in GET method. 现在,我的下一个问题是,如何调用GET方法中的“定位路由”中的任务。

class Locate(Resource):

    def get(self, ud):

Let me know if any has an idea on this. 让我知道是否对此有任何想法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在flask-restful和create_app中使用flask-jwt-extended回调 - Using flask-jwt-extended callbacks with flask-restful and create_app Flask 测试 create_app 没有返回应用程序? - Flask testing create_app is not returning the application? 带flask-sqlalchemy的create_app模式 - create_app pattern with flask-sqlalchemy 如何使用create_app在flask应用程序中向uwsgi提供不同的配置设置? - How to serve different config settings in flask app to uwsgi using create_app? 使用Blueprints和Flask 1.0+从__init__.py create_app()访问应用的最佳方法 - Best methods access to app from __init__.py create_app() using Blueprints and Flask 1.0+ Flask create_app 不会在 init 中初始化数据库实例扩展 - Flask create_app will not initializing db instance extension in init 使用Flask Factory应用程序create_app配置电子邮件令牌 - Configure Email Token with Flask Factory Application create_app Flask 无法从网站 create_app 导入 - Flask cannot import from website create_app 配置 Python Flask App 以使用“create_app”工厂并在模型类中使用数据库 - Configure Python Flask App to use “create_app” factory and use database in model class pytest w / Flask:在不使用create_app()的情况下轻松获取我们的应用设置? - pytest w/ Flask: easy way to pull in our app setup without create_app()?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM