2017-09-15 116 views
1

我必須注入PUT(捲曲-XPOST當量)兩個變量Python的請求 - 使用標頭中的變量和get請求

  • 變量1(頭)
  • 變量2(URL的一部分)

    headers = {'Authorization': 'Bearer Variable1', 
    } 
    
    files = [ 
    ('server', '*'), 
    ] 
    
    requests.get('https://URL/1/2/3/4/5/Variable2', headers=headers, files=files, verify=False) 
    

我遇到兩個問題:

  1. 將變量包含到請求中的正確方法
  2. 由於這是通過HTTPS運行的,因此如何驗證請求中實際包含的內容?我想驗證此調試目的

回答

1
  1. 什麼是變量包括在請求

傳遞headers字典爲headers參數的正確方法,因爲你寫它,很好。對於你的url字符串,我只需要將join()作爲你的變量2的基本URL,並將其作爲參數傳遞。

這是我怎麼會寫這樣的代碼:由於這是整個HTTPS運行

import requests 

base_url = 'https://URL/1/2/3/4/5/' 
url = ''.join([base_url, Variable2]) 

headers = {'Authorization': 'Bearer Variable1',} 
files = [('server', '*'),] 

resp = requests.put(url, headers=headers, files=files, verify=False) 
  • ,我如何驗證什麼是真正請求內包括的?我想驗證此調試目的
  • 您可以利用PreparedRequest對象:

    from requests import Request, Session 
    
    r = Request('PUT', url, headers=headers, files=files) 
    prepped = r.prepare() 
    
    # now, for example, you can print out the url, headers, method... 
    # whatever you need to validate in your request. 
    # for example: 
    # print prepped.url, prepped.headers 
    
    # you can also send the request like this... 
    
    s = Session() 
    resp = s.send(prepped)