Tweepy脚本影响MongoDB服务关闭。

11 浏览
0 Comments

Tweepy脚本影响MongoDB服务关闭。

我有以下的Python脚本,使用Tweepy获取tweets,并使用PyMongo将它们存储到MongoDB中。问题是每当我运行这个脚本时,我的MongoDB实例会关闭,并且脚本会停止并显示错误。我不知道为什么会发生这种情况,因为即使脚本终止或Tweepy遇到错误,也不应该影响MongoDB的运行状态。这行代码被标识为第一个触发点:stream.filter(locations=[-119.970703, 48.994636, -109.951172, 59.955010])\n脚本:\n

import tweepy, sys, json, traceback
from bson.json_util import loads as json_to_bson
from hashlib import sha1
from datetime import datetime
from pymongo import MongoClient
from time import sleep, strptime, mktime
client = MongoClient()
mode = None
class Stream(tweepy.StreamListener):
    def on_status(self, data):
        save(data)
    def on_error(self, code):
        pause()
def now():
    return str(datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
def pause():
    sys.stdout.flush()
    sleep((60*15)+5)
def save(data):
    bson = json_to_bson(json.dumps(data._json))
    tweet_date = strptime(bson['created_at'], "%a %b %d %H:%M:%S +0000 %Y")
    tweet_date = str(datetime.fromtimestamp(mktime(tweet_date)))
    bson['created_at'] = tweet_date
    bson['text_hash'] = sha1(bson['text'].encode('punycode')).hexdigest()
    bson['collected_at'] = now()
    bson['collection_type'] = mode
    if client.grebe.tweets.find_one({'text_hash': bson['text_hash']}) == None:
        client.grebe.tweets.insert_one(bson)
def api():
    CONSUMER_KEY = 'key'
    CONSUMER_SECRET = 'secret'
    ACCESS_TOKEN_KEY = 'tokenkey'
    ACCESS_TOKEN_SECRET = 'tokensecret'
    auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
    auth.set_access_token(ACCESS_TOKEN_KEY, ACCESS_TOKEN_SECRET)
    return tweepy.API(auth)
def main():
    mystream = Stream()
    stream = tweepy.Stream(api().auth, mystream)
    stream.filter(locations=[-119.970703, 48.994636, -109.951172, 59.955010])
main()

\n错误:\n

File "/usr/local/lib/python2.7/dist-packages/tweepy/streaming.py", line 445, in filter 
    self._start(async)
File "/usr/local/lib/python2.7/dist-packages/tweepy/streaming.py", line 361, in _start 
    self._run()
File "/usr/local/lib/python2.7/dist-packages/tweepy/streaming.py", line 294, in _run
    raise exception
AutoReconnect: connection closed

0
0 Comments

这个问题的原因可能是MongoDB锁的权限问题。根据以下答案提供的解决方法解决了这个问题:https://stackoverflow.com/a/15982017/863923

根据这个答案,可以使用以下步骤解决问题:

1. 打开终端或命令提示符。

2. 输入以下命令以进入MongoDB shell:mongo

3. 输入以下命令以切换到admin数据库:use admin

4. 输入以下命令创建一个新的用户:db.createUser({user: "your_username", pwd: "your_password", roles: [{role: "root", db: "admin"}]})

5. 将"your_username"替换为您要创建的用户名,并将"your_password"替换为您要设置的密码。

6. 退出MongoDB shell:exit

7. 重新启动MongoDB服务。

通过按照上述步骤创建新用户并重新启动MongoDB服务,可以解决Tweepy脚本影响MongoDB服务关闭的问题。

0