If the payload you are downloading is binary you would write it like this:
open('my.jpg', 'wb').write(response.content)
Or if it is text:
open('my.txt', 'w').write(response.text)
#print(open("my.txt", "r").read())
Answer from wp78de on Stack OverflowIf the payload you are downloading is binary you would write it like this:
open('my.jpg', 'wb').write(response.content)
Or if it is text:
open('my.txt', 'w').write(response.text)
#print(open("my.txt", "r").read())
Just save to the current directory
with open("logs.csv", "w") as text_file:
text_file.write(response.text)
or any other
import requests
import base64
pat = ""
authorization = str(base64.b64encode(bytes(':'+pat, 'ascii')), 'ascii')
url="https://auditservice.dev.azure.com/{org}/_apis/audit/downloadlog?
format=csv&startTime=2020-07-01T00.00.00&endTime=2020-10-15T16.00.00&api-version=6.1-
preview.1"
headers = {
'Accept': 'application/json',
'Authorization': 'Basic '+authorization
}
response = requests.get(url, headers=headers)
with open("/Users/username/logs/logs.csv", "w") as text_file:
text_file.write(response.content)
python - Flask-RESTful: Using GET to download a file with REST - Stack Overflow
http - download files with python (REST URL) - Stack Overflow
Python Rest client api to upload a file - Stack Overflow
Newest Questions - Software Recommendations Stack Exchange
Videos
Download from local folder
def download_Object():
try:
srcFileName="bulk_file.zip"
with open(srcFileName, 'wb') as f:
f.write(srcFileName)
except Exception as e:
print(e)
try:
srcFileName="filename"
with open(srcFileName, 'wb') as f:
f.write(srcFileName)
except Exception as e:
print(e)
The approach suggested in the Flask-RESTful documentation is to declare our supported representations on the Api object so that it can support other mediatypes. The mediatype we are looking for is application/octet-stream.
First, we need to write a representation function:
from flask import Flask, send_file, safe_join
from flask_restful import Api
app = Flask(__name__)
api = Api(app)
@api.representation('application/octet-stream')
def output_file(data, code, headers):
filepath = safe_join(data["directory"], data["filename"])
response = send_file(
filename_or_fp=filepath,
mimetype="application/octet-stream",
as_attachment=True,
attachment_filename=data["filename"]
)
return response
What this representation function does is to convert the data, code, headers our method returns into a Response object with mimetype application/octet-stream. Here we use send_file function to construct this Response object.
Our GET method can be something like:
from flask_restful import Resource
class GetFile(Resource):
def get(self, filename):
return {
"directory": <Our file directory>,
"filename": filename
}
And that's all the coding we need. When sending this GET request, we need to change the Accept mimetype to Application/octet-stream so that our API will call the representation function. Otherwise it will return the JSON data as by default.
There's an xml example on github
I know this question was asked 7 years ago so it probably doesn't matter any more to @Ayrx. Hope it helps to whoever drops by.
As long as you're setting the Content-Type header accordingly and respecting the Accept header sent by the client, you're free to return any format you want. You can just have a view that returns your binary data with the application/octet-stream content type.
Use urllib3 module.
https://urllib3.readthedocs.io/en/latest/user-guide.html
Files & binary data
For uploading files using multipart/form-data encoding you can use the same approach as Form data and specify the file field as a tuple of (file_name, file_data):
with open('example.txt') as fp:
file_data = fp.read()
r = http.request(
'POST',
'http://httpbin.org/post',
fields={
'filefield': ('example.txt', file_data),
})
json.loads(r.data.decode('utf-8'))['files']
requests library worked with below changes in my code :
import requests
from requests.auth import HTTPBasicAuth
import json
from pathlib import Path
file_ids = ''
headers={'Username': '[email protected]', 'apikey':'123-456'}
# Upload file
f = open('C:/Users/ADMIN/Downloads/abc.zip', 'rb')
files = {"file": ("C:/Users/ADMIN/Downloads/abc.zip", f)}
resp = requests.post("https:// ../analytics/upload_file", files=files, headers=headers )
print resp.text
print "status code " + str(resp.status_code)
if resp.status_code == 201:
print ("Success")
data = json.loads(resp.text)
file_ids = data['file_ids']
print file_ids
else:
print ("Failure")