本文整理汇总了Python中corehq.apps.hqmedia.models.CommCareImage类的典型用法代码示例。如果您正苦于以下问题:Python CommCareImage类的具体用法?Python CommCareImage怎么用?Python CommCareImage使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了CommCareImage类的14个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: choose_media
def choose_media(request, domain, app_id):
# TODO: Add error handling
app = get_app(domain, app_id)
media_type = request.POST['media_type']
media_id = request.POST['id']
if media_type == 'Image':
file = CommCareImage.get(media_id)
elif media_type == 'Audio':
file = CommCareImage.get(media_id)
else:
raise Http404()
if file is None or not file.is_shared:
return HttpResponse(json.dumps({
'match_found': False
}))
file.add_domain(domain)
app.create_mapping(file, request.POST['path'])
if media_type == 'Image':
return HttpResponse(json.dumps({
'match_found': True,
'image': {'m_id': file._id, 'url': file.url()},
'file': True
}))
elif media_type == 'Audio':
return HttpResponse(json.dumps({'match_found': True, 'audio': {'m_id': file._id, 'url': file.url()}}))
else:
raise Http404()
示例2: choose_media
def choose_media(request, domain, app_id):
# TODO: Add error handling
app = get_app(domain, app_id)
media_type = request.POST["media_type"]
media_id = request.POST["id"]
if media_type == "Image":
file = CommCareImage.get(media_id)
elif media_type == "Audio":
file = CommCareImage.get(media_id)
else:
raise Http404()
if file is None or not file.is_shared:
return HttpResponse(json.dumps({"match_found": False}))
file.add_domain(domain)
app.create_mapping(file, request.POST["path"])
if media_type == "Image":
return HttpResponse(
json.dumps({"match_found": True, "image": {"m_id": file._id, "url": file.url()}, "file": True})
)
elif media_type == "Audio":
return HttpResponse(json.dumps({"match_found": True, "audio": {"m_id": file._id, "url": file.url()}}))
else:
raise Http404()
示例3: test_multimedia
def test_multimedia(self):
from corehq.apps.hqmedia.models import CommCareAudio, CommCareImage, CommCareVideo
image_path = os.path.join('corehq', 'apps', 'hqwebapp', 'static', 'hqwebapp', 'img', 'commcare-hq-logo.png')
with open(image_path, 'r') as f:
image_data = f.read()
image = CommCareImage.get_by_data(image_data)
image.attach_data(image_data, original_filename='logo.png')
image.add_domain(self.domain_name)
self.assertEqual(image_data, image.get_display_file(False))
audio_data = 'fake audio data'
audio = CommCareAudio.get_by_data(audio_data)
audio.attach_data(audio_data, original_filename='tr-la-la.mp3')
audio.add_domain(self.domain_name)
self.assertEqual(audio_data, audio.get_display_file(False))
video_data = 'fake video data'
video = CommCareVideo.get_by_data(video_data)
video.attach_data(video_data, 'kittens.mp4')
video.add_domain(self.domain_name)
self.assertEqual(video_data, video.get_display_file(False))
fakedb = self._dump_and_load([image, audio, video])
copied_image = CommCareImage.wrap(fakedb.get(image._id))
copied_audio = CommCareAudio.wrap(fakedb.get(audio._id))
copied_video = CommCareVideo.wrap(fakedb.get(video._id))
self.assertEqual(image_data, copied_image.get_display_file(False))
self.assertEqual(audio_data, copied_audio.get_display_file(False))
self.assertEqual(video_data, copied_video.get_display_file(False))
示例4: test_add_domain_to_media
def test_add_domain_to_media(self):
self.image.valid_domains.remove(self.master_app_with_report_modules.domain)
self.image.save()
image = CommCareImage.get(self.image._id)
self.assertNotIn(self.master_app_with_report_modules.domain, image.valid_domains)
image_path = 'jr://file/commcare/case_list_image.jpg'
self.master_app_with_report_modules.get_module(0).set_icon('en', image_path)
self.master_app_with_report_modules.create_mapping(self.image, image_path, save=False)
missing_media = _get_missing_multimedia(self.master_app_with_report_modules)
self.assertEqual(missing_media, [])
image = CommCareImage.get(self.image._id)
self.assertIn(self.master_app_with_report_modules.domain, image.valid_domains)
示例5: get
def get(self, request, *args, **kwargs):
data, content_type = self.multimedia.get_display_file()
if self.thumb:
data = CommCareImage.get_thumbnail_data(data, self.thumb)
response = HttpResponse(mimetype=content_type)
response.write(data)
return response
示例6: get
def get(self, request, *args, **kwargs):
data, content_type = self.multimedia.get_display_file()
if self.thumb:
data = CommCareImage.get_thumbnail_data(data, self.thumb)
response = HttpResponse(data, content_type=content_type)
response['Content-Disposition'] = 'filename="download{}"'.format(self.multimedia.get_file_extension())
return response
示例7: match_zipped
def match_zipped(self, zip, replace_existing_media=True, **kwargs):
unknown_files = []
matched_audio = []
matched_images = []
errors = []
try:
for index, path in enumerate(zip.namelist()):
path = path.strip()
filename = path.lower()
basename = os.path.basename(path.lower())
is_image = False
if not basename:
continue
if self.match_filename:
filename = basename
media = None
form_path = None
data = None
if filename in self.images:
form_path = self.image_paths[self.images.index(filename)]
data = zip.read(path)
media = CommCareImage.get_by_data(data)
is_image = True
elif filename in self.audio:
form_path = self.audio_paths[self.audio.index(filename)]
data = zip.read(path)
media = CommCareAudio.get_by_data(data)
else:
unknown_files.append(path)
if media:
try:
media.attach_data(data,
upload_path=path,
username=self.username,
replace_attachment=replace_existing_media)
media.add_domain(self.domain, owner=True)
media.update_or_add_license(self.domain,
type=kwargs.get('license', ''),
author=kwargs.get('author', ''),
attribution_notes=kwargs.get('attribution_notes', ''))
self.app.create_mapping(media, form_path)
match_map = HQMediaMapItem.format_match_map(form_path, media.doc_type, media._id, path)
if is_image:
matched_images.append(match_map)
else:
matched_audio.append(match_map)
except Exception as e:
errors.append("%s (%s)" % (e, filename))
zip.close()
except Exception as e:
logging.error(e)
errors.append(e.message)
return matched_images, matched_audio, unknown_files, errors
示例8: test_override_logo
def test_override_logo(self):
image_data = _get_image_data()
image = CommCareImage.get_by_data(image_data)
image.attach_data(image_data, original_filename='logo.png')
image.add_domain(self.linked_app.domain)
image.save()
self.addCleanup(image.delete)
image_path = "jr://file/commcare/logo/data/hq_logo_android_home.png"
logo_refs = {
"hq_logo_android_home": {
"humanized_content_length": "45.4 KB",
"icon_class": "fa fa-picture-o",
"image_size": "448 X 332 Pixels",
"m_id": image._id,
"media_type": "Image",
"path": "jr://file/commcare/logo/data/hq_logo_android_home.png",
"uid": "3b79a76a067baf6a23a0b6978b2fb352",
"updated": False,
"url": "/hq/multimedia/file/CommCareImage/e3c45dd61c5593fdc5d985f0b99f6199/"
},
}
self.linked_app.master = self.plain_master_app.get_id
copy = self.plain_master_app.make_build()
copy.save()
self.addCleanup(copy.delete)
self.plain_master_app.save() # increment version number
copy1 = self.plain_master_app.make_build()
copy1.is_released = True
copy1.save()
self.addCleanup(copy1.delete)
self.linked_app.version = 1
self.linked_app.linked_app_logo_refs = logo_refs
self.linked_app.create_mapping(image, image_path, save=False)
self.linked_app.save()
self.assertEqual(self.linked_app.logo_refs, {})
update_linked_app(self.linked_app, 'test_override_logos')
# fetch after update to get the new version
self.linked_app = LinkedApplication.get(self.linked_app._id)
self.assertEqual(self.plain_master_app.logo_refs, {})
self.assertEqual(self.linked_app.linked_app_logo_refs, logo_refs)
self.assertEqual(self.linked_app.logo_refs, logo_refs)
# cleanup the linked app logo properties
self.linked_app.linked_app_logo_refs = {}
self.linked_app.save()
示例9: save
def save(self, domain, app, username, cache_handler=None):
orig_images, orig_audio, _ = utils.get_multimedia_filenames(app)
form_images = [i.replace(utils.MULTIMEDIA_PREFIX, '').lower().strip() for i in orig_images]
form_audio = [a.replace(utils.MULTIMEDIA_PREFIX, '').lower().strip() for a in orig_audio]
if self.cleaned_data["repopulate_multimedia_map"]:
app.multimedia_map = {}
app.save()
replace_attachment = self.cleaned_data["replace_existing_media"]
zip = self.cleaned_data["zip_file"]
num_files = len(zip.namelist())
if cache_handler:
cache_handler.sync()
cache_handler.data["processed_length"] = num_files
cache_handler.save()
unknown_files = []
for index, path in enumerate(zip.namelist()):
path = path.strip()
path_lower = path.lower()
if path_lower.endswith("/") or path_lower.endswith("\\") or \
path_lower.endswith(".ds_store"):
continue
media = None
form_path = None
data = None
if path_lower in form_images:
form_path = orig_images[form_images.index(path_lower)]
data = zip.read(path)
media = CommCareImage.get_by_data(data)
elif path_lower in form_audio:
form_path = orig_audio[form_audio.index(path_lower)]
data = zip.read(path)
media = CommCareAudio.get_by_data(data)
else:
unknown_files.append(path)
if media:
media.attach_data(data,
upload_path=path,
username=username,
replace_attachment=replace_attachment)
media.add_domain(domain, owner=True)
app.create_mapping(media, form_path)
if cache_handler:
cache_handler.sync()
cache_handler.data["processed"] = index+1
cache_handler.save()
zip.close()
return {"successful": unknown_files}
示例10: search_for_media
def search_for_media(request, domain, app_id):
media_type = request.GET['t']
if media_type == 'Image':
files = CommCareImage.search(request.GET['q'])
elif media_type == 'Audio':
files = CommCareAudio.search(request.GET['q'])
else:
raise Http404()
return HttpResponse(json.dumps([
{'url': i.url(),
'licenses': [license.display_name for license in i.licenses],
'tags': [tag for tags in i.tags.values() for tag in tags],
'm_id': i._id} for i in files]))
示例11: get
def get(self, request, *args, **kwargs):
obj = CachedObject(str(self.doc_id) + ':' + self.kwargs.get('media_type'))
if not obj.is_cached():
data, content_type = self.multimedia.get_display_file()
if self.thumb:
data = CommCareImage.get_thumbnail_data(data, self.thumb)
buffer = StringIO(data)
metadata = {'content_type': content_type}
obj.cache_put(buffer, metadata, timeout=0)
else:
metadata, buffer = obj.get()
data = buffer.getvalue()
content_type = metadata['content_type']
return HttpResponse(data, mimetype=content_type)
示例12: match_file
def match_file(self, uploaded_file, replace_existing_media=True, **kwargs):
errors = []
try:
if self.specific_params and self.specific_params['media_type'][0].startswith('CommCare'):
media_class = getattr(sys.modules[__name__], self.specific_params['media_type'][0])
form_path = self.specific_params['path'][0]
replace_existing_media = self.specific_params['replace_attachment'][0]
filename = uploaded_file.name
data = uploaded_file.file.read()
media = media_class.get_by_data(data)
else:
filename = uploaded_file.name
if filename in self.images:
form_path = self.image_paths[self.images.index(filename)]
data = uploaded_file.file.read()
media = CommCareImage.get_by_data(data)
elif filename in self.audio:
form_path = self.audio_paths[self.audio.index(filename)]
data = uploaded_file.file.read()
media = CommCareAudio.get_by_data(data)
else:
uploaded_file.close()
return False, {}, errors
if media:
media.attach_data(data,
original_filename=filename,
username=self.username,
replace_attachment=replace_existing_media)
media.add_domain(self.domain, owner=True, **kwargs)
media.update_or_add_license(self.domain,
type=kwargs.get('license', ''),
author=kwargs.get('author', ''),
attribution_notes=kwargs.get('attribution_notes', ''))
self.app.create_mapping(media, form_path)
return True, HQMediaMapItem.format_match_map(form_path, media.doc_type, media._id, filename), errors
except Exception as e:
logging.error(e)
errors.append(e.message)
return False, {}, errors
示例13: search_for_media
def search_for_media(request, domain, app_id):
media_type = request.GET["t"]
if media_type == "Image":
files = CommCareImage.search(request.GET["q"])
elif media_type == "Audio":
files = CommCareAudio.search(request.GET["q"])
else:
raise Http404()
return HttpResponse(
json.dumps(
[
{
"url": i.url(),
"licenses": [license.display_name for license in i.licenses],
"tags": [tag for tags in i.tags.values() for tag in tags],
"m_id": i._id,
}
for i in files
]
)
)
示例14: setUpClass
def setUpClass(cls):
super(TestRemoteLinkedApps, cls).setUpClass()
image_data = _get_image_data()
cls.image = CommCareImage.get_by_data(image_data)
cls.image.attach_data(image_data, original_filename='logo.png')
cls.image.add_domain(cls.plain_master_app.domain)