繁体   English   中英

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

[英]Run a web server using Flask in python

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

将此添加到您的代码中:

import os

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

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

导入必要的库

from flask import Flask, render_template, request

import numpy as np
import os

from keras.preprocessing.image import load_img
from keras.preprocessing.image import img_to_array
from keras.models import load_model

# load model
model = load_model(r"model/covid_detection.h5")

print('Model loaded successfully')


def pred_cot_dieas(cott_plant):
    test_image = load_img(cott_plant, target_size=(256, 256))  # load image
    print("Image loaded successfully for prediction")

    test_image = img_to_array(test_image) / 255  # convert image to np array and normalize
    test_image = np.expand_dims(test_image, axis=0)  # change dimention 3D to 4D

    result = model.predict(test_image).round(3)  # predict diseased palnt or not
    print('Prediction result = ', result)

    pred = np.argmax(result)  # get the index of max value

    if pred == 0:
        return "Positive", 'covid19.html'  # if index 0 burned leaf
    elif pred == 1:
        return 'Normal', 'normal.html'  # # if index 1
    # elif pred == 2:
    #     return 'Healthy Cotton Plant', 'healthy_plant.html'  # if index 2  fresh leaf
    else:
        return "Pneumonia", 'pneumonia.html'  # if index 3

# 


# Create flask instance
app = Flask(__name__)


# render index.html page
@app.route("/", methods=['GET', 'POST'])
def home():
    return render_template('index.html')


# get input image from client then predict class and render respective .html page for solution
@app.route("/predict", methods=['GET', 'POST'])
def predict():
    if request.method == 'POST':
        file = request.files['image']  # fet input
        filename = file.filename
        print("Input posted = ", filename)

        file_path = os.path.join('static/user upload', filename)
        file.save(file_path)

        print("Predicting class......")
        pred, output_page = pred_cot_dieas(cott_plant=file_path)

        return render_template(output_page, pred_output=pred, user_image=file_path)


# For local system & cloud
if __name__ == "__main__":
    app.run(threaded=False)

希望这可以帮助

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM