Python 2.6.5和Django框架中的“不支持的哈希类型”错误

1 投票
3 回答
1654 浏览
提问于 2025-04-16 07:05

我的注册表单在自定义注册表单的密码字段中,在执行 form.save() 时出现了一个值错误(ValueError)。

这里是异常的详细信息(复制自 http://www.pastie.org/1299144):

Environment:

Request Method: POST
Request URL: http://192.168.2.206:8080/register/
Django Version: 1.1.1
Python Version: 2.6.5
Installed Applications:
['django.contrib.auth',
 'django.contrib.admin',
 'django.contrib.contenttypes',
 'django.contrib.markup',
 'django.contrib.sessions',
 'django.contrib.sites',
 'django.contrib.comments',
 'mysite.registration',
 'mysite.profiles',
 'mysite.epw',
 'mysite.remember_me',
 'mysite.avatar',
 'mysite.django_documents',
 'mysite.inlines',
 'mysite.blog',
 'mysite.forum',
 'tagging']
Installed Middleware:
('django.middleware.cache.UpdateCacheMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.cache.FetchFromCacheMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'mysite.remember_me.views.AutoLogout')


Traceback:
File "/usr/lib/pymodules/python2.6/django/core/handlers/base.py" in get_response
  92.                 response = callback(request, *callback_args, **callback_kwargs)
File "/usr/lib/pymodules/python2.6/django/utils/decorators.py" in _wrapped_view
  48.                 response = view_func(request, *args, **kwargs)
File "/home/karthik/Desktop/EPW_LOCAL/mysite/../mysite/epw/views.py" in register
  1538.             new_user = form.save(request)
File "/home/karthik/Desktop/EPW_LOCAL/mysite/../mysite/epw/form.py" in save
  169.                                                                     profile_callback=profile_callback)
File "/home/karthik/Desktop/EPW_LOCAL/mysite/../mysite/registration/models.py" in create_inactive_user
  110.         registration_profile = self.create_profile(new_user)
File "/home/karthik/Desktop/EPW_LOCAL/mysite/../mysite/registration/models.py" in create_profile
  145.         salt = hashlib.new(str(random.random())).hexdigest()[:5]
File "/usr/lib/python2.6/hashlib.py" in __hash_new
  101.         return __get_builtin_constructor(name)(string)
File "/usr/lib/python2.6/hashlib.py" in __get_builtin_constructor
  80.     raise ValueError, "unsupported hash type"

Exception Type: ValueError at /register/
Exception Value: unsupported hash type

请问有没有人能解决这个问题。谢谢!

3 个回答

0

在保存密码的时候,我用的是sha这种加密算法,而不是hashlib,效果很好。

1

haslib.new() 这个函数需要你传入一个哈希算法的名字,比如 "md5" 或 "sha1" 之类的,作为第一个参数。可是你现在传入的是一个随机的字符串。

4

看起来你想自己实现一个注册框架。现有的框架有什么问题吗?我觉得你应该多了解一下Django框架的基本知识,并且看看相关的教程。

从这个错误信息来看,问题出在这一行 hashlib.new(str(random.random())).hexdigest()[:5]。 (熟悉一下如何查看错误信息,并找出问题所在,这在你犯错时会经常用到。)

help(hashlib.new) 显示了这个内容:

__hash_new(name, string='')
    new(name, string='') - Return a new hashing object using the named algorithm;
    optionally initialized with a string.

这里的“命名算法”应该是md5、sha1、sha256等。(你可以查看 help(hashlib) 来获取完整列表,并了解如何使用,比如用 hashlib.md5() 而不是 hashlib.new('md5')。)

撰写回答