コード例 #1
0
ファイル: utils.py プロジェクト: imycart/imycart
def handle_uploaded_file(f, type='other', product_sn='-1'):
    file_name = ""

    file_names = {}

    if not type.endswith('/'):
        type += '/'
    if not product_sn.endswith('/'):
        product_sn += '/'

    destination = None
    try:
        path = 'media/' + type + product_sn
        import os
        if not os.path.exists(path):
            os.makedirs(path)

        ext = f.name.split('.')[-1]
        logger.debug(str(ext))

        #允许上传的类型
        file_allow = ['JPG', 'JPEG', 'PNG', 'GIF']
        if ext.upper() not in file_allow:
            raise Exception('%s File type is not allowed to upload.' % [ext])

        random_name = str(uuid.uuid1())

        file_name = path + random_name + '.' + ext
        file_thumb_name = path + random_name + '-thumb' + '.' + ext

        destination = open(file_name, 'wb+')
        logger.debug('file_name: %s' % file_name)
        for chunk in f.chunks():
            destination.write(chunk)
        destination.close()

        result = thumbnail(file_name, file_thumb_name)
        if not result:
            raise Exception('thumbnail failed.')
        else:
            file_names['image'] = file_name
            file_names['thumb'] = file_thumb_name
            file_names['image_url'] = System_Config.get_base_url(
            ) + '/' + file_name
            file_names['thumb_url'] = System_Config.get_base_url(
            ) + '/' + file_thumb_name
    except Exception as e:
        #pass
        logger.error(str(e))
    finally:
        if destination:
            destination.close()
    return file_names
コード例 #2
0
ファイル: utils.py プロジェクト: imycart/imycart
def handle_uploaded_file(f,type='other',product_sn='-1'):
	file_name = ""

	file_names = {}
	
	if not type.endswith('/'):
		type += '/'
	if not product_sn.endswith('/'):
		product_sn += '/'
	
	destination = None
	try:
		path = 'media/' + type + product_sn
		import os
		if not os.path.exists(path):
			os.makedirs(path)
			
		ext = f.name.split('.')[-1]
		logger.debug(str(ext))
		
		#允许上传的类型
		file_allow = ['JPG','JPEG','PNG','GIF']
		if ext.upper() not in file_allow:
			raise Exception('%s File type is not allowed to upload.' % [ext])
		
		random_name = str(uuid.uuid1())
		
		file_name = path + random_name + '.' + ext
		file_thumb_name = path + random_name + '-thumb' + '.' + ext
		
		destination = open(file_name, 'wb+')
		logger.debug('file_name: %s' % file_name)
		for chunk in f.chunks():
			destination.write(chunk)
		destination.close()
		
		result = thumbnail(file_name,file_thumb_name)
		if not result:
			raise Exception('thumbnail failed.')
		else:
			file_names['image'] = file_name
			file_names['thumb'] = file_thumb_name
			file_names['image_url'] = System_Config.get_base_url() + '/' + file_name
			file_names['thumb_url'] = System_Config.get_base_url() + '/' + file_thumb_name
	except Exception as e:
		#pass
		logger.error(str(e))
	finally:
		if destination:
			destination.close()
	return file_names
コード例 #3
0
ファイル: myuser.py プロジェクト: imycartorg/imycart
def forget_password(request):
	ctx = {}
	ctx['system_para'] = get_system_parameters()
	ctx['menu_products'] = get_menu_products()
	ctx['page_name'] = 'Forget Password'
	ctx = add_captcha(ctx) #添加验证码
	if request.method == 'GET':
		ctx['form_display'] = ''
		ctx['success_display'] = 'display:none;'
		return render(request,System_Config.get_template_name() + '/forget_password.html',ctx)
	else:
		form = captcha_form(request.POST) # 获取Post表单数据
		if form.is_valid():
			ctx['form_display'] = 'display:none;'
			ctx.update(csrf(request))
			s_uuid = str(uuid.uuid4())
			reset_password = Reset_Password.objects.create(email=request.POST['email'],validate_code=s_uuid,apply_time=datetime.datetime.now(),expirt_time=(datetime.datetime.now() + datetime.timedelta(hours=24)),is_active=True)
			mail_ctx = {}
			mail_ctx['reset_url'] =  System_Config.get_base_url() + "/user/reset-password?email=" + reset_password.email + "&validate_code=" + reset_password.validate_code
			my_send_mail(useage='reset_password',ctx=mail_ctx,send_to=reset_password.email,title=_('You are resetting you password in %(site_name)s .') % {'site_name':System_Config.objects.get(name='site_name').val})
			ctx['apply_message'] = _('If there is an account associated with %(email_address)s you will receive an email with a link to reset your password.') % {'email_address':reset_password.email}
			ctx['success_display'] = ''
		else:
			ctx['apply_message'] = _('Please check your verify code.')
		return render(request,System_Config.get_template_name() + '/forget_password.html',ctx)
コード例 #4
0
def handle_uploaded_attachment_file(f,
                                    f2,
                                    type='other',
                                    product_sn='-1',
                                    file_name_type='random',
                                    manual_name='noname',
                                    same_name_handle='reject'):
    file_name = ""

    file_names = {}
    if f2 is None:
        f2 = f

    if not type.endswith('/'):
        type += '/'
    if not product_sn.endswith('/'):
        product_sn += '/'

    destination = None
    try:
        # path = 'media/' + type + product_sn
        path = 'media/' + 'product/' + product_sn + type
        logger.debug('查看product_sn' + product_sn)
        logger.debug('查看路径' + path)

        import os
        if not os.path.exists(path):
            os.makedirs(path)

        ext = f.name.split('.')[-1]
        ext2 = f2.name.split('.')[-1]
        logger.debug('filename origin:' + str(f.name))
        logger.debug('filename origin:' + str(f2.name))
        logger.debug(str(ext))
        logger.debug(str(ext2))
        # 允许上传的类型
        file_allow = ['JPG', 'JPEG', 'PNG', 'GIF', 'PDF', 'ZIP', 'RAR']
        if ext.upper() not in file_allow:
            raise Exception('%s File type is not allowed to upload.' % [ext])
        if ext2.upper() not in file_allow:
            raise Exception('%s File type is not allowed to upload.' % [ext])
        # 20160616,koala加入对文件名生成的生成规则
        real_name = ''
        real_thumb = ''

        real_path = path
        if file_name_type == 'random':
            random_name = str(uuid.uuid1())
            file_name = path + random_name + '.' + ext
            file_thumb_name = path + random_name + '-thumb' + '.' + ext2
            real_name = random_name + '.' + ext
            real_thumb = random_name + '-thumb' + '.' + ext2

        elif file_name_type == 'origin':

            file_name = path + f.name
            name_list_tmp = f.name.split('.')
            length = len(name_list_tmp)
            name_list_tmp[length - 2] = name_list_tmp[length - 2] + '-thumb'
            file_thumb_name = path + f2.name

            real_name = f.name
            real_thumb = f2.name

        elif file_name_type == 'manual':
            file_name = path + manual_name + '.' + ext
            file_thumb_name = path + manual_name + '-thumb' + '.' + ext2
            real_name = manual_name + '.' + ext
            real_thumb = manual_name + '-thumb' + '.' + ext2

        else:
            raise Exception('file upload failed')

        logger.info('real_name : %s' % (real_name))
        logger.info('thumb_name : %s' % (real_thumb))
        # 判断文件是否已经存在
        if os.path.exists(file_name):
            if same_name_handle == 'reject':
                file_names['upload_result'] = False
                file_names['upload_error_msg'] = 'File already exists.'
                raise Exception('File already exists.')
            elif same_name_handle == 'rewrite':
                # 覆盖,无需处理
                pass
            else:
                raise Exception('No such method: %s' % same_name_handle)

        destination = open(file_name, 'wb+')
        logger.debug('file_name: %s' % file_name)
        for chunk in f.chunks():
            destination.write(chunk)
        destination.close()

        destination2 = open(file_thumb_name, 'wb+')
        logger.debug('file_thumb_name: %s' % file_thumb_name)
        for chunk in f2.chunks():
            destination2.write(chunk)
        destination2.close()

        # result = thumbnail(file_name, file_thumb_name)
        # if not result:
        #	  file_names['upload_result'] = False
        # file_names['upload_error_msg'] = 'Thumbnail failed.'
        # raise Exception('Thumbnail failed.')
        # else:

        file_names['upload_result'] = True

        file_names['image'] = file_name

        file_names['thumb'] = file_thumb_name

        file_names['real_name'] = real_name

        file_names['real_thumb'] = real_thumb

        file_names['real_path'] = real_path

        file_names['image_url'] = System_Config.get_base_url(
        ) + '/' + file_name

        file_names['thumb_url'] = System_Config.get_base_url(
        ) + '/' + file_thumb_name

    except Exception as e:
        # pass
        logger.error(str(e))
    finally:
        if destination:
            destination.close()
    return file_names
コード例 #5
0
def handle_uploaded_file(f,
                         type='other',
                         product_sn='-1',
                         file_name_type='random',
                         manual_name='noname',
                         same_name_handle='reject',
                         scale_param=(False, 1280, 1280)):
    file_name = ""

    file_names = {}

    if not type.endswith('/'):
        type += '/'
    if not product_sn.endswith('/'):
        product_sn += '/'

    destination = None
    try:
        path = 'media/' + type + product_sn + 'images/'
        import os
        if not os.path.exists(path):
            os.makedirs(path)

        ext = f.name.split('.')[-1]
        logger.debug('filename origin:' + str(f.name))
        logger.debug(str(ext))

        # 允许上传的类型
        file_allow = ['JPG', 'JPEG', 'PNG', 'GIF']
        try:
            file_allow_list = System_Config.objects.get(
                name='file_upload_allow').val
            file_allow = file_allow_list.split(',')
        except Exception as err:
            logger.info(
                'File upload allow did not set. Default is [JPG,JPEG,PNG,GIF]. Error Message:%s'
                % err)

        if ext.upper() not in file_allow:
            file_names['upload_result'] = False
            file_names['upload_error_msg'] = '%s 类型的文件不允许上传。只能上传 %s 类型的文件。' % (
                ext, file_allow)
            return file_names
            #raise Exception('%s File type is not allowed to upload.' % [ext])

        # 20160616,koala加入对文件名生成的生成规则
        real_name = ''
        real_thumb = ''
        real_path = path
        if file_name_type == 'random':
            random_name = str(uuid.uuid1())
            file_name = path + random_name + '.' + ext
            file_thumb_name = path + random_name + '-thumb' + '.' + ext
            real_name = random_name + '.' + ext
            real_thumb = random_name + '-thumb' + '.' + ext
        elif file_name_type == 'origin':

            file_name = path + f.name
            name_list_tmp = f.name.split('.')
            length = len(name_list_tmp)
            name_list_tmp[length - 2] = name_list_tmp[length - 2] + '-thumb'
            file_thumb_name = path + '.'.join(name_list_tmp)

            real_name = f.name
            real_thumb = '.'.join(name_list_tmp)

        elif file_name_type == 'manual':
            file_name = path + manual_name + '.' + ext
            file_thumb_name = path + manual_name + '-thumb' + '.' + ext

            real_name = manual_name + '.' + ext
            real_thumb = manual_name + '-thumb' + '.' + ext

        else:
            raise Exception('file upload failed')

        logger.info('real_name : %s , real_thumb : %s' %
                    (real_name, real_thumb))

        # 判断文件是否已经存在
        if os.path.exists(file_name):
            if same_name_handle == 'reject':
                file_names['upload_result'] = False
                file_names['upload_error_msg'] = 'File already exists.'
                raise Exception('File already exists.')
            elif same_name_handle == 'rewrite':
                # 覆盖,无需处理
                pass
            else:
                raise Exception('No such method: %s' % same_name_handle)

        destination = open(file_name, 'wb+')
        logger.debug('file_name: %s' % file_name)
        for chunk in f.chunks():
            destination.write(chunk)
        destination.close()

        #对太大的文件,进行缩放
        if scale_param[0]:
            scale_result = thumbnail(file_name, '', 'scale', scale_param[1],
                                     scale_param[2])

        result = thumbnail(file_name, file_thumb_name)
        if not result:
            file_names['upload_result'] = False
            file_names['upload_error_msg'] = 'Thumbnail failed.'
            raise Exception('Thumbnail failed.')
        else:
            file_names['upload_result'] = True
            file_names['image'] = file_name
            file_names['thumb'] = file_thumb_name
            file_names['real_name'] = real_name
            file_names['real_thumb'] = real_thumb
            file_names['real_path'] = real_path
            file_names['image_url'] = System_Config.get_base_url(
            ) + '/' + file_name
            file_names['thumb_url'] = System_Config.get_base_url(
            ) + '/' + file_thumb_name
    except Exception as e:
        # pass
        logger.error(str(e))
    finally:
        if destination:
            destination.close()
    return file_names
コード例 #6
0
ファイル: utils.py プロジェクト: imycartorg/imycart
def handle_uploaded_file(f,type='other',product_sn='-1',file_name_type='random',manual_name='noname',same_name_handle='reject'):
	file_name = ""

	file_names = {}
	
	if not type.endswith('/'):
		type += '/'
	if not product_sn.endswith('/'):
		product_sn += '/'
	
	destination = None
	try:
		path = 'media/' + type + product_sn
		import os
		if not os.path.exists(path):
			os.makedirs(path)
			
		ext = f.name.split('.')[-1]
		logger.debug('filename origin:' + str(f.name))
		logger.debug(str(ext))
		
		#允许上传的类型
		file_allow = ['JPG','JPEG','PNG','GIF']
		if ext.upper() not in file_allow:
			raise Exception('%s File type is not allowed to upload.' % [ext])
		
		#20160616,koala加入对文件名生成的生成规则
		if file_name_type == 'random':
			random_name = str(uuid.uuid1())
			file_name = path + random_name + '.' + ext
			file_thumb_name = path + random_name + '-thumb' + '.' + ext
		elif file_name_type == 'origin':
			file_name = path + f.name
			name_list_tmp = f.name.split('.')
			length = len(name_list_tmp)
			name_list_tmp[length-2] = name_list_tmp[length-2] + '-thumb'
			file_thumb_name = path + '.'.join(name_list_tmp)
		elif file_name_type == 'manual':
			file_name = path + manual_name + '.' + ext
			file_thumb_name = path + manual_name + '-thumb' + '.' + ext
			logger.debug('file_name is : %s' % file_name)
		else:
			raise Exception('file upload failed')
		
		# 判断文件是否已经存在
		if os.path.exists(file_name):
			if same_name_handle == 'reject':
				file_names['upload_result'] = False
				file_names['upload_error_msg'] = 'File already exists.'
				raise Exception('File already exists.')
			elif same_name_handle == 'rewrite':
				#覆盖,无需处理
				pass
			else:
				raise Exception('No such method: %s' % same_name_handle)
		
		destination = open(file_name, 'wb+')
		logger.debug('file_name: %s' % file_name)
		for chunk in f.chunks():
			destination.write(chunk)
		destination.close()
		
		result = thumbnail(file_name,file_thumb_name)
		if not result:
			file_names['upload_result'] = False
			file_names['upload_error_msg'] = 'Thumbnail failed.'
			raise Exception('Thumbnail failed.')
		else:
			file_names['upload_result'] = True
			file_names['image'] = file_name
			file_names['thumb'] = file_thumb_name
			file_names['image_url'] = System_Config.get_base_url() + '/' + file_name
			file_names['thumb_url'] = System_Config.get_base_url() + '/' + file_thumb_name
	except Exception as e:
		#pass
		logger.error(str(e))
	finally:
		if destination:
			destination.close()
	return file_names
コード例 #7
0
ファイル: utils.py プロジェクト: icetusorg/cetusshop
def handle_uploaded_file(f, type='other', product_sn='-1', file_name_type='random', manual_name='noname',
						 same_name_handle='reject',scale_param=(False,1280,1280)):
	file_name = ""

	file_names = {}

	if not type.endswith('/'):
		type += '/'
	if not product_sn.endswith('/'):
		product_sn += '/'

	destination = None
	try:
		path = 'media/' + type + product_sn + 'images/'
		import os
		if not os.path.exists(path):
			os.makedirs(path)

		ext = f.name.split('.')[-1]
		logger.debug('filename origin:' + str(f.name))
		logger.debug(str(ext))

		# 允许上传的类型
		file_allow = ['JPG', 'JPEG', 'PNG', 'GIF']
		try:
			file_allow_list = System_Config.objects.get(name='file_upload_allow').val
			file_allow = file_allow_list.split(',')
		except Exception as err:
			logger.info('File upload allow did not set. Default is [JPG,JPEG,PNG,GIF]. Error Message:%s' % err)
		
		if ext.upper() not in file_allow:
			file_names['upload_result'] = False
			file_names['upload_error_msg'] = '%s 类型的文件不允许上传。只能上传 %s 类型的文件。' % (ext,file_allow)
			return file_names
			#raise Exception('%s File type is not allowed to upload.' % [ext])

		# 20160616,koala加入对文件名生成的生成规则
		real_name = ''
		real_thumb = ''
		real_path = path
		if file_name_type == 'random':
			random_name = str(uuid.uuid1())
			file_name = path + random_name + '.' + ext
			file_thumb_name = path + random_name + '-thumb' + '.' + ext
			real_name = random_name + '.' + ext
			real_thumb = random_name + '-thumb' + '.' + ext
		elif file_name_type == 'origin':

			file_name = path + f.name
			name_list_tmp = f.name.split('.')
			length = len(name_list_tmp)
			name_list_tmp[length - 2] = name_list_tmp[length - 2] + '-thumb'
			file_thumb_name = path + '.'.join(name_list_tmp)

			real_name = f.name
			real_thumb = '.'.join(name_list_tmp)

		elif file_name_type == 'manual':
			file_name = path + manual_name + '.' + ext
			file_thumb_name = path + manual_name + '-thumb' + '.' + ext

			real_name = manual_name + '.' + ext
			real_thumb = manual_name + '-thumb' + '.' + ext

		else:
			raise Exception('file upload failed')

		logger.info('real_name : %s , real_thumb : %s' % (real_name, real_thumb))

		# 判断文件是否已经存在
		if os.path.exists(file_name):
			if same_name_handle == 'reject':
				file_names['upload_result'] = False
				file_names['upload_error_msg'] = 'File already exists.'
				raise Exception('File already exists.')
			elif same_name_handle == 'rewrite':
				# 覆盖,无需处理
				pass
			else:
				raise Exception('No such method: %s' % same_name_handle)

		destination = open(file_name, 'wb+')
		logger.debug('file_name: %s' % file_name)
		for chunk in f.chunks():
			destination.write(chunk)
		destination.close()
		
		#对太大的文件,进行缩放
		if scale_param[0]:
			scale_result = thumbnail(file_name,'','scale',scale_param[1],scale_param[2])

		result = thumbnail(file_name, file_thumb_name)
		if not result:
			file_names['upload_result'] = False
			file_names['upload_error_msg'] = 'Thumbnail failed.'
			raise Exception('Thumbnail failed.')
		else:
			file_names['upload_result'] = True
			file_names['image'] = file_name
			file_names['thumb'] = file_thumb_name
			file_names['real_name'] = real_name
			file_names['real_thumb'] = real_thumb
			file_names['real_path'] = real_path
			file_names['image_url'] = System_Config.get_base_url() + '/' + file_name
			file_names['thumb_url'] = System_Config.get_base_url() + '/' + file_thumb_name
	except Exception as e:
		# pass
		logger.error(str(e))
	finally:
		if destination:
			destination.close()
	return file_names