本文整理汇总了Python中django.core.files.storage.DefaultStorage类的典型用法代码示例。如果您正苦于以下问题:Python DefaultStorage类的具体用法?Python DefaultStorage怎么用?Python DefaultStorage使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了DefaultStorage类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: upload_file
def upload_file(request):
callback = request.POST.get("fd-callback", None)
if len(request.FILES):
file = request.FILES.get("fd-file")
file_name = file.name
else:
file_name = request.META.get("HTTP_X_FILE_NAME")
file_temp = NamedTemporaryFile()
file = File(file_temp)
chunk = request.read(1024)
while chunk:
file_temp.write(chunk)
chunk = request.read(1024)
file_temp.flush()
default_storage = DefaultStorage()
file_path = get_file_path(file_name)
file_url = "%s%s" % (settings.MEDIA_URL, file_path)
default_storage.save(file_path, file)
output = simplejson.dumps({'success': True, 'file': file_url})
if callback:
html = '<!DOCTYPE html><html><head></head><body><script type="text/javascript">try{window.top.'+callback+'('+output+')}catch(e){}</script></body></html>'
return HttpResponse(html)
else:
return HttpResponse(output, content_type='application/json; charset="utf-8"')
示例2: export_buildings
def export_buildings(export_id, export_name, export_type,
building_ids, export_model='seed.BuildingSnapshot',
selected_fields=None):
model = get_model(*export_model.split("."))
selected_buildings = model.objects.filter(pk__in=building_ids)
def _row_cb(i):
cache.set("export_buildings__%s" % export_id, i)
my_exporter = getattr(exporter, "export_%s" % export_type, None)
if not my_exporter:
_row_cb(-1) # this means there was an error
return
exported_filename = my_exporter(selected_buildings,
selected_fields,
_row_cb)
exported_file = open(exported_filename)
s3_keyname = exporter._make_export_filename(export_id,
export_name,
export_type)
s3_key = DefaultStorage().bucket.new_key(s3_keyname)
s3_key.set_contents_from_file(exported_file)
exported_file.close()
os.remove(exported_filename)
_row_cb(selected_buildings.count()) # means we're done!
示例3: render
def render(self, context):
# text typed in the tag
token = self.args["file"]
try:
filename = resolve_path(token, self.parser, context)
except PathResolutionException as e:
return self.make_error_msg(f"Path Resolution failed: {e}")
challenge = context["challenge"]
try:
filepath = safe_join(challenge.get_project_data_folder(), filename)
except SuspiciousFileOperation:
return self.make_error_msg(
f"'{filename}' cannot be opened because it is outside the current challenge."
)
storage = DefaultStorage()
try:
with storage.open(filepath, "r") as f:
contents = f.read()
except Exception as e:
return self.make_error_msg("error opening file:" + str(e))
# TODO check content safety
return contents
示例4: get_etag_data
def get_etag_data(self, user):
"""Return the ETag data for the user's avatar.
Args:
user (django.contrib.auth.models.User):
The user.
Returns:
list of unicode:
The uniquely identifying information for the user's avatar.
"""
settings_manager = self._settings_manager_class(user)
configuration = \
settings_manager.configuration_for(self.avatar_service_id)
file_hash = configuration.get('file_hash')
if not file_hash:
storage = DefaultStorage()
file_hash = md5()
with storage.open(configuration['file_path'], 'rb') as f:
file_hash.update(f.read())
configuration['file_hash'] = file_hash.hexdigest()
settings_manager.save()
return [self.avatar_service_id, file_hash]
示例5: get_avatar_urls_uncached
def get_avatar_urls_uncached(self, user, size):
"""Return the avatar URLs for the requested user.
Args:
user (django.contrib.auth.models.User):
The user whose avatar URLs are to be fetched.
size (int):
The size (in pixels) the avatar is to be rendered at.
Returns
dict:
A dictionary containing the URLs of the user's avatars at normal-
and high-DPI.
"""
storage = DefaultStorage()
settings_manager = self._settings_manager_class(user)
configuration = \
settings_manager.configuration_for(self.avatar_service_id)
if not configuration:
return {}
return {
'1x': storage.url(configuration['file_path'])
}
示例6: go
def go():
problem = get_or_none(Problem, id=id)
if not problem:
return {"success": False, "error": u"존재하지 않는 문제입니다."}
if not request.user.is_superuser and problem.user != request.user:
return {"success": False, "error": u"권한이 없습니다."}
if request.method != "POST":
return {"success": False, "error": u"POST 접근하셔야 합니다."}
file = request.FILES["file"]
md5 = md5file(file)
target_path = os.path.join("judge-attachments", md5, file.name)
storage = DefaultStorage()
storage.save(target_path, file)
new_attachment = Attachment(problem=problem, file=target_path)
new_attachment.save()
publish(
"problem-attachment-%s" % datetime.now().strftime("%s.%f"),
"problem",
"problem-attachment",
actor=request.user,
target=problem,
timestamp=datetime.now(),
admin_only=True,
verb=u"문제 {target}에 첨부파일 %s 을 추가했습니다." % file.name,
)
return {"success": True}
示例7: go
def go():
problem = get_or_none(Problem, id=id)
if not problem:
return {"success": False,
"error": u"존재하지 않는 문제입니다."}
checker = ObjectPermissionChecker(request.user)
if not checker.has_perm('edit_problem', problem) and problem.user != request.user:
return {"success": False,
"error": u"권한이 없습니다."}
if request.method != "POST":
return {"success": False,
"error": u"POST 접근하셔야 합니다."}
file = request.FILES["file"]
md5 = md5file(file)
target_path = os.path.join("judge-attachments", md5, file.name)
storage = DefaultStorage()
storage.save(target_path, file)
new_attachment = Attachment(problem=problem,
file=target_path)
new_attachment.save()
# 해당 오브젝트에 대해 아무 퍼미션이나 있으면 처리됨. 문제의 경우 PUBLISHED 일 때는 이 권한을 사용하지 않아서 안전하다
visible_users = get_users_with_perms(problem, with_group_users=False)
visible_groups = get_groups_with_perms(problem)
publish("problem-attachment-%s" % datetime.now().strftime('%s.%f'),
"problem",
"problem-attachment",
actor=request.user,
target=problem,
timestamp=datetime.now(),
visible_users=visible_users,
visible_groups=visible_groups,
verb=u"문제 {target}에 첨부파일 %s 을 추가했습니다." % file.name)
return {"success": True}
示例8: serve
def serve(request, project_name, path, document_root=None,override_permission=""):
"""
Serve static file for a given project.
This is meant as a replacement for the inefficient debug only
'django.views.static.serve' way of serving files under /media urls.
"""
if document_root == None:
document_root = settings.MEDIA_ROOT
path = posixpath.normpath(unquote(path))
path = path.lstrip('/')
newpath = ''
for part in path.split('/'):
if not part:
# Strip empty path components.
continue
drive, part = os.path.splitdrive(part)
head, part = os.path.split(part)
if part in (os.curdir, os.pardir):
# Strip '.' and '..' in path.
continue
newpath = os.path.join(newpath, part).replace('\\', '/')
if newpath and path != newpath:
return HttpResponseRedirect(newpath)
fullpath = os.path.join(document_root,project_name, newpath)
storage = DefaultStorage()
if not storage.exists(fullpath):
# On case sensitive filesystems you can have problems if the project
# nameurl in the url is not exactly the same case as the filepath.
# find the correct case for projectname then.
# Also case sensitive file systems are weird.
# who would ever want to have a folder 'data' and 'Data' contain
# different files?
projectlist = ComicSite.objects.filter(short_name=project_name)
if projectlist == []:
raise Http404(_("project '%s' does not exist" % project_name ))
project_name = projectlist[0].short_name
fullpath = os.path.join(document_root,project_name, newpath)
if not storage.exists(fullpath):
raise Http404(_('"%(path)s" does not exist') % {'path': fullpath})
if can_access(request.user,path,project_name,override_permission):
f = storage.open(fullpath, 'rb')
file = File(f) # create django file object
# Do not offer to save images, but show them directly
return serve_file(request, file, save_as=True)
else:
return HttpResponseForbidden("This file is not available without "
"credentials")
示例9: cached_large_cover_url
def cached_large_cover_url(self):
if self.large_cover_url:
digest = md5(self.large_cover_url).hexdigest()
store = DefaultStorage()
storage_name = "imdb/image/{}".format(digest)
if store.exists(storage_name):
return "{}{}".format(settings.MEDIA_URL, storage_name)
return "{}?size=full".format(reverse('movie_cover', kwargs={'movieID': self.imdb_id}))
示例10: get_dirnames
def get_dirnames(path):
""" Get all directory names in path as list of strings
Raises: OSError if directory can not be found
"""
storage = DefaultStorage()
dirnames = storage.listdir(path)[0]
dirnames.sort()
return dirnames
示例11: save
def save(self, **kwargs):
entry = super(FormEntryForm, self).save()
# entry.record_entry(self)
for field_key in self.fields:
if self.form_field_prefix in field_key:
field = self.fields[field_key]
raw_value = self._raw_value(field_key)
value = self.cleaned_value(raw_value)
model_field = field.widget.model_field
# TODO-- add secure file handling...
if value and field.widget.model_field.is_multipart:
type = raw_value.__class__.__name__
# print 'TYPE? %s'%(type)
if isinstance(raw_value, InMemoryUploadedFile) or isinstance(raw_value, TemporaryUploadedFile):
file_upload_path = join(
"form_uploads",
str(self.form_schema.slug),
str(entry.pk),
str(model_field.slug),
raw_value.name,
)
# if settings.DEBUG:
# print 'FILE UPLOAD PATH: %s'%(file_upload_path)
try:
if model_field.type == FormField.SECURE_FILE:
secure_file_storage = import_by_path(settings.SECURE_MEDIA_STORAGE)()
value = secure_file_storage.save(file_upload_path, raw_value)
key_name = "%s/%s" % (settings.AWS_MEDIA_FOLDER, value)
BaseSecureAtom.make_private(settings.AWS_STORAGE_BUCKET_NAME_MEDIA_SECURE, key_name)
else:
file_storage = DefaultStorage()
value = file_storage.save(file_upload_path, raw_value)
except:
print "Error uploading file to %s/%s" % (file_upload_path, raw_value)
value = file_upload_path
field_entry, created = self.field_model.objects.get_or_create(
form_entry=entry, form_field=field.widget.model_field
)
# if created:
# print 'created new field entry: %s, %s, %s'%(field_entry, entry.pk, field.widget.model_field.title)
# else:
# print 'Update field entry %s'%(value)
field_entry.value = field_entry.get_compressed_value(value)
field_entry.save()
return entry
示例12: value_from_datadict
def value_from_datadict(self, data, files, name):
s3_path = data.get(name, None)
if s3_path is None:
return None
mode = 'r'
storage = DefaultStorage()
storage.location = ''
name = urllib.unquote_plus(urlparse(s3_path).path.lstrip('/'))
input_file = S3BotoStorageFile(name, mode, storage)
return input_file
示例13: save_file_to_storage
def save_file_to_storage(uploaded_file):
"""
Saves an uploaded file to default storage and returns its filename.
"""
storage = DefaultStorage()
filename = storage.get_valid_name(uploaded_file.name)
with storage.open(filename, 'wb') as f:
for chunk in uploaded_file.chunks():
f.write(chunk)
return filename
示例14: parse_php_arrays
def parse_php_arrays(filename):
""" Parse a php page containing only php arrays like $x=(1,2,3). Created to parse anode09 eval results.
Returns: dict{"varname1",array1,....},
array1 is a float array
"""
verbose = False
output = {}
storage = DefaultStorage()
with storage.open(filename, "r") as f:
content = f.read()
content = content.replace("\n", "")
php = re.compile(r"\<\?php(.*?)\?\>", re.DOTALL)
s = php.search(content)
assert s is not None, (
"trying to parse a php array, but could not find anything like <? php /?> in '%s'"
% filename
)
phpcontent = s.group(1)
phpvars = phpcontent.split("$")
phpvars = [x for x in phpvars if x != ""] # remove empty
if verbose:
print("found %d php variables in %s. " % (len(phpvars), filename))
print("parsing %s into int arrays.. " % filename)
# check whether this looks like a php var
phpvar = re.compile(
r"([a-zA-Z]+[a-zA-Z0-9]*?)=array\((.*?)\);", re.DOTALL
)
for var in phpvars:
result = phpvar.search(var)
# TODO Log these messages as info
if result is None:
msg = (
"Could not match regex pattern '%s' to '%s'\
"
% (phpvar.pattern, var)
)
continue
if len(result.groups()) != 2:
msg = (
"Expected to find varname and content,\
but regex '%s' found %d items:%s "
% (
phpvar.pattern,
len(result.groups()),
"[" + ",".join(result.groups()) + "]",
)
)
continue
(varname, varcontent) = result.groups()
output[varname] = [float(x) for x in varcontent.split(",")]
return output
示例15: __call__
async def __call__(self, in_q, out_q):
"""
The coroutine for this stage.
Args:
in_q (:class:`asyncio.Queue`): The queue to receive
:class:`~pulpcore.plugin.stages.DeclarativeContent` objects from.
out_q (:class:`asyncio.Queue`): The queue to put
:class:`~pulpcore.plugin.stages.DeclarativeContent` into.
Returns:
The coroutine for this stage.
"""
storage_backend = DefaultStorage()
shutdown = False
batch = []
while not shutdown:
try:
content = in_q.get_nowait()
except asyncio.QueueEmpty:
if not batch:
content = await in_q.get()
batch.append(content)
continue
else:
batch.append(content)
continue
artifacts_to_save = []
for declarative_content in batch:
if declarative_content is None:
shutdown = True
break
for declarative_artifact in declarative_content.d_artifacts:
if declarative_artifact.artifact.pk is None:
src_path = str(declarative_artifact.artifact.file)
dst_path = declarative_artifact.artifact.storage_path(None)
with open(src_path, mode='rb') as input_file:
django_file_obj = File(input_file)
storage_backend.save(dst_path, django_file_obj)
declarative_artifact.artifact.file = dst_path
artifacts_to_save.append(declarative_artifact.artifact)
if artifacts_to_save:
Artifact.objects.bulk_create(artifacts_to_save)
for declarative_content in batch:
if declarative_content is None:
continue
await out_q.put(declarative_content)
batch = []
await out_q.put(None)