2017-07-29 8 views
0

私はCloud9 IDEを使用し、デフォルトWebサーバーを使用します。しかし、コードはサーバーを起動しません(Webサーバーが戻る:アプリケーションはここでは実行されていないようです!)。 私はコードのすべてのインスタンスをダブルチェックしましたが、私はFlaskで弱いです。フラスココードは配布コードの一部でした。PythonでFlaskを使ってWebサーバーを実行します。

コード: application.py(つまり、サーバを起動しなければならない)

from flask import Flask, redirect, render_template, request, url_for 

import sys, helpers 
from analyzer import Analyzer 

app = Flask(__name__) 

@app.route("/") 
def index(): 
    return render_template("index.html") 

@app.route("/search") 
def search(): 

    # validate screen_name 
    screen_name = request.args.get("screen_name", "") 
    if not screen_name: 
     return redirect(url_for("index")) 

    # get screen_name's tweets 
    tweets = helpers.get_user_timeline(screen_name) 

    # pass to analyze 
    analyzer = Analyzer("positive-words.txt", "negative-words.txt") 

    positive, negative, neutral = analyzer.analyze(tweets) 

    # generate chart 
    chart = helpers.chart(positive, negative, neutral) 

    # render results 
    return render_template("search.html", chart=chart, screen_name=screen_name) 

helpers.py(application.pyによって使用される方法):使用

import html 
import os 
import plotly 
import socket 

from twython import Twython 
from twython import TwythonAuthError, TwythonError, TwythonRateLimitError 

def chart(positive, negative, neutral): 
    """Return a pie chart for specified sentiments as HTML.""" 

    # offline plot 
    # https://plot.ly/python/pie-charts/ 
    # https://plot.ly/python/reference/#pie 
    figure = { 
     "data": [ 
      { 
       "labels": ["positive", "negative", "neutral"], 
       "hoverinfo": "none", 
       "marker": { 
        "colors": [ 
         "rgb(0,255,00)", 
         "rgb(255,0,0)", 
         "rgb(255,255,0)" 
        ] 
       }, 
       "type": "pie", 
       "values": [positive, negative, neutral] 
      } 
     ], 
     "layout": { 
      "showlegend": True 
      } 
    } 
    return plotly.offline.plot(figure, output_type="div", show_link=False, link_text=False) 

def get_user_timeline(screen_name, count=200): 
    """Return list of most recent tweets posted by screen_name.""" 

    # ensure count is valid 
    if count < 1 or count > 200: 
     raise RuntimeError("invalid count") 

    # ensure environment variables are set 
    if not os.environ.get("API_KEY"): 
     raise RuntimeError("API_KEY not set") 
    if not os.environ.get("API_SECRET"): 
     raise RuntimeError("API_SECRET not set") 

    # get screen_name's (or @screen_name's) most recent tweets 
    # https://dev.twitter.com/rest/reference/get/users/lookup 
    # https://dev.twitter.com/rest/reference/get/statuses/user_timeline 
    # https://github.com/ryanmcgrath/twython/blob/master/twython/endpoints.py 
    try: 
     twitter = Twython(os.environ.get("API_KEY"), os.environ.get("API_SECRET")) 
     user = twitter.lookup_user(screen_name=screen_name.lstrip("@")) 
     if user[0]["protected"]: 
      return None 
     tweets = twitter.get_user_timeline(screen_name=screen_name, count=count) 
     return [html.unescape(tweet["text"].replace("\n", " ")) for tweet in tweets] 
    except TwythonAuthError: 
     raise RuntimeError("invalid API_KEY and/or API_SECRET") from None 
    except TwythonRateLimitError: 
     raise RuntimeError("you've hit a rate limit") from None 
    except TwythonError: 
     return None 

analyzer.py(方法by application.py):

# Tokenizing library 
import nltk 

class Analyzer(): 
    # Defining template for the class with two arguments(file names are not hard coded) 
    def __init__(self, positives, negatives): 
     # Two dicts for - and + words 
     self.positives = {} 
     self.negatives = {} 
     # Method for reading files into dicts 
     def open_file (file_name, dictionary_name): 
      with open(file_name) as f: 
       # Loop to start with 35th line 
       for i in range(35): 
        next(f) 
       for line in f: 
        # Keys and values of a dict 
        dictionary_name[line.strip()] = line.strip() 
     # Calling methods 
     open_file(positives, self.positives) 
     open_file(negatives, self.negatives) 
    # Analyse tokens 
    def analyze(self, text): 
     # Access tools of nltk 
     tokenizer = nltk.tokenize.TweetTokenizer() 
     # Defining couning score variable 
     score_positive = 0 
     score_negative = 0 
     score_neutral = 0 
     # since the text is a list we itterate of the list element by element 
     for tweet in text: 
      tokens = tokenizer.tokenize(tweet) 
      # Checking each token 
      for token in tokens: 
       if token.lower() in self.positives: 
        score_positive += 1 
       elif token.lower() in self.negatives: 
        score_negative += 1 
       else: 
        score_neutral += 1 
     return score_positive, score_negative, score_neutral 

答えて

1

import os 

port = int(os.getenv("PORT")) 

if __name__ == '__main__': 
    app.run(host='0.0.0.0', port=port, debug=True) 
+0

ありがとうございます!どのようにしてもわかりません。少なくとも私は今、ヒントを持っています。非常に便利。 – Arman

+0

正しいポートにアプリケーションを公開する必要があります。そうしないと、アプリケーションにアクセスできなくなります。 app.run()をローカルで起動するだけで動作します。私のようにポートを初期化するのではなく、アプリケーションが使用しているポートをチェックしてハードコードすることもできます。 – user3080315

+0

今、それはクリアです、ありがとうたくさんのuser3080315! – Arman

関連する問題