请求将指定PowerShell代码转换为Python实现(含API调用逻辑)
PowerShell转Python实现文件上传API请求
原PowerShell逻辑
这段代码的作用是读取本地文件字节内容,构造JSON请求体,最终发送PUT请求更新指定API端点:
$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"
用户尝试的Python代码问题
用户的代码直接将文件对象放入字典,尝试序列化JSON时会报错(JSON无法序列化文件对象),同时键名大小写与原PowerShell不一致,导致请求不匹配:
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)
正确的Python实现
要完全对齐PowerShell的逻辑,需注意两个核心点:
- PowerShell会自动将字节数组转为Base64字符串再序列化JSON,Python需要手动完成这一步
- 保持请求体键名的大小写与原代码一致(
fileName和fileAttachment)
完整Pythonic实现代码:
import json import base64 import requests # 替换为实际业务变量 destinationapi = "你的API前缀地址" fileSecretId = "目标SecretID" fileFieldToUpdate = "待更新字段名" destinationheaders = {"Authorization": "你的认证信息"} # 示例请求头,按需调整 # 构造API端点 endpoint = f"{destinationapi}/secrets/{fileSecretId}/fields/{fileFieldToUpdate}" print(endpoint) # 读取文件并转为Base64字符串 file_path = "C:/brian/13568-test.txt" with open(file_path, "rb") as f: file_base64 = base64.b64encode(f.read()).decode("utf-8") # 构造符合要求的请求体 secret_args = { "fileName": "test.pem", "fileAttachment": file_base64 } request_body = json.dumps(secret_args) # 发送PUT请求 response = requests.put( url=endpoint, headers=destinationheaders, data=request_body, content_type="application/json" ) # 按需处理响应 print(response.status_code) print(response.json())
核心细节说明
- 用
with语句管理文件资源,确保文件自动关闭,符合Python最佳实践 - 通过
base64.b64encode将文件字节转为Base64字符串,再解码为UTF-8格式,保证能被JSON序列化 - 使用
requests库发送HTTP请求,比标准库urllib更简洁易用 - 严格匹配原PowerShell的请求体键名和Content-Type设置,避免接口不兼容
内容的提问来源于stack exchange,提问作者evilmonkey2148
相关产品推荐
相关产品推荐

