TypeError:在散列之前必须对Unicode对象进行编码有什么问题?

时间:2018-03-26 10:08:53

标签: python django

我收到错误,TypeError:必须在散列之前对Unicode对象进行编码。 我写了代码,

        user = Data()
        passwd = request.data['password']

        md5 = hashlib.md5()
        md5.update(passwd)

        user.password = md5.hexdigest()
        print(user.password)

        user.save()

Traceback说

Traceback (most recent call last):
  File "/usr/local/lib/python3.6/site-packages/django/core/handlers/exception.py", line 35, in inner
    response = get_response(request)
  File "/usr/local/lib/python3.6/site-packages/django/core/handlers/base.py", line 128, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "/usr/local/lib/python3.6/site-packages/django/core/handlers/base.py", line 126, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/usr/local/lib/python3.6/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view
    return view_func(*args, **kwargs)
  File "/usr/local/lib/python3.6/site-packages/rest_framework/viewsets.py", line 95, in view
    return self.dispatch(request, *args, **kwargs)
  File "/usr/local/lib/python3.6/site-packages/rest_framework/views.py", line 494, in dispatch
    response = self.handle_exception(exc)
  File "/usr/local/lib/python3.6/site-packages/rest_framework/views.py", line 454, in handle_exception
    self.raise_uncaught_exception(exc)
  File "/usr/local/lib/python3.6/site-packages/rest_framework/views.py", line 491, in dispatch
    response = handler(request, *args, **kwargs)
  File "/opt/project/app/views.py", line 27, in create
    md5.update(passwd)

我在代码顶部添加了#coding:utf-8,但发生了同样的错误。我的代码出了什么问题?我应该如何解决这个问题?

1 个答案:

答案 0 :(得分:3)

错误告诉您需要执行的操作:将密码编码为字节字符串。

md5.update(passwd.encode('utf-8'))

注意尽管你可能根本不应该这样做;如果要使用用户密码,请使用用户模型的set_password()方法。

(请不要随意向您的脚本添加编码声明;这只会影响文件中的文字字符。)