【问题标题】:How to properly have Flask run a threaded task in background on Heroku?如何正确让 Flask 在 Heroku 的后台运行线程任务?
【发布时间】:2020-10-07 20:13:35
【问题描述】:

所以,基本上,我有一个无限循环,每隔几分钟就会不断地抓取一个网站。然而,为了启动这个过程,我只是导航到 /scraper 来启动新线程,虽然这工作得很好,但我不想继续路由到 /scraper 来启动线程,如果 Heroku 重新启动他们的服务器维护。有没有一种方法可以实现这一点,这样如果我路由到主页/我只能运行一个线程,因为我宁愿通过路由到主页而不是 /scraper 来启动爬虫。

def scrappy():
    while True:
        try:
            print("Loading scraper...")
            exec(open("texas_scraper.py").read()) #time.sleep(300) inside this .py
        except Exception as e:
            print("Error: There may be a bug in the code or your environment setup.")
            print(e)
            time.sleep(60)
        continue

@app.route('/')
def index():
    print("Someone is on homepage")
    return '''
        <html><body>
        Hi. <a href="/uploads"> Please click here to download the roster.</a>
        </body></html>
        '''

@app.route('/scraper')
def digger():
    t1 = Thread(target = scrappy)
    t1.setDaemon(True)
    t1.start()
    print("Someone started the scraper")
    return '''
        <html><body>
        Hi. Loading scraper now!
        </body></html>
        '''

【问题讨论】:

    标签: python flask heroku flask-sqlalchemy


    【解决方案1】:

    您正在寻找的可能是在 Heroku 中启动两个不同的进程。

    Heroku 有一个Procfile,它决定了实际启动您的应用程序的原因。一个可能是按原样启动您的网络服务器。 Source.

    可以定义第二个进程,这就像在 procfile 中添加一个新行一样简单。您可以使用该新行开始类似Celery 的内容,它可以完全满足您的需求。 Celery 是一个分布式任务队列系统,例如,您可以使用它来安排每 n 次的任务。这消除了对 while 循环的需要,因为您可以简单地每 300 秒安排一次。

    web: flask run
    worker: celery worker -A your_app/celery.py
    

    显然还有其他 Celery 的替代品,找到一个适合您需求的不错的任务队列框架。你甚至可以直接运行你的 webscraper,但是,这可能不会像 Celery 那样在发生崩溃时自行恢复。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-11-20
      • 2021-12-20
      • 1970-01-01
      • 2023-01-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多