在python中使用Flask运行Web服务器

时间:2017-07-29 03:51:50

标签: python flask webserver

我使用Cloud9 IDE并使用默认Web服务器。但是代码没有启动服务器(Web服务器返回:没有应用程序似乎在这里运行!)。 我仔细检查了代码的每个实例,但我在Flask中很弱。 Flask代码是分发代码的一部分。

代码: 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(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 个答案:

答案 0 :(得分:2)

将此添加到您的代码中:

import os

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

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