繁体   English   中英

在服务器上找不到请求的 URL。 如果您手动输入了 URL,请检查您的拼写并重试。 404

[英]The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again. 404

当我打开带有 127.0.0.1:5000 的网站时出现错误,程序将显示 404 错误,当我检查服务器时,它显示“在服务器上找不到请求的 URL。如果您手动输入 URL,请检查你的拼写,然后再试一次。” 我无法解决它。 可以告诉我任何回应来解决它吗? 这是错误响应:

* Serving Flask app "writecsvfile" (lazy loading)

127.0.0.1 - - [14/Jun/2020 14:46:15] "GET / HTTP/1.1" 200 -
127.0.0.1 - - [14/Jun/2020 14:46:15] "GET /drawplot HTTP/1.1" 404 -

这是我的 python 代码:

from flask import Flask, render_template, request, Response
import csv

app = Flask(__name__)

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

@app.route('/', methods=['GET','POST'])
def save_comment():
    if request.method == ['POST']:
        school = request.form['school']
        sex = request.form['sex']
        age = request.form['age']
        address = request.form['address']
        famsize = request.form['famsize']
        pstatus = request.form['Pstatus']
        Medu = request.form['Medu']
        Fedu = request.form['Fedu']
        Mjob = request.form['Mjob']
        Fjob = request.form['Fjob']
        reason = request.form['reason']
        guardian = request.form['guardian']
        traveltime = request.form['traveltime']
        studytime = request.form['studytime']
        failure = request.form['failure']
        schoolsup = request.form['schoolsup']
        famsup = request.form['famsup']
        paid = request.form['paid']
        activities = request.form['activities']
        nursery = request.form['nursery']
        higher = request.form['higher']
        internet = request.form['internet']
        romantic = request.form['romantic']
        famrel = request.form['famrel']
        freetime = request.form['freetime']
        goout = request.form['goout']
        Dalc = request.form['Dalc']
        Walc = request.form['Walc']
        health = request.form['health']
        absences = request.form['absences']
        G1 = request.form['G1']
        G2 = request.form['G2']
        G3 = request.form['G3']
        fieldNames = ['school', 'sex', 'age', 'address','famsize', 'Pstatus','Medu','Fedu', 'reason','guardian','traveltime','studytime','failure','schoolsup','famsup','paid','activities','nursery','higher','internet','romantic','famrel','freetime','goout','Dalc','Walc','health','absences','G1','G2','G3']
        with open('/example.data','w') as inFile:
            writer = csv.DictWriter(inFile, fieldnames = fieldNames)
            writer.writerow({'school':school, 'sex':sex, 'age':age, 'address':address,'famsize':famsize, 'Pstatus':pstatus,'Medu':Medu,'Fedu':Fedu, 'reason':reason,'guardian':guardian,'traveltime':traveltime,'studytime':studytime,'failure':failure,'schoolsup':schoolsup,'famsup':famsup,'paid':paid,'activities':activities,'nursery':nursery,'higher':higher,'internet':internet,'romantic':romantic,'famrel':famrel,'freetime':freetime,'goout':goout,'Dalc':Dalc,'Walc':Walc,'health':health,'absences':absences,'G1':G1,'G2':G2,'G3':G3})
    return "enter data ..."

if __name__ == '__main__':
    app.run(debug=True)

我也在其他程序中发现了同样的问题,代码如下:

import matplotlib.pyplot as plt
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.neighbors import KNeighborsClassifier
from sklearn.metrics import classification_report, confusion_matrix
import numpy as np
from flask import Flask,render_template,redirect,url_for
import json, random


classifier = KNeighborsClassifier(n_neighbors=5)  # default n=5

error = []
def train():
    data = pd.read_csv(r"example.data")
    print(data.head())  # print first 5 column of data
    print(data.tail())
    columns = ["sex", "age", "address", "famsize", "Pstatus", "Medu", "Fedu", "Mjob", "Fjob", "reason", "guardian",
               "traveltime", "studytime", "failures", "schoolsup", "famsup", "paid", "activities", "nursery", "higher",
               "internet", "romantic", "famrel", "freetime", "goout", "Dalc", "Walc", "health", "absences"]

    data.drop(columns, inplace=True,
              axis=1)  # drop specified labels from rows or columns, return nothing and the dataframe is now updated
    y = data.iloc[:, 0].values  # first column of data frame
    X = data.iloc[:, [1, 2, 3]].values  # all columns of data frame with 2nd, 3rd, 4th rows

    X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.15)  # customed get train,test data

    scaler = StandardScaler()  # transform data will have a mean value 0 and standard deviation of 1
    scaler.fit(X_train)

    X_train = scaler.transform(X_train)  # make x_train standard
    X_test = scaler.transform(X_test)

    classifier.fit(X_train, y_train)
    acc = classifier.score(X_test, y_test)  # make a accuracy score
    print("Accuracy is {}%".format(round((acc * 100), 2)))

    y_pred = classifier.predict(X_test)  # make a prediction
    print("Generating confusion matrix and report....")
    print(confusion_matrix(y_test, y_pred))
    print(classification_report(y_test, y_pred))



    # Calculating error for K values between 1 and 40
    for i in range(1, 40):
        knn = KNeighborsClassifier(n_neighbors=i)
        knn.fit(X_train, y_train)
        pred_i = knn.predict(X_test)
        error.append(np.mean(pred_i != y_test))




def prediction(input1, input2, input3, input4):
    X = [input1, input2, input3, input4]

    classifier.predict(X)


train()  # Function Calll


def drawplot():
    plt.figure(figsize=(12, 6))
    plt.plot(range(1, 40), error, color='red', linestyle='dashed', marker='o',
             markerfacecolor='blue', markersize=10)
    plt.title('Error Rate K Value')
    plt.xlabel('K Value')
    plt.ylabel('Mean Error')
    plt.show()

drawplot()



app = Flask(__name__)


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


if __name__ == '__main__':
    app.run(debug=True)

模板索引.html代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Student Statistics...</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/chartist.js/latest/chartist.min.css">
    <script src="https://cdn.jsdelivr.net/chartist.js/latest/chartist.min.js"></script>

    <!-- Bootstraps Java Scipts Links -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
    <script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>



    <!-- JQuery links  -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>


</head>
<body>
<h2>...Enter Student Information detail...</h2>
<div class="ct-chart ct-perfect-fourth"> Graph</div>

<script>
    class MyCharts{
        constructor(xData, YData, width, height, title)
        {
            this.XData = XData;
            this.YData = YData;
            this.width = width;
            this.height= height;
            this.title = title;
        }
        createGraph()
        {
            var plotdata =
                {
                    labels: this.XData,
                    series:[
                        this.YData
                    ]
                }

             var options = {
                width:this.width,
                 height:this.height,
                 axisX:{
                    showGrid:true,
                     showLabel:true
                 },
                 axisY:{
                    offset:60
                 }
             };
            new Chartist.Line('.ct-chart', data, options);
        }
    }
    var XData= ['0', '5', '10', '15', '20'];
    var plotdata =$.get('/drawplot')
    var tm = plotdata.done(function (resp) {
        console.log("JSON DATA", resp.drawplot);
        var obj = new MyCharts(XData, resp.drawplot, 500, 500);
        obj.createGraph();
    })
</script>

<table border="1">
<tr>
<th>
<label>School:</label>
</th>
<td>
<input type="text" name="school">
</td>
<th>
<label>Sex:</label>
</th>
<td>
<input type="text" name="sex">
</td>
<th>
<label>Age:</label></th><td>
<input type="text" name="age">
</td>
</tr>
<tr>
<th>
<label>Address:</label></th><td><input type="text" name="Address"></td>
<th>
<label>Guardian</label></th><td><input type="text" name="Guardian">
</td>
<th>
<label>TravelTime</label></th><td><input type="text" name="TravelTime">
</td>
</tr>
<tr>
<th>
<label>Study-Time</label></th><td><input type="text" name="Study-Time">
</td>
<th>
<label>Failure</label></th><td><input type="text" name="Failure">
</td>
<th>
<label>Famsize:</label></th><td><input type="text" name="Famsize">
</td>
</tr>
<th>
<label>Pstatus:</label></th><td><input type="text" name="Pstatus">
</td>
<th>
<label>Medu:</label></th><td><input type="text" name="Medu">
</td>
<th>
<label>Reason:</label></th><td><input type="text" name="Reason">
</td>
</tr>
<tr>
<th>
<label>Schoolsup</label></th><td><input type="text" name="Schoolsup">
</td>
<th>
<label>Famsup</label></th><td><input type="text" name="Famsup">
</td>
<th>
<label>Paid</label></th><td><input type="text" name="Paid">
</td>
</tr>
<tr>
<th>
<label>Activities</label></th><td><input type="text" name="Activities">
</td>
<th>
<label>Nursery</label></th><td><input type="text" name="Nursery">
</td>
<th>
<label>Higher</label></th><td><input type="text" name="Higher">
</td>
</tr>
<th>
<label>Internet</label></th><td><input type="text" name="Internet">
</td>
<th>
<label>Romantic</label></th><td><input type="text" name="Romantic">
</td>
<th>
<label>Famrel</label></th><td><input type="text" name="Famrel">
</td>
</tr>
<tr>
<th>
<label>Free-Time</label></th><td><input type="text" name="Free-Time">
</td>
<th>
<label>Goout</label></th><td><input type="text" name="Goout">
</td>
<th>
<label>Dalc</label></th><td><input type="text" name="Dalc">
</td>
</tr>
<tr>
<th>
<label>Walc</label></th><td><input type="text" name="Walc">
</td>
<th>
<label>Health</label></th><td><input type="text" name="Health">
</td>
<th>
<label>Absences</label></th><td><input type="text" name="Absences">
</td>
</tr>
<tr>
<th>
<label>G1</label></th><td><input type="text" name="G1">
<th>
<label>G2</label></th><td><input type="text" name="G2">
</td>
<th>
<label>G3</label></th><td><input type="text" name="G3">
</td>
</tr>
    <tr>
        <td colspan="6"><input type="submit" name="submit" value="submit"></td>
    </tr>
</table>


</body>
</html>

如果我们分析:

127.0.0.1 - - [14/Jun/2020 14:46:15] "GET /drawplot HTTP/1.1" 404 -

这意味着它没有找到 url /drawplot

你的第二个例子只有这条路线

@app.route('/', methods=["GET", "POST"])

和你的第一个例子:

@app.route('/')
@app.route('/', methods=['GET','POST'])

您没有“/drawplot”路线

如果你有喜欢

@app.route('/drawplot')

错误将 go 消失。

但是,如果您的目标是实际返回文件,请首先将文件保存在文件夹中并使用send_from_directory function

不要误会我的意思,但我觉得您需要更好地了解 Flask。 我建议你完成一两个教程。

例如,您的提交按钮应位于<form></form>标记中,或使用点击侦听器发出 AJAX 请求。

暂无
暂无

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

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