繁体   English   中英

等效于Python的PowerShell.Powers,同时包含数据和文件

[英]PowerShell equivalent for Python's requests.post with both data and files

我正在尝试使此Python代码等效于PowerShell:

import requests
requests.post('http://someCKANsite/api/action/resource_create',
              data={"package_id":"my_dataset"},
              headers={"X-CKAN-API-Key": "21a47217-6d7b-49c5-88f9-72ebd5a4d4bb"},
              files=[('upload', file('/path/to/file/to/upload.csv'))])

我努力了:

Invoke-WebRequest -Method Post -Uri http://someCKANsite/api/action/resource_create -Headers $headers -InFile $myfile -Body $rcbody -ContentType "multipart/form-data"

......用$headers包含我的X-CKAN-API-Key$rcbody包含package_id 但是我收到错误消息Invoke-WebRequest : The cmdlet cannot run because the following conflicting parameters are specified: Body and InFile. Specify either Body or Infile, then retry. Invoke-WebRequest : The cmdlet cannot run because the following conflicting parameters are specified: Body and InFile. Specify either Body or Infile, then retry.

我尝试将?package_id=...放在Uri的末尾,但这不起作用。 我已经在Advanced REST client尝试了各种组合,但都无济于事。 我也尝试过Invoke-RestMethod ,但是它有同样的麻烦。

您不能同时指定两者; 因为-InFile基本上只是将文件的内容作为一个正文添加(与您现有的正文冲突)。

但是,您可以自己执行以下操作来构造文件的主体(与invoke-webrequest /或invoke-rest方法相同):

$body = "upload=$(get-content c:\yourfile.csv -Enc Byte -raw)&package_id=my_dataset"
Invoke-RestMethod -Method $method -Headers $headers -Uri ($server+$uri) -body $body

在这里,我只是通过封装它们(&package_id =)在您的体内添加了更多参数。 您应该知道服务器如何处理您的参数。

它们是从正文(如我在此处假设)中读取的,还是作为url字符串的一部分读取的? 您可以在调用python并随后调整invoke-webrequst / invoke-restmethod时轻松查看请求的传递方式(例如,使用提琴手)。

希望这可以帮助:)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM