我正在使用Flask框架和python制作一个web应用程序,我想让web能够上传csv,而不用保存和显示我制作的模板中的数据,我已经添加了上传和处理数据的语法,直到它在一个表视图中,但在运行网站后,它进入404未找到错误信息,我该如何修复它?我已经在www.example.com中制作了一个代码main.py
from datetime import datetime
from flask import Flask, render_template, request, session
from FlaskWebProject2 import app
import os
import pandas as pd
from werkzeug.utils import secure_filename
#*** Flask configuration
UPLOAD_FOLDER = os.path.join('staticFiles', 'uploads')
ALLOWED_EXTENSIONS = {'csv'}
app = Flask(__name__, template_folder='templateFiles', static_folder='staticFiles')
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
app.secret_key = 'This is your secret key to utilize session in Flask'
@app.route('/')
def index():
return render_template('index.html')
@app.route('/upload', methods=['POST', 'GET'])
def uploadFile():
if request.method == 'POST':
# upload file flask
uploaded_df = request.files['uploaded-file']
# Extracting uploaded data file name
data_filename = secure_filename(uploaded_df.filename)
# flask upload file to database (defined uploaded folder in static path)
uploaded_df.save(os.path.join(app.config['UPLOAD_FOLDER'], data_filename))
# Storing uploaded file path in flask session
session['uploaded_data_file_path'] = os.path.join(app.config['UPLOAD_FOLDER'], data_filename)
return render_template('index_upload_and_show_data_page2.html')
@app.route('/show_data')
def showData():
# Retrieving uploaded file path from session
data_file_path = session.get('uploaded_data_file_path', None)
# read csv file in python flask (reading uploaded csv file from uploaded server location)
uploaded_df = pd.read_csv(data_file_path)
# pandas dataframe to html table flask
uploaded_df_html = uploaded_df.to_html()
return render_template('show_csv_data.html', data_var = uploaded_df_html)
我想网站可以显示主页和上传,阅读和显示csv数据正常工作
1条答案
按热度按时间3bygqnnd1#
如果您正在请求
/upload
并得到404,这是很自然的。您已经为/upload
端点添加了一个处理程序:但是
uploadFile
只支持POST
请求。当您在浏览器中输入localhost/upload
时,浏览器会向Web服务器发送一个GET
请求。有两种解决方案可以获得相同的结果:1.将另一个
if
添加到uploadFile
函数,并检查传入请求是否为GET
,如果是,则显示一个页面(例如,用于上传文件的表单)。1.编写另一个类似
upload_file_form
的函数,专门用于GET
请求以显示表单。P.S.:根据PEP8,您应该使用
camel_case
作为函数名称。例如,upload_file
而不是uploadFile