如何运行我的脚本远程存储数据库中的数据?

时间:2013-07-30 12:49:08

标签: python heroku pymongo mlab

我有一个脚本,它将Twitter的流式api中的推文用于我的localhost mongodb。为了提高正常运行时间,我想远程运行,将推文存储在“类似云的数据库”中,例如MongoLab。

这是我的剧本:

import json
import pymongo
import tweepy

consumer_key = ""
consumer_secret = ""
access_key = ""
access_secret = ""

auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_key, access_secret)
api = tweepy.API(auth)


class CustomStreamListener(tweepy.StreamListener):
    def __init__(self, api):
        self.api = api
        super(tweepy.StreamListener, self).__init__()

        self.db = pymongo.MongoClient().test

    def on_data(self, tweet):
        self.db.tweets.insert(json.loads(tweet))

    def on_error(self, status_code):
        return True # Don't kill the stream

    def on_timeout(self):
        return True # Don't kill the stream


sapi = tweepy.streaming.Stream(auth, CustomStreamListener(api))
sapi.filter(track=['Gandolfini'])

现在,我已经使用MongoLab和Heroku建立了帐户,但我完全陷入困境(我对所有编程都很陌生)。我想,推动事情向前发展,我需要解决两个问题:i)如何使用Heroku托管我的脚本? ii)如何将在Heroku中运行的脚本指向我的Mongolab帐户?有什么想法吗?

2 个答案:

答案 0 :(得分:2)

以下是在Heroku上设置Python的指南:

https://devcenter.heroku.com/articles/python

要将代码连接到MongoLab数据库,您只需将URI传递给MongoClient对象即可。如果您通过Heroku使用MongoLab插件,则URI将在环境变量中绑定:

https://devcenter.heroku.com/articles/mongolab#getting-your-connection-uri

你应该可以使用os.getenv()来获取它:

http://docs.python.org/2/library/os.html#os.getenv

另外,请确保使用正确的数据库名称(不要使用“test”)。数据库的名称将显示在最后一个斜杠“/”后面的URI的末尾。最后,你应该得到这样的结论:

self.db = pymongo.MongoClient(os.getenv("MONGOLAB_URI")).heroku_appXXXXXXX

答案 1 :(得分:0)

请注意,此时从Heroku调用Twitter API会导致基于Twitter IP地址的速率限制出现问题。基本上,您的应用程序将与其他Heroku应用程序共享IP地址,这些应用程序也可以向Twitter发送请求,Twitter可以将共享IP地址列入黑名单。有关详细信息,请参阅这两个问题:

Twitter Rate Limits for Site hosted on Heroku

(twitter) Authentication failure! timeout: Net::OpenTimeout, execution expired