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

阿曼

我使用 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
jz22

将此添加到您的代码中:

import os

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

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

如何从 Flask Web 服务器中运行 Python 程序?

来自分类Dev

运行Python Web服务器

来自分类Dev

在 python 中使用 gevent 的静态 Web 服务器演示

来自分类Dev

如何使用socketio运行flask服务器?

来自分类Dev

使用python的Web服务器

来自分类Dev

使用可移植的本地Web服务器运行Web服务器

来自分类Dev

使用Flask将请求发布到Web服务器

来自分类Dev

使用Flask在Web服务器上部署Tensorflow

来自分类Dev

在Tornado Web服务器中运行Python脚本

来自分类Dev

如何与Web服务器协作运行python程序?

来自分类Dev

在Tornado Web服务器中运行Python脚本

来自分类Dev

如何在Web服务器上运行python脚本?

来自分类Dev

Django和Flask是否需要单独的Web服务器来运行Web应用程序?

来自分类Dev

运行 Flask Web 服务器是否会阻止 Node.JS 中的 Web 抓取?

来自分类Dev

如何使用apache从Web服务器运行bash脚本?

来自分类Dev

使用最新更改运行Nginx Web服务器

来自分类Dev

当前使用uWSGI Web服务器的Flask Web应用程序迁移到ASGI Web服务器(uvicorn)

来自分类Dev

无需复杂的Web服务器即可在本地运行Production Flask应用

来自分类Dev

无需复杂的Web服务器即可在本地运行Production Flask应用

来自分类Dev

在 Python 中使用 Flask 时出现“未知的 MySQL 服务器主机”

来自分类Dev

使用python simpleHTTP服务器保持服务器正常运行

来自分类Dev

使用数据库连接将代码部署到Azure Web时,Flask应用程序无法呈现,但是在本地服务器上运行良好

来自分类Dev

使用PHP从Apache服务器运行Python脚本

来自分类Dev

使用服务器操作运行 python 代码时出错

来自分类Dev

在Python 3.6中运行Flask开发服务器会引发SocketServer和ForkingMixIn的ImportError

来自分类Dev

Python 3.4上的Flask Bug?如果应用包含相对导入,则开发服务器无法运行

来自分类Dev

将带有服务员服务器的 Python Flask 设为 Windows 服务时无法运行

来自分类Dev

Python Flask - 如何使用 Flask 启动 python 服务器并使用多个参数多次执行它

来自分类Dev

在python中使用套接字编写代理Web服务器

Related 相关文章

  1. 1

    如何从 Flask Web 服务器中运行 Python 程序?

  2. 2

    运行Python Web服务器

  3. 3

    在 python 中使用 gevent 的静态 Web 服务器演示

  4. 4

    如何使用socketio运行flask服务器?

  5. 5

    使用python的Web服务器

  6. 6

    使用可移植的本地Web服务器运行Web服务器

  7. 7

    使用Flask将请求发布到Web服务器

  8. 8

    使用Flask在Web服务器上部署Tensorflow

  9. 9

    在Tornado Web服务器中运行Python脚本

  10. 10

    如何与Web服务器协作运行python程序?

  11. 11

    在Tornado Web服务器中运行Python脚本

  12. 12

    如何在Web服务器上运行python脚本?

  13. 13

    Django和Flask是否需要单独的Web服务器来运行Web应用程序?

  14. 14

    运行 Flask Web 服务器是否会阻止 Node.JS 中的 Web 抓取?

  15. 15

    如何使用apache从Web服务器运行bash脚本?

  16. 16

    使用最新更改运行Nginx Web服务器

  17. 17

    当前使用uWSGI Web服务器的Flask Web应用程序迁移到ASGI Web服务器(uvicorn)

  18. 18

    无需复杂的Web服务器即可在本地运行Production Flask应用

  19. 19

    无需复杂的Web服务器即可在本地运行Production Flask应用

  20. 20

    在 Python 中使用 Flask 时出现“未知的 MySQL 服务器主机”

  21. 21

    使用python simpleHTTP服务器保持服务器正常运行

  22. 22

    使用数据库连接将代码部署到Azure Web时,Flask应用程序无法呈现,但是在本地服务器上运行良好

  23. 23

    使用PHP从Apache服务器运行Python脚本

  24. 24

    使用服务器操作运行 python 代码时出错

  25. 25

    在Python 3.6中运行Flask开发服务器会引发SocketServer和ForkingMixIn的ImportError

  26. 26

    Python 3.4上的Flask Bug?如果应用包含相对导入,则开发服务器无法运行

  27. 27

    将带有服务员服务器的 Python Flask 设为 Windows 服务时无法运行

  28. 28

    Python Flask - 如何使用 Flask 启动 python 服务器并使用多个参数多次执行它

  29. 29

    在python中使用套接字编写代理Web服务器

热门标签

归档