Uploading file in python flask

2024/5/20 18:49:35

I am trying to incorporate uploading a basic text/csv file on my web app which runs flask to handle http requests. I tried to follow the baby example in flasks documentation running on localhost here. But when I try this code on my page it seems to upload but then just hangs and in fact my flask server freezes and I have to close terminal to try again...Ctrl+C doesn't even work.

I execute run.py:

#!/usr/bin/env python
from app import appif __name__ == '__main__':app.run(host='0.0.0.0', port=5000, debug=False, use_reloader=False)

and app is a directory in the same directory where run.py is with the following __init__.py:

import os
from flask import Flask
from werkzeug import secure_filename#Flask object initialization
#app flask object has to be created before importing views below
#because it calls "import app from app"
UPLOAD_FOLDER = '/csv/upload'
ALLOWED_EXTENSIONS = set(['txt', 'csv'])app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER

and here is my views.py file which has all my routes:

from flask import render_template, request, redirect, url_for
from app import app
import os#File extension checking
def allowed_filename(filename):return '.' in filename and filename.rsplit('.',1)[1] in ALLOWED_EXTENSIONS@app.route('/', methods=['GET', 'POST'])
@app.route('/index.html', methods=['GET', 'POST'])
def index():if request.method == 'POST':submitted_file = request.files['file']if submitted_file and allowed_filename(submitted_file):filename = secure_filename(submitted_file.filename)submitted_file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))return redirect(url_for('uploaded_file', filename=filename))return '''<!doctype html><title>Upload new File</title><h1>Upload new File</h1><form action="" method=post enctype=multipart/form-data><p><input type=file name=file><input type=submit value=Upload></form>'''
Answer

The problem is that you're passing the wrong thing to allowed_filename(). You should be passing submitted_file.filename not submitted_file itself

https://en.xdnf.cn/q/73146.html

Related Q&A

Diagonal stacking in numpy?

So numpy has some convenience functions for combining several arrays into one, e.g. hstack and vstack. Im wondering if theres something similar but for stacking the component arrays diagonally?Say I h…

Rules Engine in C or Python [closed]

Closed. This question is seeking recommendations for books, tools, software libraries, and more. It does not meet Stack Overflow guidelines. It is not currently accepting answers.We don’t allow questi…

Draw arrows between 3 points

I am trying to draw arrows between three points in matplotlib.Lets assume we have 3 arbitrary points (A1,A2,A3) in 2d and we want to draw arrows from A1 to A2 and from A2 to A3.Some code to make it cle…

Make an animated wave with drawPolyline in PySide/PyQt

Im trying to animate a polyline (it have to act like a wave). Ive tried this way:from PySide.QtCore import * from PySide.QtGui import * import sys, timeclass Test(QMainWindow):def __init__(self, parent…

dateutil.tz package apparently missing when using Pandas?

My python 2.7 code is as follows:import pandas as pd from pandas import DataFrameDF_rando = DataFrame([1,2,3])...and then when I execute, I get a strange error regarding dateutil.tz./Library/Frameworks…

Importing SPSS dataset into Python

Is there any way to import SPSS dataset into Python, preferably NumPy recarray format? I have looked around but could not find any answer.Joon

Given a set of points defined in (X, Y, Z) coordinates, interpolate Z-value at arbitrary (X, Y)

Given a set of points in (X, Y, Z) coordinates that are points on a surface, I would like to be able to interpolate Z-values at arbitrary (X, Y) coordinates. Ive found some success using mlab.griddata …

Python multiprocessing speed

I wrote this bit of code to test out Pythons multiprocessing on my computer:from multiprocessing import Poolvar = range(5000000) def test_func(i):return i+1if __name__ == __main__:p = Pool()var = p.map…

Using os.forkpty() to create a pseudo-terminal to ssh to a remote server and communicate with it

Im trying to write a python script that can ssh into remote server and can execute simple commands like ls,cd from the python client. However, Im not able to read the output from the pseudo-terminal af…

Calculating the sum of a series?

This is my assignment and for the life of me i cant seem to think of a way to do it. This is the code I have so far:sum = 0 k = 1 while k <= 0.0001:if k % 2 == 1:sum = sum + 1.0/kelse:sum = sum - 1.…