正在寻找有关以下方面的指导:
import requests
import json
class RESTConnector:
def __init__(self, user, passwd, url):
self.user = user
self.passwd = passwd
self.url = url
self.auth = user + ' ' + passwd
def display_details(self):
return '{} {} {} {}'.format(self.user, self.passwd, self.url, self.auth)
def pull_data(self):
response = requests.get(self.url, self.auth, timeout=3)
print(type(response))
print(response)
sub = RESTConnector('username1', 'password', 'http://some.url.com')
selection = input("Select data to query: ").lower()
if selection == 'subnet':
print(sub.display_details())
print(sub.pull_data())
else:
print(f'Selection not recognised!')
使用curl来测试通过display_details方法返回的凭据,并按预期返回数据,但是上面的代码返回以下内容:
$python "/Desktop/Python/RESTConnector.py"
Select data to query: subnet
username1 password https://some.url.com username1 password
<class 'requests.models.Response'>
<Response [404]>
None
答案 0 :(得分:1)
出现该错误是因为必须通过带有关键字参数的auth。
requests.get(url, auth=('user', 'passwd'), timeout=timeout)
这是实现:
import requests
import json
class RESTConnector:
def __init__(self, user, passwd, url):
self.user = user
self.passwd = passwd
self.url = url
self.timeout = 3
def display_details(self):
# Display all relevant class attribute.
data = [f'{x}: {getattr(self, x)}' for x in self.__dir__() if not x.endswith('__')]
return data
def pull_data(self):
response = requests.get(self.url, auth=(self.user, self.passwd), timeout=self.timeout)
print('Task executed successfully:', response.ok)
sub = RESTConnector('username', 'password', 'http://some.url.com')
selection = input('Select data to query: ').lower()
if selection == 'subnet':
print(sub.display_details())
print(sub.pull_data())
else:
print('Selection not recognised!')