TypeError:无法将字节连接到int

时间:2014-06-28 08:13:57

标签: python

我正在尝试哈希文件名然后保存到DB中。我正在使用Flask和Python 3.4

这是上传代码:

@app.route('/', methods=['GET', 'POST'])
def upload_pic():
    if request.method == 'POST':
        file = request.files['file']
        try:
            extension = file.filename.rsplit('.', 1)[1].lower()
        except IndexError as e:
            abort(404)
        if file and check_extension(extension):
            # Salt and hash the file contents
            filename = md5(file.read() + str(round(time.time() * 1000))).hexdigest() + '.' + extension
            file.seek(0)  # Move cursor back to beginning so we can write to disk
            file.save(os.path.join(app.config['UPLOAD_DIR'], filename))
            add_pic(filename)
            gen_thumbnail(filename)
            return redirect(url_for('show_pic', filename=filename))
        else:  # Bad file extension
            abort(404)
    else:
        return render_template('upload.html')

当我发布表单时,我会收到此错误回溯。

Traceback (most recent call last):
  File "C:\Python34\lib\site-packages\flask\app.py", line 1836, in __call__
    return self.wsgi_app(environ, start_response)
  File "C:\Python34\lib\site-packages\flask\app.py", line 1820, in wsgi_app
    response = self.make_response(self.handle_exception(e))
  File "C:\Python34\lib\site-packages\flask\app.py", line 1403, in handle_exception
    reraise(exc_type, exc_value, tb)
  File "C:\Python34\lib\site-packages\flask\_compat.py", line 33, in reraise
    raise value
  File "C:\Python34\lib\site-packages\flask\app.py", line 1817, in wsgi_app
    response = self.full_dispatch_request()
  File "C:\Python34\lib\site-packages\flask\app.py", line 1477, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "C:\Python34\lib\site-packages\flask\app.py", line 1381, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File "C:\Python34\lib\site-packages\flask\_compat.py", line 33, in reraise
    raise value
  File "C:\Python34\lib\site-packages\flask\app.py", line 1475, in full_dispatch_request
    rv = self.dispatch_request()
  File "C:\Python34\lib\site-packages\flask\app.py", line 1461, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "C:\Users\Ajay\PycharmProjects\codehackr-upload\flaskgur.py", line 70, in upload_pic
    filename = md5(file.read() + (round(time.time() * 1000))).hexdigest() + '.' + extension
TypeError: can't concat bytes to int

我不知道发生了什么错误,请赐教。

感谢。

1 个答案:

答案 0 :(得分:4)

您正在尝试将file.read()的结果与round(time.time() * 1000))的结果连接起来,这是一个整数。这就是你收到错误的原因:

TypeError: can't concat bytes to int

尝试转换整数:

file.read() + bytes(round(time.time() * 1000)))

但正如@Lev Levitsky所注意到的,看起来您的代码已经有了更正:您确定要运行代码的最新版本吗?