3

I am trying to deploy a simple flask application to Heroku, it is working fine locally, but when deploying to Heroku I get this error:

2016-05-05T18:39:24.897207+00:00 heroku[router]: at=error code=H10 
desc="App crashed" method=GET path="/favicon.ico" host=read-
laterr.herokuapp.com request_id=2ab420c2-64df-4544-9aaf-675ae5f5abfa 
fwd="87.56.186.149" dyno= connect= service= status=503 bytes=

I know it comes because my web dyno crashes, but I just don't know why it crashes.

Here is my Procfile:

web: gunicorn app:app

If I just deploy a single hello app it works but not if I deploy the code below in app.py:

And my app.py:

from __future__ import absolute_import, print_function
from tweepy import StreamListener
from tweepy import OAuthHandler
from tweepy import Stream
import os
import json
import time
from flask import Flask, render_template

app = Flask(__name__)


@app.route("/")
def index():
    return render_template("index.html", articles=sorted(articles, key=lambda article: article["liked_on"], reverse=True))


consumer_key="xxxkeyxxx"
consumer_secret="xxxsecretxxx"
access_token="xxxtokenxxx"
access_token_secret="xxxtokensecretxxx"

articles = []

class LikedTweetsListener(StreamListener):
    def on_data(self, data):
        tweet = json.loads(data)
        if 'event' in tweet and tweet['event'] == "favorite":
            liked_tweet = tweet["target_object"]
            liked_tweet_text = liked_tweet["text"]
            story_url = extract_url(liked_tweet)
            if story_url:
                article = extract_article(story_url)
                if article:
                    article['story_url'] = story_url
                    article['liked_on'] = time.time()
                    articles.append(article)
        return True

    def on_error(self, status):
        print("Error status received : {0}".format(status))


def extract_url(liked_tweet):
    url_entities = liked_tweet["entities"]["urls"]
    if url_entities and len(url_entities) > 0:
        return url_entities[0]['expanded_url']
    else:
        return None


from newspaper import Article

def extract_article(story_url):
    article = Article(story_url)
    article.download()
    article.parse()
    title = article.title
    img = article.top_image
    publish_date = article.publish_date
    text = article.text.split('\n\n')[0] if article.text else ""
    return {
        'title':title,
        'img':img,
        'publish_date':publish_date,
        'text':text.encode('ascii','ignore')
    }


if __name__ == '__main__':
    l = LikedTweetsListener()
    auth = OAuthHandler(consumer_key, consumer_secret)
    auth.set_access_token(access_token, access_token_secret)

    stream = Stream(auth, l)
    stream.userstream(async=True)

    port = int(os.environ.get('PORT', 33507))
    app.run(host='0.0.0.0', port=port)

Any help would be much appreciated!

Anker Bach Ryhl
  • 107
  • 2
  • 10
  • None of the code inside the `__name__ == '__main__'` block will be run on Heroku; I doubt you want all of that in there. Really it should just have the last two lines there, everything else should be at the top level. – Daniel Roseman May 06 '16 at 14:10
  • My ProcFile is as follows: `web: python server.py -p $PORT` where server.py is starting the flask app. Then again I'm wrapping Flask in a Tornado HTTP server and not Gunicorn. – Terran May 06 '16 at 14:28
  • @Terran What is your server.py looking like? – Anker Bach Ryhl May 06 '16 at 14:30
  • @DanielRoseman Thanks but the web dyno still crashes. – Anker Bach Ryhl May 06 '16 at 14:41
  • @AnkerBachRyhl My server.py: https://github.com/geometalab/OSMTagFinder/blob/master/OSMTagFinder/server.py Only the last 4 lines of `runFlaskApp` method should be of interest. Sorry for my non-pythonic Python. – Terran May 06 '16 at 15:43
  • @Terran Now I have made a server.py looking like this: from tornado.wsgi import WSGIContainer from tornado.httpserver import HTTPServer from tornado.ioloop import IOLoop def runFlaskApp () : tagFinderPort = int(os.environ.get("PORT", cl.getWebsiteInt('PORT'))) http_server = HTTPServer(WSGIContainer(app)) http_server.listen(port=tagFinderPort) IOLoop.instance().start() And a Procfile looking like this: web: python server.py -p $PORT But the web dyno still crashes... – Anker Bach Ryhl May 06 '16 at 16:01
  • @AnkerBachRyhl Uhh you can't just copy the code like that. Try host 0.0.0.0 and port 5000 for example. You don't have to use my configloader cl for instance. No wonder it crashes. Try with a simple hello world flask app first, that runs locally and then try to deploy it on heroku. – Terran May 06 '16 at 16:30
  • @Terran I'm sorry I am still pretty new to python :( I don't quite understand how I should make my server.py and the last bit of code in app.py. Can you maybe give an exampel? I am very glad your want to help me ;) – Anker Bach Ryhl May 06 '16 at 16:57
  • @Terran Just ignore the last comment ;) I tried to push a simple hello world flask app up and it worked! But my old script still not work do you know why? – Anker Bach Ryhl May 06 '16 at 18:10
  • @AnkerBachRyhl Sorry, idk. Maybe heroku logs the exact error. Try to view it with the "heroku logs" command or else use "heroku run bash" to look at the logfiles. – Terran May 06 '16 at 18:16
  • @Terran when running python app.py inside the heroku bash I get this error: File "app.py", line 53, in from newspaper import Article File "/app/.heroku/miniconda/lib/python2.7/site-packages/newspaper/__init__.py", line 10, in from .article import Article, ArticleException File "/app/.heroku/miniconda/lib/python2.7/site-packages/newspaper/article.py", line 12, in from . import images File "/app/.heroku/miniconda/lib/python2.7/site-packages/newspaper/images.py", line 15, in import urllib.request ImportError: No module named request – Anker Bach Ryhl May 06 '16 at 18:23
  • @AnkerBachRyhl Ahh you need to install all dependencies on Heroku too. Same as you installed them on your local machine. Maybe you're using pip? If so you can create a requirements.txt with the command `pip freeze > requirements.txt` and put the txt file it into your app directory. Heroku should recognize it and install it. (Maybe you need to install pip on Heroku first, I'm not sure on that anymore) – Terran May 06 '16 at 18:29
  • @Terran I had done that already ;) But it seems like the pip package newspaper3k doesn't work... Do you maybe know why? Or how to solve it? – Anker Bach Ryhl May 06 '16 at 18:38

0 Answers0