Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
185 views
in Technique[技术] by (71.8m points)

python - How to take a file as a form-field input without defining it as a Model in Django?

I have written a simple API for Tax Analysis through a ZIP file sent by our supplier using the FastAPI framework. (As you can see below). However, I had to start shifting my APIs to Django for some technical reasons. I have been searching for a way to input a file as form-data in Django, but all of them require a Model to be created for that, however, for my requirement, I don't need that file stored anywhere permanently, just temporarily in the memory for further analysis. Below is an example of how I was taking the file as an input through FastAPI.

@app.get('/xtracap_gst/files')
async def gst(file: UploadFile = File(any))

Any inputs would be appreciated

EDIT:

I have managed to get the file uploaded in my memory but it returns a MultiValueDictionary and as per documentation, it is further handled by the UploadedFile Class of request.FILES. However, on running UploadedFile.read() it says TypeError: 'property' object is not callable . Please find my code below:

@api_view (['GET','POST'])
def gstAnalysis(request):
    if request.method == 'POST':
        parser_classes = (FileUploadParser,)
        file = request.FILES
        file =  UploadedFile.read()
        print(file)
        return Response({'test'})
    else:
        return Response({'Test'}) 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I can't test it but ...

you should get dictionary request.FILES (even if you send one file) and every element in dictionary is a object UploadedFile and its key is name from <input name=...>. And UploadedFile has method .read()

  for name, uploaded_file in request.FILES.items(): 
      print( name )    
      print( uploaded_file.read() ) 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...