创建了一个Web应用程序,并成功构建了一个功能来清除Google我的商家导出的CSV文件。但是,当我使用编写的代码运行该函数时,会收到以下错误消息:
未找到
在服务器上找不到请求的URL。如果输入URL 手动,请检查您的拼写,然后重试。
不确定我要去哪里哪里
mport os
import pandas as pd
from flask import Flask, request, redirect, url_for
from flask import Flask, make_response
from werkzeug.utils import secure_filename
UPLOAD_FOLDER = './Downloads/gmbreports'
if not os.path.exists(UPLOAD_FOLDER):
os.makedirs(UPLOAD_FOLDER)
ALLOWED_EXTENSIONS = 'csv'
app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
def allowed_file(filename):
return '.' in filename and \
filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
def transform(text_file_contents):
disc = open('clean.csv')
disc2 = open('clean_two.csv','w')
#cleaning up csv
for row in disc:
row = row.strip()
row = row[1:-1]
row = row.replace('""','"')
disc2.write(row+'\n')
disc2.close()
disc.close()
discovery = pd.read_csv('clean_two.csv')
discovery_clean = discovery.iloc[1:]
cols = list(discovery_clean.columns[4:])
discovery_clean[cols] = discovery_clean[cols].apply(pd.to_numeric,errors='coerce')
return discovery_clean
@app.route('/', methods=['GET', 'POST'])
def upload_file():
if request.method == 'POST':
if 'file' not in request.files:
flash('No file part')
return redirect(request.url)
file = request.files['file']
if file.filename == '':
flash('You need to upload a csv file')
return redirect(request.url)
if file and allowed_file(file.filename):
filename = secure_filename(file.filename)
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
return redirect(url_for('uploaded_file',
filename=filename))
return '''
<!doctype html>
<title>Google My Business Discovery Report Builder</title>
<h1>Upload GMB Discovery csv</h1>
<form action="\transform" method="post" enctype="multipart/form-data">
<p><input type="file" name="file">
<input type="submit" value=Upload>
</form>
'''
@app.route('/transform',methods=["POST"])
def transform_view():
request_file=request.files['file']
request_file.save('clean.csv')
if not request_file:
return "No file"
result = transform()
print(result)
response = make_response(result)
response.headers["Content-Disposition"] ="attachment; filename=result.csv"
return response
if __name__=='__main__':
app.run()
注意:运行脚本并上传csv后,我得到此错误消息。理想的结果是上传一个csv,并将其作为清理后的数据表显示在我的屏幕上
答案 0 :(得分:2)
这里有多个问题。首先,Wondercricket关于表单操作是正确的。需要将其更改为“ / transform”。
完成后,您仍然会收到内部服务器错误。在这种情况下,您的transform
函数被定义为采用单个参数,但没有被一个参数调用。只需更改
def transform(text_file_contents):
到
def transform():
这应该允许进行上传,并且转换现在将运行。但是,还有最后一个问题。 transform
返回一个熊猫DataFrame,Flask不能将其用作响应。更改
response = make_response(result)
到
response = make_response(result.to_csv())
你应该很好。