Reading key/value pairs from text file, line by line, and passing values/dict to urlopen http function
I have to fill in multiple form fields on a web page
I got the http POST part completed so I can post data to the web page. I also got the part completed where I create a dictionary of key/value pairs and have the form fields filled on the web page.Key/value pairs:
input1 = {'hostname' : 'host', 'port' : '22', 'basedn' : 'CN=Users', 'bindusername' : 'admin', 'bindpassword' : 'passwd', 'groupname' : 'CN=Group,CN=Users,DC=tech,DC=com', 'usernameattribute' : 'name'}
for line in open("/Users/rwettstein/Scripts/Files/ldap-settings.txt", "r"):
print line
input = line
time.sleep(10)
params = urllib.urlencode(dict(input))
try:
f_handler = urlopen('https://hostname/path/file.php', param开发者_如何学Cs)
except urllib2.HTTPError, error:
print "Error Code: %s" % error.code
However, if I place the key/value pair information into a text file and then read the data from the text file, read from the file line by line, encode it into a dictionary, and then hand it off to the Http Request, I get the following error:
ValueError: dictionary update sequence element #0 has length 1; 2 is required
Is this error occurring because the value being passed from the file read function only returns one single argument?
This is because each line in your file is ONE string. You need a KEY, VALUE
pair to update a dictionary. If you post a sample line from your file in your question, I can show you how split it into the required KEY
and VALUE
EDIT: How to Split Lines from the text file
line = "{'hostname' : 'host', 'port' : '22', 'basedn' : 'CN=Users', 'bindusername' : 'admin', 'bindpassword' : 'passwd', 'groupname' : 'CN=Group,CN=Users,DC=tech,DC=com', 'usernameattribute' : 'name'}"
pairs = line[1:-1].replace("'", '').split(', ')
pairs = [pair.split(":") for pair in pairs]
for pair in pairs:
pair = [i.strip() for i in pair]
pass_this_in = dict(pairs)
Hope this helps
Use ast.literal_eval to parse each line into a dict. I've modified your code a little to show how it's done.
import ast
input1 = {'hostname' : 'host', 'port' : '22', 'basedn' : 'CN=Users', 'bindusername' : 'admin', 'bindpassword' : 'passwd', 'groupname' : 'CN=Group,CN=Users,DC=tech,DC=com', 'usernameattribute' : 'name'}
for line in open("/Users/rwettstein/Scripts/Files/ldap-settings.txt", "r"):
print line
# this assumes each line has a dictionary literal in it.
# you can add more robust processing (e.g. skipping empty lines
# or lines starting with #)
input = ast.literal_eval(line.strip())
time.sleep(10)
# this assumes input is a dict or a sequence of key/value tuples.
params = urllib.urlencode(input)
try:
f_handler = urlopen('https://hostname/path/file.php', params)
except urllib2.HTTPError, error:
print "Error Code: %s" % error.code
精彩评论