skip to Main Content

I have to remove control/space characters from my cache key. It is giving following error:

MemcachedKeyCharacterError: Control/space characters not allowed (key=' :1 :ZjE3MDJiNDY4NjI3OGJlY2ZmYzg4YmFhYmU2ZjRiN2E4MzU1NTMyYw==n')

The code which I am using is:

class CachedAPIView(APIView):
    def get_object(self,request):
        s = hashlib.sha1()
        s.update('Messages')
        returnData=cache.get(base64.encodestring(s.hexdigest()),None)
        if not returnData:
            obj=function(self,request.data)
            s = hashlib.sha1()
            s.update('Messages')
            cache.set(base64.encodestring(s.hexdigest()),returnData)

2

Answers


  1. The code snippet below is offered simply as a means to correct the input string, however I’m sure there is another, more specific, solution to your problem. With this invalid string, I use str.split with a : delimiter to produce a list object – and I only want the portion after the last :, so of the returned list object, I grab the last item, specifying the last index [-1], and now with the original string (excluding everything before the last :) I invoke the method .strip to remove the unwanted newline character, resulting in what I believe should be a valid string for you to use.

    >>> temp = ' :1 :ZjE3MDJiNDY4NjI3OGJlY2ZmYzg4YmFhYmU2ZjRiN2E4MzU1NTMyYw==n'
    >>> key_string = temp.split(':')[-1].strip()
    # ZjE3MDJiNDY4NjI3OGJlY2ZmYzg4YmFhYmU2ZjRiN2E4MzU1NTMyYw==
    
    Login or Signup to reply.
  2. base64.encodestring(s.hexdigest()).strip()
    

    PS. You dont need to calculate s.update('Messages') twice. You can even cash s.hexdigest().

    cache.set(…,returnData)
    

    is wrong because you don’t have returnData — you checked its absense with if not returnData. Do you mean

    cache.set(…,obj)
    

    ?

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search