program tip

파이썬 요청 모듈에 헤더 추가

radiobox 2020. 10. 14. 07:41
반응형

파이썬 요청 모듈에 헤더 추가


앞서 httplib모듈을 사용 하여 요청에 헤더를 추가했습니다. 이제 requests모듈에 대해 동일한 작업을 시도하고 있습니다.

이것은 내가 사용하고있는 파이썬 요청 모듈입니다 : http://pypi.python.org/pypi/requests

어떻게에 헤더를 추가 할 수 있습니다 request.post그리고 request.get내가 추가해야 할 말을 foobar헤더에 각 요청에 키를 누릅니다.


에서 http://docs.python-requests.org/en/latest/user/quickstart/

url = 'https://api.github.com/some/endpoint'
payload = {'some': 'data'}
headers = {'content-type': 'application/json'}

r = requests.post(url, data=json.dumps(payload), headers=headers)

헤더 (키 : 값 쌍, 여기서 키는 헤더의 이름이고 값은 쌍의 값)로 사전을 작성하고 해당 사전을 .get또는 .post메소드 의 headers 매개 변수에 전달하기 만하면됩니다 .

귀하의 질문에 더 구체적입니다.

headers = {'foobar': 'raboof'}
requests.get('http://himom.com', headers=headers)

이 작업을 수행하여 Session 개체에 대한 모든 향후 가져 오기에 대한 헤더를 설정할 수도 있습니다. 여기서 x-test는 모든 s.get () 호출에 있습니다.

s = requests.Session()
s.auth = ('user', 'pass')
s.headers.update({'x-test': 'true'})

# both 'x-test' and 'x-test2' are sent
s.get('http://httpbin.org/headers', headers={'x-test2': 'true'})

에서 : http://docs.python-requests.org/en/latest/user/advanced/#session-objects

참고 URL : https://stackoverflow.com/questions/8685790/adding-header-to-python-requests-module

반응형