Using python script to upload a file to django server localhost - python

I build an django rest framework that can help me to upload a file
in view.py
class FileResultViewSet(viewsets.ModelViewSet):
queryset = FileResult.objects.order_by('-timestamp')
serializer_class = FileResultSerializer
parser_classes = (MultiPartParser, FormParser)
def perform_create(self, serializer):
serializer.save()
The script work well without any error, and the file is stored in media folder
Then, I use an python script that can help me to upload file to django
import requests
import openpyxl
url = "http://localhost:8000/upload/"
headers = {'Content-Type': 'multipart/form-data'}
file_path = "H:/MEGA_H/Data/uploaded/Book1.xlsx"
'''
with open(file_path, 'rb') as f:
file = {'file': f}
response = requests.get(url, headers=headers, files=file)
'''
filename = "Book1.xlsx"
# Open the file and read its contents
with open(file_path, 'rb') as f:
file_contents = f.read()
# Create a dictionary to store the file information
#file_data = {'file': (filename, file_contents,result_file)}
file_data = {
"result_file": file_contents
}
# Make a POST request to the URL with the file information
response = requests.post(url, files=file_data)
# Check if the request was successful
if response.status_code == 201:
print("File successfully uploaded")
else:
print("Failed to upload file")
The code still works with an issue, after upload the file to media folder, the file doesnt include the file type, so it can not read. I have to change the name of the file , and typing file type ".xlsx"
The file name is only Book1, without Book1.xlsx

with open(file_path, 'rb') as f:
file_contents = f.read()
file_data = {
"result_file": file_contents
}
This is the wrong way to do it. The dict should contain the file object itself, not the file contents.
with open(file_path, 'rb') as f:
file_data = {"result_file": f}
response = requests.post(url, files=file_data)

Related

How to send a PDF file by DRF

I have a request for you, can you please help me with one question.
How can I send a pdf file via api.
It starts like this, they send me the base64 format and I accept it and do the decoding.
Then I need to send this file to another endpoint, but I just can’t put it there. Could you please help me
According to Postman, my file sits quietly and works as it should. The picture shows that it takes the form-date.
def sendDocs(photoBack):
try:
headers = {'Content-Type':'multipart/form-data;',
'bsauth': 'key'}
import base64
decodedData = base64.b64decode((photoBack))
pdfFile = open('photoBack.pdf', 'rb+')
pdfFile.write(decodedData)
pdfFile.close()
response = HttpResponse(pdfFile, content_type='application/pdf')
response['Content-Disposition'] = 'attachment; filename="photoBack.pdf"'
url = f'https://file.shinhanfinance.kz/files/shinhanfinance/add?client={1013246509}'
files = {"file":response}
firstPost1 = requests.post(url,data =response,headers=headers)
print(Response(firstPost1))
return Response({firstPost1})
except:
return Response({'bruh what wrong ?'})
Here my code
def sendDocs(photoBack):
try:
headers = {'Content-Type':'multipart/form-data;',
'bsauth': 'key'}
import base64
decodedData = base64.b64decode((photoBack))
pdfFile = open('photoBack.pdf', 'rb+')
pdfFile.write(decodedData)
pdfFile.close()
response = HttpResponse(pdfFile, content_type='application/pdf')
response['Content-Disposition'] = 'attachment; filename="photoBack.pdf"'
url = f'https://file.shinhanfinance.kz/files/shinhanfinance/add?client={1013246509}'
files = {"file":response}
firstPost1 = requests.post(url,data =response,headers=headers)
print(Response(firstPost1))
return Response({firstPost1})
except:
return Response({'bruh what wrong ?'})
You can try to use decodedData, and put it into file parameters.
firstPost1 = requests.post(url, files={"file": decodedData}, headers=headers)
I think here is your solution How to upload file with python requests?

file.save not saving file in proper format

I have to upload a file on two places,
in a local directory
in Jira via curl
I have written post endpoint which read files from request and send same file to Jira over a request and after success response, it saves it locally.
my code looks like below
for file in request.files.getlist('file'):
filename = file.filename
mimetype = file.content_type
if not is_valid_type(mimetype):
return json.dumps({"success": False, "message": "Invalid File Format" }), 415
files = {'file': (filename, file, mimetype)}
r = requests.post(jira_url, files=files, headers=headers, auth=HTTPBasicAuth(current_app.config.get('username'), current_app.config.get('password')),verify=False)
LOG.info("Got %s response from %s - text %s", r.status_code, "upload", r.json())
data = r.json()
filename = secure_filename(file.filename)
file.save(os.path.join(current_app.config["UPLOAD_FOLDER"], filename))
it saves the file but when I try to open it, it says we don't support this file format.
if I remove the post call to Jira from loop then it saves the file in the proper format.
did you try with open/write?:
with open("input_file.txt", "w") as text_file:
text_file.write("destination_file")
text_file.close()
solution to specify the path destination:
import os
filename = "input_file.txt"
path = "/pathlocation/..."
fullpath = os.path.join(path, filename)
with open("input_file.txt", "w") as text_file:
text_file.write(fullpath)
text_file.close()

How to POST a tgz file in Python using urllib2

I would like to POST a .tgz file with the Python urllib2 library to a backend server. I can't use requests due to some licensing issues. There are some examples of file upload on stackoverflow but all relate to attaching a file in a form.
My code is the following but it unfortunately fails:
stats["random"] = "data"
statsFile = "mydata.json"
headersFile = "header-data.txt"
tarFile = "body.tgz"
headers = {}
#Some custom headers
headers["X-confidential"] = "Confidential"
headers["X-version"] = "2"
headers["Content-Type"] = "application/x-gtar"
#Create the json and txt files
with open(statsFile, 'w') as a, open(headersFile, 'w') as b:
json.dump(stats, a, indent=4)
for k,v in headers.items():
b.write(k+":"+v+"\n")
#Create a compressed file to send
tar = tarfile.open(tarFile, 'w:gz' )
for name in [statsFile,headersFile]:
tar.add(name)
tar.close()
#Read the binary data from the file
with open(tarFile, 'rb') as f:
content = f.read()
url = "http://www.myurl.com"
req = urllib2.Request(url, data=content, headers=headers)
response = urllib2.urlopen(req, timeout=timeout)
If I use requests, it works like a charm:
r = requests.post(url, files={tarFile: open(tarFile, 'rb')}, headers=headers)
I essentially need the equivalent of the above for urllib2. Does anybody maybe know it? I have checked the docs as well but I was not able to make it work..What am I missing?
Thanks!

how to create csvs and write to zip file in Google App Engine (python)?

I'm trying to write multiple csvs to a zip file in Google App Engine. I found this post: Confused about making a CSV file into a ZIP file in django which has been helpful. In fact, when I do:
o=StringIO.StringIO()
file = zipfile.ZipFile(file=o,compression=zipfile.ZIP_DEFLATED,mode="w")
.. . ## add your csv files here
file.close()
o.seek(0)
self.response.headers['Content-Type'] ='application/zip'
self.response.headers['Content-Disposition'] = 'attachment; filename="your_csvs.zip"'
self.response.out.write(o.getvalue())
I get a blank zip file which is fine. However, above this, I have
self.response.headers['Content-Type'] = 'text/csv'
self.response.headers['Content-Disposition'] = 'attachment; filename=sheet.csv'
writer = csv.writer(self.response.out)
writer.writerow(['Text Here'])
Which by itself lets me download a csv. Where I'm stuck is when I try to combine the two. If I do:
self.response.headers['Content-Type'] = 'text/csv'
self.response.headers['Content-Disposition'] = 'attachment; filename=sheet.csv'
writer = csv.writer(self.response.out)
writer.writerow(['Text Here'])
o=StringIO.StringIO()
file = zipfile.ZipFile(file=o,compression=zipfile.ZIP_DEFLATED,mode="w")
file.writestr("sheet.csv", output.getvalue())
file.close()
o.seek(0)
self.response.headers['Content-Type'] ='application/zip'
self.response.headers['Content-Disposition'] = 'attachment; filename="your_csvs.zip"'
self.response.out.write(o.getvalue())
I get a zipfile that can't open. I'm fairly certain I'm using writestr incorrectly but I can't figure out the code to get the csv I create into the zip. Can anyone help?
Here is what I am doing
zh = StringIO()
zf = zipfile.ZipFile(zh,'w')
zi = zipfile.ZipInfo('test.csv')
zi.compress_type = zipfile.ZIP_DEFLATED
zi.comment = 'Some comment'
zf.writestr(zi, zh.getvalue())
zf.close()
payload = zh.getvalue()

How to download a file uploaded using django-filebrowser?

I am trying to create a download of a file object. the file was added using django-filebrowser which means it is turn in to a string path to the the file. I have tried the following:
f = Obj.objects.get(id=obj_id)
myfile = FileObject(os.path.join(MEDIA_ROOT, f.Audio.path))
...
response = HttpResponse(myfile, content_type="audio/mpeg")
response['Content-Disposition'] = 'attachment; filename=myfile.mp3'
return response
The file that is downloaded contains the string of the path to the file location and not the file. Could anyone be of assistance on how to access the file object?
f = Obj.objects.get(id=obj_id)
myfile = open(os.path.join(MEDIA_ROOT, f.Audio.path)).read()
...
response = HttpResponse(myfile, content_type="audio/mpeg")
response['Content-Disposition'] = 'attachment; filename=myfile.mp3'
return response
NOTE! This is not memory friendly! Since the whole file is put into memory. You're better of using a webserver for file serving or if you want to use Django for file serving you could use xsendfile or have a look at this thread
You need to open the file and send it's binary contents back in the response. So something like:
fileObject = FileObject(os.path.join(MEDIA_ROOT, f.Audio.path))
myfile = open(fileObject.path)
response = HttpResponse(myfile.read(), mimetype="audio/mpeg")
response['Content-Disposition'] = 'attachment; filename=myfile.mp3'
return response
Hope that gets what you're looking for.

Categories