本文整理汇总了Python中filebrowser.base.FileObject类的典型用法代码示例。如果您正苦于以下问题:Python FileObject类的具体用法?Python FileObject怎么用?Python FileObject使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了FileObject类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: generate_version_add_watermark
def generate_version_add_watermark(original_path, version_suffix):
"""
Generate the given version of an image and adds watermark to it
NOTE: this function only generates a new version from original file (i.e in db) when
1. the version does not exists.
2. the modified date of original image is newer than version
:param original_path: relative path to original image
:param version_suffix: version prefix as defined in common settings
'medium'|'large'|'thumbnail'
:return: image object.
"""
from filebrowser.base import FileObject
from filebrowser.sites import site
from core.models import Image
fob = FileObject(original_path, site=site)
version_path = fob.version_path(version_suffix)
if not site.storage.isfile(version_path):
version_path = fob._generate_version(version_suffix)
# abs_path = os.path.join(settings.MEDIA_ROOT, version_path)
# Image.create_image_watermark(abs_path, abs_path, settings.WATERMARK_IMAGE_LOCATION)
elif site.storage.modified_time(original_path) > site.storage.modified_time(version_path):
version_path = fob._generate_version(version_suffix)
# abs_path = os.path.join(settings.MEDIA_ROOT, version_path)
# Image.create_image_watermark(abs_path, abs_path, settings.WATERMARK_IMAGE_LOCATION)
return FileObject(version_path, site=site)
示例2: get_teaser_image
def get_teaser_image(path, version):
if path:
image = FileObject(path)
if image.filetype == "Image":
return image.version_generate(version).url.split('adimas.info')[1]
else:
return ""
示例3: image_thumbnail
def image_thumbnail(self, obj):
if obj.image:
image = FileObject(obj.image.path)
if image.filetype == "Image":
return '<img src="%s" />' % image.version_generate(ADMIN_THUMBNAIL).url
else:
return ""
示例4: render
def render(self, context):
try:
version_suffix = self.suffix.resolve(context)
source = self.src.resolve(context)
except VariableDoesNotExist:
return None
if version_suffix not in VERSIONS:
return "" # FIXME: should this throw an error?
if isinstance(source, FileObject):
source = source.path
elif isinstance(source, File):
source = source.name
else: # string
source = source
site = context.get('filebrowser_site', get_default_site())
if FORCE_PLACEHOLDER or (SHOW_PLACEHOLDER and not site.storage.isfile(source)):
source = PLACEHOLDER
fileobject = FileObject(source, site=site)
try:
version = fileobject.version_generate(version_suffix)
context[self.var_name] = version
except Exception as e:
if settings.TEMPLATE_DEBUG:
raise e
context[self.var_name] = ""
return ""
示例5: image_thumbnail
def image_thumbnail(self):
if self.image:
image = FileObject(self.image.path)
if image.filetype == "Image":
return '<img src="%s" />' % image.version_generate('admin_thumbnail').url
else:
return ""
示例6: test_unicode_options_namer_version
def test_unicode_options_namer_version(self):
path_unicode = os.path.join(self.FOLDER_PATH, "測試文件.jpg")
expected = u"測試文件_large--680x0.jpg"
shutil.copy(self.STATIC_IMG_PATH, path_unicode)
f = FileObject(path_unicode, site=site)
version = f.version_generate("large")
self.assertEqual(version.filename, expected)
示例7: detail
def detail(self, request):
"""
Show detail page for a file.
Rename existing File/Directory (deletes existing Image Versions/Thumbnails).
"""
from filebrowser.forms import ChangeForm
query = request.GET
path = u'%s' % os.path.join(self.directory, query.get('dir', ''))
fileobject = FileObject(os.path.join(path, query.get('filename', '')), site=self)
if request.method == 'POST':
form = ChangeForm(request.POST, path=path, fileobject=fileobject, filebrowser_site=self)
if form.is_valid():
new_name = form.cleaned_data['name']
action_name = form.cleaned_data['custom_action']
try:
action_response = None
if action_name:
action = self.get_action(action_name)
# Pre-action signal
signals.filebrowser_actions_pre_apply.send(sender=request, action_name=action_name, fileobject=[fileobject], site=self)
# Call the action to action
action_response = action(request=request, fileobjects=[fileobject])
# Post-action signal
signals.filebrowser_actions_post_apply.send(sender=request, action_name=action_name, fileobject=[fileobject], result=action_response, site=self)
if new_name != fileobject.filename:
signals.filebrowser_pre_rename.send(sender=request, path=fileobject.path, name=fileobject.filename, new_name=new_name, site=self)
fileobject.delete_versions()
self.storage.move(fileobject.path, os.path.join(fileobject.head, new_name))
signals.filebrowser_post_rename.send(sender=request, path=fileobject.path, name=fileobject.filename, new_name=new_name, site=self)
messages.add_message(request, messages.SUCCESS, _('Renaming was successful.'))
if isinstance(action_response, HttpResponse):
return action_response
if "_continue" in request.POST:
redirect_url = reverse("filebrowser:fb_detail", current_app=self.name) + query_helper(query, "filename=" + new_name, "filename")
else:
redirect_url = reverse("filebrowser:fb_browse", current_app=self.name) + query_helper(query, "", "filename")
return HttpResponseRedirect(redirect_url)
except OSError:
form.errors['name'] = forms.util.ErrorList([_('Error.')])
else:
form = ChangeForm(initial={"name": fileobject.filename}, path=path, fileobject=fileobject, filebrowser_site=self)
return render(
admin_request(request, self.name),
'filebrowser/detail.html',
admin_context({
'form': form,
'fileobject': fileobject,
'query': query,
'title': u'%s' % fileobject.filename,
'is_popup': "pop" in request.GET,
'settings_var': get_settings_var(directory=self.directory),
'breadcrumbs': get_breadcrumbs(query, query.get('dir', '')),
'breadcrumbs_title': u'%s' % fileobject.filename,
'filebrowser_site': self
}, request),
)
示例8: detail
def detail(self, request):
"""
Show detail page for a file.
Rename existing File/Directory (deletes existing Image Versions/Thumbnails).
"""
from filebrowser.forms import ChangeForm
query = request.GET
abs_path = u"%s" % os.path.join(self.media_root, query.get("dir", ""))
fileobject = FileObject(
os.path.join(abs_path, query.get("filename", "")), media_root=self.media_root, media_url=self.media_url
)
if request.method == "POST":
form = ChangeForm(request.POST, path=abs_path, fileobject=fileobject, site=self)
if form.is_valid():
new_name = form.cleaned_data["name"]
action_name = form.cleaned_data["custom_action"]
try:
action_response = None
if action_name:
action = self.get_action(action_name)
# Pre-action signal
self.filebrowser_actions_pre_apply.send(
sender=request, action_name=action_name, fileobject=[fileobject]
)
# Call the action to action
action_response = action(request=request, fileobjects=[fileobject])
# Post-action signal
self.filebrowser_actions_post_apply.send(
sender=request, action_name=action_name, fileobject=[fileobject], result=action_response
)
if new_name != fileobject.filename:
self.filebrowser_pre_rename.send(
sender=request, path=fileobject.path, name=fileobject.filename, new_name=new_name
)
fileobject.delete_versions()
os.rename(fileobject.path, os.path.join(fileobject.head, new_name))
self.filebrowser_post_rename.send(
sender=request, path=fileobject.path, name=fileobject.filename, new_name=new_name
)
messages.add_message(request, messages.SUCCESS, _("Renaming was successful."))
if isinstance(action_response, HttpResponse):
return action_response
if "_continue" in request.POST:
redirect_url = reverse("filebrowser:fb_detail", current_app=self.name) + query_helper(
query, "filename=" + new_name, "filename"
)
else:
redirect_url = reverse("filebrowser:fb_browse", current_app=self.name) + query_helper(
query, "", "filename"
)
return HttpResponseRedirect(redirect_url)
except OSError, (errno, strerror):
form.errors["name"] = forms.util.ErrorList([_("Error.")])
示例9: get_image_thumbnail_html
def get_image_thumbnail_html(image):
if image:
image_fileobject = FileObject(image.path)
if image_fileobject and image_fileobject.filetype == "Image" \
and os.path.isfile(settings.MEDIA_ROOT + image.path):
str = '<img src="%s" />' % image_fileobject.version_generate(settings.FILEBROWSER_ADMIN_THUMBNAIL).url
return str
return False
else:
return False
示例10: get
def get(self, request, *args, **kwargs):
''' Receives the request '''
ctx = {'show_profile': "0"}
if 'loggedin_user_credentials' in request.session:
ctx = request.session['loggedin_user_credentials']
try:
PhotographerObj = Photographer.objects.get(user_ref=request.user)
if len(PhotographerObj.image.all()):
formargs = {'username': request.user.username, 'home_page_desc': PhotographerObj.home_page_desc}
count = 1
for k in PhotographerObj.image.all().order_by('created_date'):
if k.profile_image:
rel_path = os.path.join(os.path.join(FILEBROWSER_DIRECTORY,request.user.username) + '/', k.image.filename)
a = FileObject(rel_path)
version = a.version_generate('thumbnail').url
formargs.update({'profile_image_name': k.image.filename,
'profile_image': version})
name = 'image_' + str(count) + '_desc'
rel_path = os.path.join(os.path.join(FILEBROWSER_DIRECTORY,request.user.username) + '/', k.image.filename)
a = FileObject(rel_path)
version = a.version_generate('thumbnail').url
formargs.update({'image_' + str(count) + '_name': k.image.filename,
'image_' + str(count): version
})
formargs.update({'image_' + str(count) + '_desc': k.image_desc})
count += 1
# formargs.update({'image_1_desc': PhotographerObj.image_1_desc,
# 'image_2_desc': PhotographerObj.image_2_desc,
# 'image_3_desc': PhotographerObj.image_3_desc,
# 'image_4_desc': PhotographerObj.image_4_desc,
# })
formsubmit = self.form_class(formargs)
ctx.update({'upload_form': formsubmit})
ctx.update({'show_profile': "1"})
except Exception as e:
ctx.update({'show_profile': "0"})
pass
ctx.update({'username': request.user.username})
return Response(ctx, template_name=self.template_name)
示例11: view_tinymce_templates
def view_tinymce_templates(request):
full_path = os.path.join(settings.MEDIA_ROOT, NEWSLETTER_TINYMCE_TEMPLATE_DIR)
tmpl_dir = os.listdir(full_path)
templates = []
for tmpl in tmpl_dir:
fileobject = FileObject(os.path.join(NEWSLETTER_TINYMCE_TEMPLATE_DIR, tmpl))
templates.append('["%s", "%s"]' % (fileobject.filename, fileobject._url_full()))
page = """
var tinyMCETemplateList = [
// Name, URL, Description
%s,
];
""" % ",".join(templates)
return HttpResponse(page, mimetype='text/javascript; charset=utf8')
示例12: delete
def delete(self, request):
"Delete existing File/Directory."
query = request.GET
path = u'%s' % os.path.join(self.directory, query.get('dir', ''))
fileobject = FileObject(os.path.join(path, query.get('filename', '')), site=self)
if request.GET:
try:
signals.filebrowser_pre_delete.send(sender=request, path=fileobject.path, name=fileobject.filename, site=self)
fileobject.delete_versions()
fileobject.delete()
signals.filebrowser_post_delete.send(sender=request, path=fileobject.path, name=fileobject.filename, site=self)
messages.add_message(request, messages.SUCCESS, _('Successfully deleted %s') % fileobject.filename)
except OSError, (errno, strerror):
# TODO: define error-message
pass
示例13: test_get
def test_get(self):
""" Check the detail view and version generation. Check also renaming of files. """
response = self.client.get(self.url, {'dir': self.F_IMAGE.dirname, 'filename': self.F_IMAGE.filename})
self.assertTrue(response.status_code == 200)
# At this moment all versions should be generated. Check that.
pre_rename_versions = []
for version_suffix in VERSIONS:
path = self.F_IMAGE.version_path(version_suffix)
pre_rename_versions.append(path)
self.assertTrue(site.storage.exists(path))
# Attemp renaming the file
url = '?'.join([self.url, urlencode({'dir': self.F_IMAGE.dirname, 'filename': self.F_IMAGE.filename})])
response = self.client.post(url, {'name': 'testpic.jpg'})
# Check we get 302 response for renaming
self.assertTrue(response.status_code == 302)
# Check the file was renamed correctly:
self.assertTrue(site.storage.exists(os.path.join(self.F_IMAGE.head, 'testpic.jpg')))
# Store the renamed file
self.F_IMAGE = FileObject(os.path.join(self.F_IMAGE.head, 'testpic.jpg'), site=site)
# Check if all pre-rename versions were deleted:
for path in pre_rename_versions:
self.assertFalse(site.storage.exists(path))
# Check if all post–rename versions were deleted (resp. not being generated):
for version_suffix in VERSIONS:
path = self.F_IMAGE.version_path(version_suffix)
self.assertFalse(site.storage.exists(path))
示例14: save_file
def save_file(self, file):
"""
Little helper to save a file default save to media/temp/
"""
# original_name = file.name
# extension = os.path.splitext(original_name)[1][1:]
# filename = os.path.splitext(original_name)[0].strip('.')
# filename = filename + '__' + str(time.time()) + '.' + extension
# rel_path = os.path.join(TEMP_UPLOAD_DIR, filename)
#Create user directory in temp folder
try:
os.makedirs(os.path.join(MEDIA_ROOT, TEMP_UPLOAD_DIR))
except OSError:
# Do nothing Assume that dir is already created.
pass
try:
userdirpath = os.path.join(os.path.join(MEDIA_ROOT, TEMP_UPLOAD_DIR), self.request.user.username)
os.makedirs(userdirpath)
except OSError:
# Do nothing Assume that dir is already created.
pass
source_dir = os.path.join(MEDIA_ROOT)
destination_dir = os.path.join(source_dir,os.path.join(TEMP_UPLOAD_DIR,self.request.user.username))
ext = '.' + os.path.splitext(file.name)[1][1:]
img_name = file.name.split(ext)[0]
img_name = generate_unique_file_name(destination_dir, img_name, ext)
rel_path = os.path.join(os.path.join(TEMP_UPLOAD_DIR,self.request.user.username) + '/', img_name)
fd = open(os.path.join(MEDIA_ROOT, rel_path), 'wb')
for chunk in file.chunks():
fd.write(chunk)
fd.close()
try:
a = FileObject(rel_path)
version = a.version_generate('thumbnail').url
except Exception as e:
pass
return {'path': MEDIA_URL + rel_path, 'file': img_name, 'name': img_name, 'version': version}
示例15: test_version_attributes_3
def test_version_attributes_3(self):
"""
FileObject version attributes/methods
with alternative versions_basedir
# is_version
# original
# original_filename
# versions_basedir
# versions
# admin_versions
# version_name(suffix)
# version_generate(suffix)
"""
# new settings
filebrowser.base.VERSIONS_BASEDIR = "_versionstestdirectory"
filebrowser.base.VERSIONS = {
'admin_thumbnail': {'verbose_name': 'Admin Thumbnail', 'width': 60, 'height': 60, 'opts': 'crop'},
'large': {'verbose_name': 'Large', 'width': 600, 'height': '', 'opts': ''},
}
filebrowser.base.ADMIN_VERSIONS = ['large']
# expected test results
version_list = ['_versionstestdirectory/fb_tmp_dir/fb_tmp_dir_sub/testimage_admin_thumbnail.jpg', '_versionstestdirectory/fb_tmp_dir/fb_tmp_dir_sub/testimage_large.jpg']
admin_version_list = ['_versionstestdirectory/fb_tmp_dir/fb_tmp_dir_sub/testimage_large.jpg']
self.assertEqual(self.f_image.is_version, False)
self.assertEqual(self.f_image.original.path, self.f_image.path)
self.assertEqual(self.f_image.versions_basedir, "_versionstestdirectory")
self.assertEqual(self.f_image.versions(), version_list)
self.assertEqual(self.f_image.admin_versions(), admin_version_list)
self.assertEqual(self.f_image.version_name("large"), "testimage_large.jpg")
self.assertEqual(self.f_image.version_path("large"), "_versionstestdirectory/fb_tmp_dir/fb_tmp_dir_sub/testimage_large.jpg")
# version does not exist yet
f_version = FileObject(os.path.join(self.directory, self.tmpdir_name, "testimage_large.jpg"), site=site)
self.assertEqual(f_version.exists, False)
# generate version
f_version = self.f_image.version_generate("large")
self.assertEqual(f_version.path, "_versionstestdirectory/fb_tmp_dir/fb_tmp_dir_sub/testimage_large.jpg")
self.assertEqual(f_version.exists, True)
self.assertEqual(f_version.is_version, True)
self.assertEqual(f_version.original_filename, "testimage.jpg")
self.assertEqual(f_version.original.path, self.f_image.path)
self.assertEqual(f_version.versions(), [])
self.assertEqual(f_version.admin_versions(), [])