2013-07-30 42 views
0

我有一個腳本,消耗twitter的流api到我的本地主機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

這裏有一個指南,得到的Python建立在Heroku:

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

和你的代碼連接到您的MongoLab數據庫,所有你需要做的就是通過URI您MongoClient對象。如果您使用的MongoLab附加Heroku上通過,URI爲界,你在環境變量:

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

您應該能夠使用os.getenv()來得到它:

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

此外,請確保您使用正確的數據庫名稱(不要使用「測試」)。數據庫的名稱將顯示在最後一個斜槓'/'後面的URI的末尾。最後,你應該結束了,像這樣:

self.db = pymongo.MongoClient(os.getenv("MONGOLAB_URI")).heroku_appXXXXXXX 
相關問題