Heroku Postgres + Python:连接错误过多

时间:2019-12-18 05:07:44

标签: python postgresql heroku flask sqlalchemy

我正在尝试构建应用程序,以在Flask的Twitter上获取已保存的用户时间轴推文。但是会发生此错误。

  

sqlalchemy.exc.OperationalError:(psycopg2.OperationalError)严重:角色“ xxxxxxxxxxxx”的连接太多

该程序正在我的本地服务器/环境上运行,但是当我在Heroku上托管它时,它会中断。

app / __ init __。py

# Initialized app
app = Flask(__name__, instance_relative_config=True)
configure_app(app)

# Initialized database
db = SQLAlchemy(app)
migrate = Migrate(app, db)
db.init_app(app)

# Get timeline tweet
import main.get_tweet

app / get_tweet.py

from flask import current_app
from requests_oauthlib import OAuth1Session
from apscheduler.schedulers.background import BackgroundScheduler

from main.database import save_tweet

import tweepy

def get_current_tweet():
    client_id = current_app.config['TWITTER_CLIENT_ID']
    client_secret = current_app.config['TWITTER_CLIENT_SECRET']

    base_url = 'https://api.twitter.com/'
    user_timeline_url = base_url + 'statuses/user_timeline'

    users = fetch_users()    
    for user in users:
        try:
            twitter_profile = user.twitter_profile_info()

            oauth_token = twitter_profile.access_token
            oauth_verifier = twitter_profile.access_secret

            auth = tweepy.OAuthHandler(client_id, client_secret)
            auth.set_access_token(oauth_token, oauth_verifier)

            api = tweepy.API(auth)
            user_tweets=api.user_timeline(screen_name=twitter_profile.screen_name, count=1, exclude_replies=False, include_rts=False)

            status = user_tweets[0]._json
            save_tweet(status, user)
        except:
            print(user.name + " has been errored.")

sched = BackgroundScheduler(standalone=True,coalesce=True)
sched.add_job(get_current_tweet, 'interval', minutes=10)
sched.start()

app / database.py

def update_or_create_current_tweet(request, user):
    twitter_profile = user.twitter_profile_info()
    uid = request['id']
    url =  "https://twitter.com/" + twitter_profile.screen_name + "/status/" + str(uid)
    content = request['text']
    tweet = Tweet(
       uid=uid,
       user_id=user.id,
       url=url,
       content=content
    )
    db.session.add(tweet)
    db.session.commit()
    return current_tweet

0 个答案:

没有答案