【问题标题】:Scaling a Heroku dyno from within the script从脚本中缩放 Heroku dyno
【发布时间】:2020-11-23 00:55:54
【问题描述】:

我正在使用工人测功机运行蜘蛛,一切正常。这很好,但是每当蜘蛛完成时 Heroku 就会感到困惑。它打印以下日志并再次启动应用程序,因为它认为应用程序崩溃了。

app[worker.1]: 2020-11-23 00:04:10 [scrapy.core.engine] INFO: Spider closed (finished)
heroku[worker.1]: Process exited with status 0
heroku[worker.1]: State changed from up to crashed
heroku[worker.1]: State changed from crashed to starting
heroku[worker.1]: Starting process with command `python realscraper.py`

那么我如何告诉 Heroku dyno 当蜘蛛关闭时,它应该缩小到 0?我不希望它崩溃并继续尝试重新启动。

【问题讨论】:

  • 请同时添加代码

标签: python heroku


【解决方案1】:

通过修改this tutorial(其中有一些错误或贬值的东西),我能够在我的管道的close_spider 函数中创建一个scale 函数。当我的蜘蛛关闭时,它会自动将测功机缩放为零,因此 Heroku 之后无法再次运行该脚本。

APP = "herokuappname" ## your app name
KEY = "yourapikey" ## your Heroku API key
PROCESS = "worker" ## any type of dyno process should work here
HEADERS = {
    'Accept': "application/vnd.heroku+json; version=3",
    'Authorization': 'Bearer ' + KEY,
    'Content-Type': 'application/json'
}

class MyPipeline:
    ## up here are the __init__ and process_item definitions, omitted for clarity

    def close_spider(self, spider):

        def scale(size):
            payload = {'quantity': size} ## size is the number of dynos to scale to
            json_payload = json.dumps(payload)
            url = "https://api.heroku.com/apps/" + APP + "/formation/" + PROCESS
            try:
                result = requests.patch(url, headers=HEADERS, data=json_payload)
            except:
                print("Running scale function didn't work lol")
                return None
            if result.status_code == 200:
                return "Success!"
            else:
                return "Failure"

        print('Scaling out ... Closing app...')
        print(scale(0))
        
        return

显然我wasn't the only one 正在寻找类似的解决方案。 Heroku Docs 没有明确说明您可以使用 API 从脚本中关闭 dyno。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-12-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-03
    • 2015-09-16
    • 2019-06-24
    相关资源
    最近更新 更多