我试图创建一个简单的键/值存储客户端,它接受来自这样的文本文件的输入
list
set foo bar
get foo
list
这是我得到的错误
Traceback (most recent call last):
File "hiringAPIv1.py", line 37, in <module>
json = json.loads(handle.read())
AttributeError: 'dict' object has no attribute 'loads'
我目前在 for 循环中为每个新命令调用 url,但我遇到了任何大于 1 行的输入文件的问题。这是我的来源,我正在使用 Python。
import urllib
import urllib2
import fileinput
import json
import pprint
urlBase = "http://hiringapi.dev.voxel.net/v1/"
f = file('input.txt', 'r')
for line in f:
contents = line.split()
#print contents
#print len(contents)
if len(contents) >= 1:
command = contents[0]
if len(contents) >= 2:
key = contents[1]
if len(contents) >= 3:
value = contents[2]
if command == 'get':
urlFinal = urlBase + "key?key=" + key
output = key
if command == 'set':
urlfinal = urlBase + "key?key=" + key + "&value=" + value
output = 'status'
if command =='list':
urlFinal = urlBase + command
#if command == 'delete':
response = urllib2.Request(urlFinal)
try:
handle = urllib2.urlopen(response)
json = json.loads(handle.read())
#pprint.pprint(json)
#pprint.pprint(json['status'])
if command == 'list':
print str(json['keys'])
else:
print str(json[output])
except IOError, e:
if hasattr(e, 'code'):
print e.code
if hasattr(e,'msg'):
print e.msg
if e.code != 401:
print 'We got another error'
print e.code
else:
print e.headers
print e.headers['www-authenticate']
f.close()