HTTP Digest/Basic Auth with Python Requests module

谁说胖子不能爱 提交于 2019-12-05 13:29:12

The two requests are independent:

r = requests.get(url, auth=HTTPDigestAuth('user', 'pass')) 
response = requests.get(url) #XXX <-- DROP IT

The second request does not send any credentials. Therefore it is not surprising that it receives 401 Unauthorized http response status.

To fix it:

  1. Use the same url as you use in your browser. Drop digest-auth/auth/user/pass at the end. It is just an example in the requests docs
  2. Print r.status_code instead of response.status_code to see whether it's succeeded.

Why would you use username/password in the url and in auth parameter? Drop username/password from the url. To see the request that is sent and the response headers, you could enable logging/debugging:

import logging
import requests
from requests.auth import HTTPDigestAuth

# these two lines enable debugging at httplib level (requests->urllib3->httplib)
# you will see the REQUEST, including HEADERS and DATA, 
# and RESPONSE with HEADERS but without DATA.
# the only thing missing will be the response.body which is not logged.
try:
    import httplib
except ImportError:
    import http.client as httplib

httplib.HTTPConnection.debuglevel = 1

logging.basicConfig(level=logging.DEBUG) # you need to initialize logging, 
                      # otherwise you will not see anything from requests

# make request
url = 'https://example.com/cgi/metadata.cgi?template=html'
r = requests.get(url, auth=HTTPDigestAuth('myUsername', 'myPassword'),
                 timeout=10)
print(r.status_code)
print(r.headers)
import requests
from requests.auth import HTTPDigestAuth

url='https://example.com/cgi/metadata.cgi?template=html'
r = requests.get(url, auth=HTTPDigestAuth('myUsername', 'myPassword'), verify=False,  stream=True)        


print(r.headers) 
print(r.status_code)

fixed with adding stream=True since the page is streaming xml/html data. My next questions is, how do I store/parse a constant stream of data?

I tried storing in r.content but it seems to run indefinitely (the same problem I had before)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!