0

Created a web app and have managed to build a function to clean up csv files from Google my Business exports. However when I run the function with the code I have written I get the following error message:

Not Found

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

Not sure where I am going wrong

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()

Note: I get this error message after running the script and uploading a csv. The desired outcome is uploading a csv, and showing it on my screen as a cleaned up data table

9
  • what error message do you get in the terminal where you run the flask server? Commented May 1, 2019 at 13:22
  • @mousahalaseh not sure what you mean, If i run the script and try and upload a csv I get the Not Found error Commented May 1, 2019 at 13:24
  • also, it's a bad design to render HTML directly from your method. use a separate template engine (e.g. Jinja) Commented May 1, 2019 at 13:24
  • how exactly do you run the app? Commented May 1, 2019 at 13:25
  • @mousahalaseh python main.py on bash then I get a page that allows me to upload a csv file, I upload the file and get this error message Commented May 1, 2019 at 13:27

1 Answer 1

2

There are multiple problems here. First, Wondercricket is correct about the form action. It needs to be changed to "/transform".

Once that's done, you're still getting an Internal Server Error. In this case, your transform function is defined as taking a single parameter, but it's not being called with one. Simply change

def transform(text_file_contents):

to

def transform():

That should allow the upload to happen, and the transform will now run. However, there's still one last problem. transform returns a pandas DataFrame, which Flask can't use as a response. Change

response = make_response(result)

to

response = make_response(result.to_csv())

and you should be good to go.

Sign up to request clarification or add additional context in comments.

1 Comment

Also, keep in mind, if you're just running this via python main.py then you'll need to restart the server once you make your changes.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.