R10/H10 尝试使用 Heroku 打开 Flask 应用程序时出现应用程序错误

R10/H10 application error when trying to open Flask app with Heroku

我和一个朋友写了一个 Python 应用程序来在世界地图上按国家/地区绘制 Covid-19 病例数。

这是我们的代码:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Mar 15 17:01:50 2020

@author: sheldon
"""

import os 
import pandas as pd
import folium
from folium import plugins
import rasterio as rio
from rasterio.warp import calculate_default_transform, reproject, Resampling
import earthpy as et
import pdb 
import flask
from flask import Flask




class CovidDF:
    def __init__(self, url):
        self.url = url
        self.raw = None
        self.aggregated = None

    def reload(self, date):
        self.raw = pd.read_csv(self.url)
        self.group_by_regions(date)

    def group_by_regions(self,date):
          df=self.raw[['Province/State','Country/Region','Lat','Long',date]]
          self.aggregated=df.groupby(['Country/Region']).agg({'Lat':'mean',
                              'Long':'mean',
                              date: 'sum'})
          self.aggregated.at['France','Lat']=46.2276
          self.aggregated.at['France','Long']=2.2137


class CovidData(object):

    def __init__(self):
        self.confirmed_cases = CovidDF('https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_19-covid-Confirmed.csv')
        self.deaths = CovidDF('https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_19-covid-Deaths.csv')
        self.recoveries = CovidDF('https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_19-covid-Recovered.csv')
        self.loaded = False
        self.map = folium.Map(location=[0,0],
              tiles = 'Stamen Terrain',
              zoom_start=2)
        
    def populate(self, date):
        if not self.loaded:
             self.confirmed_cases.reload(date)
             self.deaths.reload(date)
             self.recoveries.reload(date)
             self.loaded=True

    def plot_number_of_cases(self,df,date,custom_color):
          dc=df.iloc[df[date].to_numpy().nonzero()]
          latitude = dc.Lat.values.astype('float')
          longitude = dc.Long.values.astype('float')
          radius = dc[date].values.astype('float')
     
          for la,lo,ra in zip(latitude,longitude,radius):
              folium.Circle(
                  location=[la,lo],
                  radius=ra*10,
                  fill=True,
                  color=custom_color,
                  fill_color=custom_color,
                  fill_opacity=0.5
              ).add_to(self.map)

    def plot_number_of_cases_for_all_dataframes(self,date):
          self.plot_number_of_cases(self.confirmed_cases.aggregated,date,'blue')
          self.plot_number_of_cases(self.deaths.aggregated,date,'red')
          self.plot_number_of_cases(self.recoveries.aggregated,date,'green')
          



my_date='3/14/20'
covid_data=CovidData()
covid_data.populate(my_date)
covid_data.plot_number_of_cases_for_all_dataframes(my_date)
#covid_data.map.save("./mytest.html")

app = Flask(__name__)
@app.route("/")
def display_map():
     return covid_data.map._repr_html_()

该应用程序在 Heroku 上构建良好,但我们在尝试打开它时遇到应用程序错误。 检查日志会产生以下错误消息:

2020-03-16T10:37:49.600873+00:00 heroku[web.1]: Error R10 (Boot timeout) -> Web process failed to bind to $PORT within 60 seconds of launch

2020-03-16T10:37:49.600972+00:00 heroku[web.1]: Stopping process with SIGKILL

2020-03-16T10:37:49.697252+00:00 heroku[web.1]: Process exited with status 137

2020-03-16T10:41:33.514461+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=covid19-viz.herokuapp.com request_id=2e0727f9-d3eb-4966-8252-92a871deaa41 fwd="77.150.72.89" dyno= connect= service= status=503 bytes= protocol=https

我已经检查过 this other post 并了解到该错误与端口规范问题有关,但我不知道如何解决。任何帮助将不胜感激!

解决方案一:

当 运行 应用通过 python app.py 添加到您的 app.py 时:

if __name__ == "__main__":
  app.run(host='0.0.0.0', port=os.environ.get('PORT', 80))

方案二:

当 运行 应用通过 flask run 调整 Procfile 为:

web: flask run --host=0.0.0.0 --port=$PORT

方案三:

使用 Gunicorn 将 Procfile 调整为:

web: gunicorn app:app

gunicorn 添加到 requirements.txt。 Gunicorn 自动绑定到 $PORT.


在 Heroku 上托管时,您需要绑定到 Heroku 作为环境变量提供给您的 $PORT