金字塔中上传的文件的md5

时间:2018-07-22 22:27:39

标签: python-2.7 md5 pyramid

@view_config(route_name='home',request_method='GET')
def home(request):
    return Response('''<form method="post" enctype="multipart/form-data">
    Select image to upload:
    <input type="file" name="fileToUpload" id="fileToUpload">
    <input type="submit" value="Upload Image" name="submit">
</form>''')

@view_config(route_name='home',request_method='POST')
def dj(request):
    file = request.params['fileToUpload']
    return Response(md5(file))

    def md5(fname):
    hash_md5 = hashlib.md5()
    with open(fname, "rb") as f:
        for chunk in iter(lambda: f.read(4096), b""):
            hash_md5.update(chunk)
    return hash_md5.hexdigest()

此代码给出TypeError:强制转换为Unicode:需要字符串或缓冲区,找到实例如何解决该问题? 我试图获取文件的md5哈希值,它可能很大,所以我试图以块的形式获取它,以免使内存过载。终端发送以下Traceback:

Traceback (most recent call last):
  File "c:\python27\lib\wsgiref\handlers.py", line 85, in run
    self.result = application(self.environ, self.start_response)
  File "c:\python27\lib\site-packages\pyramid\router.py", line 236, in __call__
    response = self.invoke_subrequest(request, use_tweens=True)
  File "c:\python27\lib\site-packages\pyramid\router.py", line 211, in invoke_subrequest
    response = handle_request(request)
  File "c:\python27\lib\site-packages\pyramid\tweens.py", line 62, in excview_tween
    reraise(*attrs['exc_info'])
  File "c:\python27\lib\site-packages\pyramid\tweens.py", line 22, in excview_tween
    response = handler(request)
  File "c:\python27\lib\site-packages\pyramid\router.py", line 158, in handle_request
    view_name
  File "c:\python27\lib\site-packages\pyramid\view.py", line 547, in _call_view
    response = view_callable(context, request)
  File "c:\python27\lib\site-packages\pyramid\config\views.py", line 182, in __call__
    return view(context, request)
  File "c:\python27\lib\site-packages\pyramid\viewderivers.py", line 393, in attr_view
    return view(context, request)
  File "c:\python27\lib\site-packages\pyramid\viewderivers.py", line 371, in predicate_wrapper
    return view(context, request)
  File "c:\python27\lib\site-packages\pyramid\viewderivers.py", line 413, in viewresult_to_response
    result = view(context, request)
  File "c:\python27\lib\site-packages\pyramid\viewderivers.py", line 147, in _requestonly_view
    response = view(request)
  File "c:\users\balendra\desktop\myapp\myapp\views.py", line 23, in dj
    return Response(md5(file))
  File "c:\users\balendra\desktop\myapp\myapp\views.py", line 33, in md5
    with open(fname, "rb") as f:
TypeError: coercing to Unicode: need string or buffer, instance found

1 个答案:

答案 0 :(得分:0)

看起来您的文件名(fname)不是字符串。