簡體   English   中英

您將如何在python Requests或urllib2甚至pycurl中實現curl命令?

[英]How would you implement this curl command in python Requests or urllib2 or even pycurl?

您將如何在python Requests或urllib2甚至pycurl中實現curl命令? 我看過大量關於stackoverflow的示例,以及其他與我正在尋找的示例接近的示例,但是沒有一個示例顯示使用用戶名/密碼和令牌進行身份驗證(雙因素身份驗證)的示例。 我正在嘗試使用兩因素身份驗證登錄到站點,然后使用cookie請求json數據。
因此,我有一個登錄表單,要求發布“ urserId”,“ password”和“ token”(我相信該網站使用的是Google Authenticator令牌)。 這是滿足我需要的工作curl命令,我想將這兩個命令轉換為python。

curl -X POST  -H "Accept: Application/json" -H "Content-Type: application/json" http://example.com/rest/auth/login -d '{"userId":"myuserid", "password":"mypa$$word", "token":"321"}'

curl http://example.com/rest/search?q=e43f6f3bd6a0f0c0415accfh285f6a00b55552666b7s --cookie 'connect.sid=s%3BJAUAVY68925VclAlLZCV.Gy902343-x%20343seMBMsQodfdo-35'

我嘗試了許多不同的組合,包括以下使用請求的組合:

payload = {"userId":"myuserid", "password":"mypa$$word", "token":"321"}
headers={'Accept': 'Application/json','Content-Type': 'application/json'}

with requests.session() as c:
    c.post('http://example.com/rest/auth/login', headers=headers, data=payload )
    cookies=c.cookies.get_dict()
    c.get('http://example.com/rest/global/config', cookies=cookies)

不幸的是,它導致響應[400],告訴我我沒有正確使用憑據。

requests 文檔

很多時候您要發送的數據未經格式編碼。 如果您傳遞的是string而不是dict ,那么該數據將直接發布。

也就是說,您發布的內容不是application/json ,而是(我假設) application/x-www-form-urlencoded ,並且您的請求標頭在說謊:)

嘗試使用data=json.dumps(payload)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM