我有一个脚本,它使用存储在“my_dict”变量中的字典,以及url,user,password的值以及“id”变量。然后,该脚本根据传递的标头对URL进行HTTP GET调用。如何创建与此功能相同的Python函数?以及如何为以后的另一组url,用户,密码等功能?
import urllib, urllib2, base64, json
my_dict = {'server': {'user': 'patrick', 'url': 'http://192.168.0.1/tasks', 'password': 'secret'}}
id = "8d4lkf8kjhla8EnsdAjkjFjkdb6lklne"
for value in my_dict.keys():
url = my_dict[value]['url']
pass = my_dict[value]['password']
authKey = base64.b64encode("patrick:"+str(pass))
headers = {"login-session": id, "Content-Type": "application/json", "Authorization": "Basic " + authKey}
data = {"param": "value"}
request = urllib2.Request(url)
for key, value in headers.items():
request.add_header(key, value)
response = json.load(urllib2.urlopen(request))
print response
答案 0 :(得分:0)
您的问题有很多子问题,例如您想要变量或常数?你知道语法吗?你的功能将如何使用?等等。
因此,获得答案的最佳方式是学习一些基础知识,例如here( free ),了解python中的函数语法。之后你很可能会得到你问题的答案。
答案 1 :(得分:0)
如果我理解正确的话,这样的简单函数就会起作用,
def send_request(my_dict, id):
for value in my_dict.keys():
url = my_dict[value]['url']
pass = my_dict[value]['password']
authKey = base64.b64encode("patrick:"+str(pass))
headers = {"login-session": id, "Content-Type": "application/json", "Authorization": "Basic " + authKey}
data = {"param": "value"}
request = urllib2.Request(url)
for key, value in headers.items():
request.add_header(key, value)
response = json.load(urllib2.urlopen(request))
print response