Upload file using Material UI DropzoneDialogBase - reactjs

I am having issues uploading the files using Material UI DropzoneDialogBase;
My frontend is react & backend is flask
My component is defined as below
<DropzoneDialogBase
dialogTitle={addFileClassDialogTitle()}
fileObjects={uploadFiles}
cancelButtonText={"cancel"}
submitButtonText={"submit"}
maxFileSize={5000000}
filesLimit={1}
open={fileClassState.showAddFileClassForm}
onAdd={newFile => {
console.log('onAdd', newFile);
setUploadFiles([].concat( uploadFiles , newFile ));
}}
onDelete={deleteFile => {
console.log('onDelete', deleteFile);
const fileList = [...uploadFiles];
fileList.splice( deleteFile, 1 );
setUploadFiles( fileList );
}}
onClose={() => setShowAddFileClassForm(false)}
onSave={() => saveNewFileClass( )}
showPreviews={true}
showFileNamesInPreview={true}
/>
The component works fine and adds the files to the object "uploadFiles"
This is my saveNewFileClass
const saveNewFileClass = async () => {
const credentials = localStorage.getItem("credentials");
const formData = new FormData();
formData.append("file", uploadFiles[0]);
console.log( "type of uploadfiles =>", typeof(uploadFiles[0]));
for (var key of formData.entries()) {
console.log(key[0] + ', ' + key[1]);
}
formData.append("data", JSON.stringify({ token: credentials, fileclass: newFileClass }));
console.log('onSave', uploadFiles);
console.log("save new file class", formData);
const requestOptions = {
mode: 'cors',
cache: 'no-cache',
headers: { 'Content-Type': 'multipart/form-data' },
redirect: 'follow',
referrerPolicy: 'no-referrer'
};
const response = await axios.post(
'https://myhost.com:5000/api/addfileclass',
formData,
requestOptions )
const responseData = await response.data;
storeCredentials( responseData.credentials );
setShowAddFileClassForm(false);
}
The Console logs displayed are as below
FileClass.js:143 type of uploadfiles => object
FileClass.js:146 file, [object Object]
FileClass.js:151 onSave [{…}]0: {file: File, data: "data:application/vnd.openxmlformats-officedocument…jUHJvcHMvYXBwLnhtbFBLBQYAAAAAEgASANcEAADDUgAAAAA="}length: 1__proto__: Array(0)
FileClass.js:152 save new file class FormData {}
The log on line 151 confirms that the uploadFiles has an array of Files
However when I append to FormData 'files' it is changed as [Object Object]
Due to this on the flask backend I am not getting any values in request.files and I get the following error
Traceback (most recent call last):
File "/home/ubuntu/.local/lib/python3.8/site-packages/flask/app.py", line 2464, in __call__
return self.wsgi_app(environ, start_response)
File "/home/ubuntu/.local/lib/python3.8/site-packages/flask/app.py", line 2450, in wsgi_app
response = self.handle_exception(e)
File "/home/ubuntu/.local/lib/python3.8/site-packages/flask_cors/extension.py", line 161, in wrapped_function
return cors_after_request(app.make_response(f(*args, **kwargs)))
File "/home/ubuntu/.local/lib/python3.8/site-packages/flask/app.py", line 1867, in handle_exception
reraise(exc_type, exc_value, tb)
File "/home/ubuntu/.local/lib/python3.8/site-packages/flask/_compat.py", line 39, in reraise
raise value
File "/home/ubuntu/.local/lib/python3.8/site-packages/flask/app.py", line 2447, in wsgi_app
response = self.full_dispatch_request()
File "/home/ubuntu/.local/lib/python3.8/site-packages/flask/app.py", line 1952, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/home/ubuntu/.local/lib/python3.8/site-packages/flask_cors/extension.py", line 161, in wrapped_function
return cors_after_request(app.make_response(f(*args, **kwargs)))
File "/home/ubuntu/.local/lib/python3.8/site-packages/flask/app.py", line 1821, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/home/ubuntu/.local/lib/python3.8/site-packages/flask/_compat.py", line 39, in reraise
raise value
File "/home/ubuntu/.local/lib/python3.8/site-packages/flask/app.py", line 1950, in full_dispatch_request
rv = self.dispatch_request()
File "/home/ubuntu/.local/lib/python3.8/site-packages/flask/app.py", line 1936, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/home/ubuntu/.local/lib/python3.8/site-packages/flask_cors/decorator.py", line 128, in wrapped_function
resp = make_response(f(*args, **kwargs))
File "/home/ubuntu/platform-streamxls/react-excel-upload/flaskapp/routes.py", line 286, in addfileclass
downloadfile = request.files["file"]
File "/home/ubuntu/.local/lib/python3.8/site-packages/werkzeug/datastructures.py", line 442, in __getitem__
raise exceptions.BadRequestKeyError(key)
werkzeug.exceptions.BadRequestKeyError: 400 Bad Request: The browser (or proxy) sent a request that this server could not understand.
KeyError: 'file'
The python code segment where the error is raised is
def addfileclass():
headers = request.headers
downloadfile = request.files["file"]
Any help on how to fix the react will be nice

The variable uploadFiles is an object array which has a structure of data,files
uploadFiles = []{ data : "mime information", file : "the file Object"}
I changed the append statement to the following
const formData = new FormData();
formData.append("file", uploadFiles[0].file);
This works fine for a single file
I have worked out the pattern to upload multiple files.
most of the examples I searched had multiple api calls in a loop to upload multiple files; this is not always an efficient solution
I have the following for multiple files
const formData = new FormData();
uploadFiles.map((file, idx) => {
formData.append("file"+idx, file.file);
});
formData.append("data", JSON.stringify({ filecount: uploadFiles.length }));
In my backend - I use the filecount to identify the number of files that are there and use the values of "file0", "file1"... to handle the file uploads

Related

Too many values to unpack in Django [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 months ago.
Improve this question
My endpoint to edit a user in Django is implemented like this:
#api_view(['PUT'])
#permission_classes([IsAuthenticated])
def updateUser(request, pk):
user = User.objects.get(pk)
data = request.data
user.first_name = data['name']
user.username = data['email']
user.email = data['email']
user.is_staff = data['isAdmin']
user.save()
serializer = UserSerializer(user, many=False)
return Response(serializer.data)
My user serializer is implemented like this:
class UserSerializer(serializers.ModelSerializer):
name = serializers.SerializerMethodField(read_only=True)
_id = serializers.SerializerMethodField(read_only=True)
isAdmin = serializers.SerializerMethodField(read_only=True)
class Meta:
model = User
fields = ['id', '_id', 'username', 'email', 'name', 'isAdmin']
def get__id(self, obj):
return obj.id
def get_isAdmin(self, obj):
return obj.is_staff
def get_name(self, obj):
name = obj.first_name
if name == '':
name = obj.email
return name
My action in Redux to send a put request to Django is implemented like this:
export const updateUser = (user) => async (dispatch, getState) => {
try {
dispatch({
type: USER_UPDATE_REQUEST
})
const {
userLogin: { userInfo
}
} = getState()
const config = {
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${userInfo.token}`
}
}
const { data } = await axios.put(
`/api/users/update/${user._id}/`,
user,
config
)
dispatch({
type: USER_UPDATE_SUCCESS,
})
dispatch({
type: USER_DETAILS_SUCCESS,
payload: data
})
} catch (error) {
dispatch({
type: USER_UPDATE_FAIL,
payload: error.response && error.response.data.detail
? error.response.data.detail
: error.message,
})
}
}
I dispatch updateUser action on click of the button in my component like this:
const submitHandler = (e) => {
e.preventDefault()
dispatch(updateUser({ _id: user._id, name, email, isAdmin }))
}
I get error from Django:
Internal Server Error: /api/users/update/undefined/ Traceback (most recent call last): File "C:\Users\pc\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\handlers\exception.py", line 55, in inner
response = get_response(request) File "C:\Users\pc\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\handlers\base.py", line 197, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\pc\AppData\Local\Programs\Python\Python310\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view
return view_func(*args, **kwargs) File "C:\Users\pc\AppData\Local\Programs\Python\Python310\lib\site-packages\django\views\generic\base.py", line 84, in view
return self.dispatch(request, *args, **kwargs) File "C:\Users\pc\AppData\Local\Programs\Python\Python310\lib\site-packages\rest_framework\views.py", line 509, in dispatch
response = self.handle_exception(exc) File "C:\Users\pc\AppData\Local\Programs\Python\Python310\lib\site-packages\rest_framework\views.py", line 469, in handle_exception
self.raise_uncaught_exception(exc) File "C:\Users\pc\AppData\Local\Programs\Python\Python310\lib\site-packages\rest_framework\views.py", line 480, in raise_uncaught_exception
raise exc File "C:\Users\pc\AppData\Local\Programs\Python\Python310\lib\site-packages\rest_framework\views.py", line 506, in dispatch
response = handler(request, *args, **kwargs) File "C:\Users\pc\AppData\Local\Programs\Python\Python310\lib\site-packages\rest_framework\decorators.py", line 50, in handler
return func(*args, **kwargs) File "C:\Users\pc\Desktop\ecommerce\backend\base\views\user_views.py", line 94, in updateUser
user = User.objects.get(pk) File "C:\Users\pc\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\models\manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\Users\pc\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\models\query.py", line 482, in get
clone = self._chain() if self.query.combinator else self.filter(*args, **kwargs) File "C:\Users\pc\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\models\query.py", line 1071, in filter
return self._filter_or_exclude(False, args, kwargs) File "C:\Users\pc\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\models\query.py", line 1089, in _filter_or_exclude
clone._filter_or_exclude_inplace(negate, args, kwargs) File "C:\Users\pc\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\models\query.py", line 1096, in _filter_or_exclude_inplace
self._query.add_q(Q(*args, **kwargs)) File "C:\Users\pc\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\models\sql\query.py", line 1502, in add_q
clause, _ = self._add_q(q_object, self.used_aliases) File "C:\Users\pc\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\models\sql\query.py", line 1532, in _add_q
child_clause, needed_inner = self.build_filter( File "C:\Users\pc\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\models\sql\query.py", line 1374, in build_filter
arg, value = filter_expr ValueError: too many values to unpack (expected 2) [16/Dec/2022 10:32:19] "PUT /api/users/update/undefined/ HTTP/1.1" 500 133599
Please help me understand where the problem is
It is in the first line of your view function:
user = User.objects.get(pk=pk)
-- Explaination --
.get require keyword arguments.

Downloading a .csv file from FastAPI using React leads to "405 Method Not Allowed" error

Below is my React code to retrieve the .csv file. I would like the file to be downloaded immediately on click of the button:
downloadData = () => {
fetch('http://localhost:8000/genreport')
.then(response => {
response.blob().then(blob => {
let url = window.URL.createObjectURL(blob);
let a = document.createElement('a');
a.href = url;
a.download = 'onomonitoring.csv';
a.click();
});
...
render() {
return (
<div id="container">
<button onClick={this.downloadData}>Download</button>
</div>
)
}
}
This is my FastAPI code to generate the .csv file:
#app.post("/genreport")
def gen_colreport(db: Session = Depends(get_db)):
df = collection_report(db)
date_today = datetime.today().strftime('%Y%m%d')
col_report_str = "collectionreport_"
filename = col_report_str + date_today + ".csv"
# col_report = df.to_csv(filename, encoding="utf-8")
stream = io.StringIO()
df.to_csv(stream, encoding="utf-8", index= False)
response = StreamingResponse(iter([stream.getvalue()]),
media_type="text/csv"
)
response.headers["Content-Disposition"] = "attachment; filename=%s" % (filename)
return response
I can download the file from FastAPI but when I run the code it throws a 405 Method Not Allowed error. Is there a way I can download the .csv file from FastAPI directly or retrieve the csv file from the database directly?

Managing Django Rest Framework 500 Internal Server Error in React when creating user

I am attempting my first React + DRF project. Here is my difficulty. When I try to create a user with an existing username I get a 500 internal server error and I can't seem to catch it or do anything with it in React. It otherwise works perfectly well and I can display errors when retrieving user info (such as: "sure does not exist").
The full traceback of the IntegrityError error I get from the backend is:
Traceback (most recent call last):
File "/Users/bernardino/Desktop/boombust/.env/lib/python3.8/site-packages/django/db/backends/utils.py", line 89, in _execute
return self.cursor.execute(sql, params)
psycopg2.errors.UniqueViolation: duplicate key value violates unique constraint "users_customuser_username_key"
DETAIL: Key (username)=(kenshiro) already exists.
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/Users/bernardino/Desktop/boombust/.env/lib/python3.8/site-packages/django/core/handlers/exception.py", line 55, in inner
response = get_response(request)
File "/Users/bernardino/Desktop/boombust/.env/lib/python3.8/site-packages/django/core/handlers/base.py", line 197, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Users/bernardino/Desktop/boombust/.env/lib/python3.8/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view
return view_func(*args, **kwargs)
File "/Users/bernardino/Desktop/boombust/.env/lib/python3.8/site-packages/django/views/generic/base.py", line 84, in view
return self.dispatch(request, *args, **kwargs)
File "/Users/bernardino/Desktop/boombust/.env/lib/python3.8/site-packages/rest_framework/views.py", line 509, in dispatch
response = self.handle_exception(exc)
File "/Users/bernardino/Desktop/boombust/.env/lib/python3.8/site-packages/rest_framework/views.py", line 469, in handle_exception
self.raise_uncaught_exception(exc)
File "/Users/bernardino/Desktop/boombust/.env/lib/python3.8/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception
raise exc
File "/Users/bernardino/Desktop/boombust/.env/lib/python3.8/site-packages/rest_framework/views.py", line 506, in dispatch
response = handler(request, *args, **kwargs)
File "/Users/bernardino/Desktop/boombust/users/views.py", line 33, in post
user = serializer.save()
File "/Users/bernardino/Desktop/boombust/.env/lib/python3.8/site-packages/rest_framework/serializers.py", line 212, in save
self.instance = self.create(validated_data)
File "/Users/bernardino/Desktop/boombust/users/serializers.py", line 59, in create
instance.save()
File "/Users/bernardino/Desktop/boombust/.env/lib/python3.8/site-packages/django/contrib/auth/base_user.py", line 68, in save
super().save(*args, **kwargs)
File "/Users/bernardino/Desktop/boombust/.env/lib/python3.8/site-packages/django/db/models/base.py", line 806, in save
self.save_base(
File "/Users/bernardino/Desktop/boombust/.env/lib/python3.8/site-packages/django/db/models/base.py", line 857, in save_base
updated = self._save_table(
File "/Users/bernardino/Desktop/boombust/.env/lib/python3.8/site-packages/django/db/models/base.py", line 1000, in _save_table
results = self._do_insert(
File "/Users/bernardino/Desktop/boombust/.env/lib/python3.8/site-packages/django/db/models/base.py", line 1041, in _do_insert
return manager._insert(
File "/Users/bernardino/Desktop/boombust/.env/lib/python3.8/site-packages/django/db/models/manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/Users/bernardino/Desktop/boombust/.env/lib/python3.8/site-packages/django/db/models/query.py", line 1434, in _insert
return query.get_compiler(using=using).execute_sql(returning_fields)
File "/Users/bernardino/Desktop/boombust/.env/lib/python3.8/site-packages/django/db/models/sql/compiler.py", line 1621, in execute_sql
cursor.execute(sql, params)
File "/Users/bernardino/Desktop/boombust/.env/lib/python3.8/site-packages/django/db/backends/utils.py", line 103, in execute
return super().execute(sql, params)
File "/Users/bernardino/Desktop/boombust/.env/lib/python3.8/site-packages/django/db/backends/utils.py", line 67, in execute
return self._execute_with_wrappers(
File "/Users/bernardino/Desktop/boombust/.env/lib/python3.8/site-packages/django/db/backends/utils.py", line 80, in _execute_with_wrappers
return executor(sql, params, many, context)
File "/Users/bernardino/Desktop/boombust/.env/lib/python3.8/site-packages/django/db/backends/utils.py", line 89, in _execute
return self.cursor.execute(sql, params)
File "/Users/bernardino/Desktop/boombust/.env/lib/python3.8/site-packages/django/db/utils.py", line 91, in __exit__
raise dj_exc_value.with_traceback(traceback) from exc_value
File "/Users/bernardino/Desktop/boombust/.env/lib/python3.8/site-packages/django/db/backends/utils.py", line 89, in _execute
return self.cursor.execute(sql, params)
django.db.utils.IntegrityError: duplicate key value violates unique constraint "users_customuser_username_key"
DETAIL: Key (username)=(kenshiro) already exists.
The view in views.py is:
class CustomUserCreate(APIView):
permission_classes = (permissions.AllowAny,)
def post(self, request, format='json'):
serializer = CustomUserSerializer(data=request.data)
if serializer.is_valid(raise_exception=True):
try:
user = serializer.save()
if user:
json = serializer.data
return Response(json, status=status.HTTP_201_CREATED)
except IntegrityError:
return Response({"error": "This username is already taken."}, status=status.HTTP_406_NOT_ACCEPTABLE)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
And this is the React logic:
const onSubmit = async (values) => {
const user = {
first_name: values.firstName,
last_name: values.lastName,
username: values.username,
email: values.email,
password: values.password,
};
const response = await fetch(`users/user/create/`, {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
},
body: JSON.stringify({...user}),
}).catch(err => err);
const text = await response.text();
console.log(response.status);
if (response.status === 201) {
console.log("success", JSON.parse(text));
} else {
console.log("failed", text);
}
};
This is the serializer from serializers.py:
class CustomUserSerializer(serializers.ModelSerializer):
token = serializers.SerializerMethodField()
password = serializers.CharField(write_only=True)
email = serializers.EmailField(
required=True
)
username = serializers.CharField(required=True)
first_name = serializers.CharField(required=True)
last_name = serializers.CharField(required=True)
password = serializers.CharField(
min_length=8, write_only=True, required=True)
class Meta:
model = CustomUser
fields = ('email', 'username', 'password', 'token', 'first_name', 'last_name')
extra_kwargs = {'password': {'write_only': True}}
def get_token(self, user):
refresh = RefreshToken.for_user(user)
return {
'refresh': str(refresh),
'access': str(refresh.access_token),
}
I do have a username = CICharField(unique=True) in the CustomUser class in models.py if it helps.
You need to check before you save the model.
class CustomUserCreate(APIView):
permission_classes = (permissions.AllowAny,)
def post(self, request, format='json'):
serializer = CustomUserSerializer(data=request.data)
if serializer.is_valid(raise_exception=True):
# here you can check if the username already exists or not
username = serializer.validated_data.get('username')
if CustomUser.objects.filter(username = username).count() > 0:
return Response({"error": "This username is already taken."}, status=status.HTTP_406_NOT_ACCEPTABLE)
# if username is new
user = serializer.save()
if user:
json = serializer.data
return Response(json, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

How to upload file along with json meta data using rest api

I have requirement to upload xlsx file on server along with some json data(both has to be done in one request). I was able to upload just file using multipart/form-data, but when I tried add JSON data to the same request, request is failing with org.apache.commons.fileupload.FileUploadBase$InvalidContentTypeException: the request doesn't contain a multipart/form-data or multipart/mixed stream
exception. Below is my code.
Client side code
var method = 'POST';
$.ajax({
type: method,
url : "rest/file/upload",
transformRequest: function () {
var formData = new FormData();
formData.append("model", JSON.stringify(jsonData));
formData.append("file",document.getElementById("fileForm"));
return formData;
},
enctype : 'multipart/form-data',
processData : false,
contentType : false,
success: function (data) {},
error: function (data) {}
});
model is the JSON data & file is xlsx file which is to be uploaded.
Server Side Code
#POST
#Path("/upload")
#Consumes(MediaType.MULTIPART_FORM_DATA)
#Produces(MediaType.TEXT_PLAIN)
public Response uploadResumableISOFile(#Context HttpServletRequest request, #Context UriInfo uri,
#Context HttpHeaders headers, #Context HttpServletResponse response) throws IOException {
ServletFileUpload uploader = null;
try {
DiskFileItemFactory fileFactory = new DiskFileItemFactory();
uploader = new ServletFileUpload(fileFactory);
List<FileItem> fileItemsList = uploader.parseRequest(request);
Iterator<FileItem> fileItemsIterator = fileItemsList.iterator();
while (fileItemsIterator.hasNext()) {
FileItem fileItem = fileItemsIterator.next();
File file = File.createTempFile("TEMP_", ".xlsx");
fileItem.write(file);
System.out.print("File " + fileItem.getName() + " uploaded successfully.");
}
System.out.println("File uploaded to successfully...");
return Response.status(Response.Status.OK).build();
} catch (Exception e) {
System.out.println(e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity("Failed to upload file.").build();
}
}
Please let me know if something is missing.

How to send csv from angular to flask and load into pandas?

I am trying to post a csv file from my client to my server and load the file into pandas. I get the error IOError: Expected file path name or file-like object, got type
I tried sending the same file to the same url through postman and there was no error. So I think there is a problem with how angular sends the file or how it is appended to FormData.
app.py
from flask import Flask, render_template, request, send_from_directory
from minimongo import Model, configure
import pandas
import csv
app = Flask(__name__)
configure(host="xx.xx.com", port=xx, username="xx", password="xx")
class Placement(Model):
class Meta:
database= "flask_api"
collection = "placements"
#app.route('/')
def index():
return render_template("index.html")
#app.route('/<path:path>')
def send_static(path):
return send_from_directory('static', path)
#app.route('/receive_form', methods=['GET', 'POST'])
def receive_form():
instance = Placement()
instance.x = "test"
instance.save()
df = pandas.read_csv(request.files.get("csv"))
return "200"
if __name__ == '__main__':
app.run(debug=True)
app.js
angular.module("negatizer", ['ngRoute'])
.service("getJson", function($http){
this.getJson = function(callback){
$http.get("/mock/data.json").then(callback)
}
})
.service("postFormData", function($http){
this.postFormData = function(data, callback){
console.log("service")
$http.post("/receive_form", data).then(callback)
}
})
.controller("mainCtrl", function($scope, $window, getJson, postFormData){
$scope.fileChanged = function(element) {
var form = new FormData()
form.append("csv", element.files[0])
postFormData.postFormData(form, function() {
console.log("I sent the the form")
})
}
getJson.getJson(function(response) {
console.log(response.data)
$scope.varName = response.data
})
})
.config(function ($routeProvider) {
$routeProvider
.when("/", {
controller: "mainCtrl",
templateUrl: "partials/home.html"
})
.otherwise({
redirectTo: "/mock/data.json"
});
});
the form in index.html
<form action="/" enctype="multipart/form-data" id="form" method="post">
<span id="upload">
Upload Automatic Placements<input ng-model="photo" onchange="angular.element(this).scope().fileChanged(this)" type="file" name="csv">
</span>
</form>
traceback
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/flask/app.py", line 1836, in __call__
return self.wsgi_app(environ, start_response)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/flask/app.py", line 1820, in wsgi_app
response = self.make_response(self.handle_exception(e))
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/flask/app.py", line 1403, in handle_exception
reraise(exc_type, exc_value, tb)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/flask/app.py", line 1817, in wsgi_app
response = self.full_dispatch_request()
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/flask/app.py", line 1477, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/flask/app.py", line 1381, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/flask/app.py", line 1475, in full_dispatch_request
rv = self.dispatch_request()
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/flask/app.py", line 1461, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/Users/student/Documents/flask_projects/neg_app/app.py", line 28, in receive_form
df = pandas.read_csv(request.form.get("csv"))
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pandas/io/parsers.py", line 498, in parser_f
return _read(filepath_or_buffer, kwds)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pandas/io/parsers.py", line 275, in _read
parser = TextFileReader(filepath_or_buffer, **kwds)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pandas/io/parsers.py", line 590, in __init__
self._make_engine(self.engine)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pandas/io/parsers.py", line 731, in _make_engine
self._engine = CParserWrapper(self.f, **self.options)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pandas/io/parsers.py", line 1103, in __init__
self._reader = _parser.TextReader(src, **kwds)
File "pandas/parser.pyx", line 353, in pandas.parser.TextReader.__cinit__ (pandas/parser.c:3246)
File "pandas/parser.pyx", line 608, in pandas.parser.TextReader._setup_parser_source (pandas/parser.c:6288)
IOError: Expected file path name or file-like object, got <type 'NoneType'> type

Resources