I am trying to retrieve a value from a dictionary. It works fine in one part of my code but then breaks in the next.
if user is not None:
user["Username"] = "Temp-"+user["Username"]
print "USER ID: " + str(user["ID"]) #Works fine
#Rename user in source account
patch_user(user, headers)
Patch User:
def patch_user( user, headers ):
"""Patch a User field based on their ID
"""
patched_user = request('patch_user', user["AccountID"], user, headers)
Then in request:
def request( request, account_id, user, headers):
"""Send a User request to the server
Send a request to the server
"""
url = api_root + "/accounts/" + str(account_id)
function_dictionary = {'get_user_from_id': (requests.get, #Function
(url + "/users/" + str(user),), #Tuple of Arguments
{'headers': headers}), #Dictionary of keyword args
'patch_user':(requests.patch,
(url + "/users/" + str(user["ID"]),),
{'headers': headers, 'data':json.dumps(user)})
func, args, kwargs = function_dictionary[request]
result = func(*args, **kwargs)
#Throw exception if non-200 response
result.raise_for_status()
#Result from query
print "Query " + request + " result: " + result.text
return result
I get the following error:
TypeError: string indices must be integers, not str
at (url + "/users/" + str(user["ID"]),),
Any help is appreciated!
Edit
Full Trace:
Traceback (most recent call last):
File "C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\IDE\Extensio
ns\Microsoft\Python Tools for Visual Studio\2.0\visualstudio_py_util.py", line 7
6, in exec_file
exec(code_obj, global_variables)
File "C:\Front-End\pcli-front
.py", line 179, in
user_operations.move_user(arguments[''],arguments[''],
arguments[''], headers)
File "C:\Front-End\user_opera
tions.py", line 27, in move_user
user = get_user_from_id(source_account, user_id, headers)
File "C:\Front-End\user_opera
tions.py", line 68, in get_user_from_id
user = request('get_user_from_id', account_id, user_id, headers)
File "C:\Front-End\user_opera
tions.py", line 131, in request
(url + "/users/" + str(user["ID"]),),
TypeError: string indices must be integers, not str
解决方案
Your exception is coming from an entirely different code path than you think it is. patch_user has nothing to do with it; the stack trace shows that the problem is coming from get_user_from_id.
It looks like the third argument of request means something different when called from patch_user or get_user_from_id. When patch_user calls it, user is a dict. When get_user_from_id calls it, user is a string representing a user ID. The problem is that request still tries to build the full function_dictionary regardless of which type of request it's making, so this line:
(url + "/users/" + str(user["ID"]),),
still runs even when user is a string. To fix this, you could use an else/if chain instead of the dictionary to avoid running the problematic code when it shouldn't be run, or you could divide request into separate methods for each request type.