I got an error when I open the website with 127.0.0.1:5000 and the program will show the 404 error and when I check the server it showed "The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again." I cannot solve it. Can show me any response to solve it? Here is the error response:
* 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 -
And here is my code of 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)
Also I found same problem in other program and here is the code:
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)
Template index.html code:
<!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>
If we analyse:
127.0.0.1 - - [14/Jun/2020 14:46:15] "GET /drawplot HTTP/1.1" 404 -
That means it is not finding the url /drawplot
Your second example has only this route
@app.route('/', methods=["GET", "POST"])
and your first example:
@app.route('/')
@app.route('/', methods=['GET','POST'])
You don't have a '/drawplot' route
If you have like
@app.route('/drawplot')
the error will go away.
However, if your aim is to actually return the file, first save the file in a folder and use the send_from_directory function
Don't get me wrong but i get the impression that you need to get better acquainted with Flask. I suggest you complete one or two tutorials.
For example, your submit button should be in a <form></form>
tag, or use a click listener to make an AJAX request.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.