skip to Main Content

I am trying to save the value in Memcache but facing below error for value (for ñ in canada)

"last_name":"Cañada Herrador","personal_space_id":105175

pymemcache.exceptions.MemcacheIllegalInputError: Data values must be binary-safe: ‘ascii’ codec can’t encode character ‘xf1’ in position 61: ordinal not in range(128)

How can I save Unicode characters in memcache, as by default it only supports ASCII char?

2

Answers


  1. How can I save Unicode characters in memcache, as by default it only supports ASCII char?

    You might harness base64 built-in module for this task, but beware that if used with ASCII-only text it will take more space than text itself, consider following example:

    import base64
    last_name = "Cañada Herrador"
    encoded_last_name = base64.b64encode(last_name.encode("utf-8")).decode("ascii")
    # now encoded_last_name is ASCII str which you can use with memcache
    print(encoded_last_name)  # Q2HDsWFkYSBIZXJyYWRvcg==
    # after retrieving to get original string do
    decoded_last_name = base64.b64decode(encoded_last_name).decode("utf-8")
    print(decoded_last_name)  # Cañada Herrador
    
    Login or Signup to reply.
  2. You can use string.encode() function, but you have to decide how to deal with unicode characters. Here https://docs.python.org/3/howto/unicode.html#converting-to-bytes, you have all the options and explanations.

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