Looking to convert this powershell code into python:
$secretArgs = @{
fileName = "test.pem"
fileAttachment = [IO.File]::ReadAllBytes("C:\brian\13568-test.txt")
} | ConvertTo-Json
*Update: I am trying this code to get a similar result:
import json
test_file = open("test.txt", "rb")
test_file_name = "test.txt"
body = {"filename":test_file_name,"fileattachment":test_file}
print(body)
data = json.dumps(body)
print(data)
The goal to find a pythonic method for this powershell snippet:
$endpoint ="$destinationapi/secrets/$fileSecretId/fields/$fileFieldToUpdate"
echo $endpoint
$secretArgs = @{
fileName = "test.pem"
fileAttachment = [IO.File]::ReadAllBytes("C:\brian\13568-test.txt")
} | ConvertTo-Json
$response = $null
$response = Invoke-RestMethod -Method Put -Uri $endpoint -Headers $destinationheaders -Body $secretArgs -ContentType "application/json"
CodePudding user response:
import json
secretArgs = {"fileName": "test.pem"}
with open("test.pem", "r") as f:
data = f.read()
raw_bytes = list(bytearray(data, "utf-8"))
secretArgs["fileAttachment"] = list(bytes(raw_bytes))
print(json.dumps(secretArgs))
CodePudding user response:
I created a small test file to see what the powershell command did exactly.
PS C:\> cat C:\temp\13568-test.txt
blah blah blah
PS C:\> $secretArgs = @{
>> fileName = "test.pem"
>> fileAttachment = [IO.File]::ReadAllBytes("C:/temp/13568-test.txt")
>> } | ConvertTo-Json
PS C:\> echo $secretArgs
{
"fileName": "test.pem",
"fileAttachment": [
98,
108,
97,
104,
32,
98,
108,
97,
104,
32,
98,
108,
97,
104
]
}
PS C:\>
To reproduce this in Python it seems to be:
import json
from pathlib import Path
test_file = Path("C:/temp/13568-test.txt")
content = {"fileName": "test.pem",
"fileAttachment": list(test_file.read_bytes())}
secret_args = json.dumps(content, indent=4)
print(secret_args)
Which gave the following output:
{
"fileName": "test.pem",
"fileAttachment": [
98,
108,
97,
104,
32,
98,
108,
97,
104,
32,
98,
108,
97,
104
]
}