我最近向Heroku部署了一个Web应用程序,试图从Twitter Streaming API下载推文。它工作60秒,但随后Heroku抛出错误:
Error R10 (Boot timeout) -> Web process failed to bind to $PORT within 60 seconds of launch
要连接到API,我使用PycURL(C库libcurl的包装器)来打开与端点uri的连接。我将PycURL使用的本地端口设置为Heroku指定的$ PORT变量。相关代码如下:
def collect_debug_info(self, debug_type, debug_msg):
if debug_type == 0 and debug_msg.decode('utf-8')[0] == 'L':
print('debug(%s): %s' % (debug_type, debug_msg))
def setup_connection(self):
# Creates persistent HTTP connection to Streaming API endpoint using cURL.
if self.conn:
self.conn.close()
self.buffer = ''
self.conn = pycurl.Curl()
self.conn.setopt(pycurl.URL, API_ENDPOINT_URL)
self.conn.setopt(pycurl.USERAGENT, USER_AGENT)
# Using gzip is optional but saves us bandwidth.
self.conn.setopt(pycurl.ENCODING, 'deflate, gzip')
self.conn.setopt(pycurl.POST, 1)
self.conn.setopt(pycurl.POSTFIELDS, urllib.parse.urlencode(POST_PARAMS))
self.conn.setopt(pycurl.HTTPHEADER, ['Host: stream.twitter.com',
'Authorization: %s' % self.get_oauth_header()])
self.conn.setopt(pycurl.LOCALPORT, int(os.environ.get('PORT')))
self.conn.setopt(pycurl.VERBOSE, 1)
self.conn.setopt(pycurl.DEBUGFUNCTION, self.collect_debug_info)
# self.handle_tweet is the method that is called when new tweets arrive
self.conn.setopt(pycurl.WRITEFUNCTION, self.handle_tweet)
print('Port var: %s' % os.environ.get('PORT'))
collect_debug_info
返回的文字为debug(0): b'Local port: 19379\n'
print('Port var: %s' % os.environ.get('PORT'))
返回的文字为Port var: 19379
我的Procfile如下:
web: python3 "twitter streaming data.py"
" twitter streaming data.py"包含我发布的代码以及其他代码。