0

I am new to python. I have powershell script which downloads logs for me from web. I want same script in python.

PowerShell script -

$outfile = "/logs.csv"
$connectionToken=""
$base64AuthInfo=[System.Convert]::ToBase64String([System.Text.Encoding]::
ASCII.GetBytes(":$($connectionToken)"))

$AuditLogURL = "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" 

$AuditInfo = Invoke-RestMethod -Uri $AuditLogURL -Headers @{authorization = "Basic   
$base64AuthInfo"} -Method Get –OutFile $outfile 

I have created python script which calls the url but I am not sure how to download file in specified folder from this script -

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)
megha
  • 621
  • 2
  • 11
  • 36

2 Answers2

2

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())
wp78de
  • 18,207
  • 7
  • 43
  • 71
1

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)

Pavel Slepiankou
  • 3,516
  • 2
  • 25
  • 30
  • Thank you , this worked! is there any way I can select required data from this csv file and then generate new csv file with only needed data ? – megha Oct 21 '20 at 02:54
  • 1
    I'd prefer to use pandas for filtering data, just read CSV file with https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_csv.html – Pavel Slepiankou Oct 21 '20 at 03:07