本文整理汇总了Python中couchexport.models.Format.from_format方法的典型用法代码示例。如果您正苦于以下问题:Python Format.from_format方法的具体用法?Python Format.from_format怎么用?Python Format.from_format使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类couchexport.models.Format
的用法示例。
在下文中一共展示了Format.from_format方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: location_export
# 需要导入模块: from couchexport.models import Format [as 别名]
# 或者: from couchexport.models.Format import from_format [as 别名]
def location_export(request, domain):
response = HttpResponse(mimetype=Format.from_format('xlsx').mimetype)
response['Content-Disposition'] = 'attachment; filename=locations.xlsx'
dump_locations(response, domain)
return response
示例2: dump_locations
# 需要导入模块: from couchexport.models import Format [as 别名]
# 或者: from couchexport.models.Format import from_format [as 别名]
def dump_locations(domain, download_id, include_consumption, headers_only, task=None):
exporter = LocationExporter(domain, include_consumption=include_consumption,
headers_only=headers_only, async_task=task)
fd, path = tempfile.mkstemp()
writer = Excel2007ExportWriter()
writer.open(header_table=exporter.get_headers(), file=path)
with writer:
exporter.write_data(writer)
with open(path, 'rb') as file_:
db = get_blob_db()
expiry_mins = 60
db.put(
file_,
domain=domain,
parent_id=domain,
type_code=CODES.tempfile,
key=download_id,
timeout=expiry_mins,
)
file_format = Format.from_format(Excel2007ExportWriter.format)
expose_blob_download(
download_id,
expiry=expiry_mins * 60,
mimetype=file_format.mimetype,
content_disposition=safe_filename_header('{}_locations'.format(domain), file_format.extension),
download_id=download_id,
)
示例3: _render_report_configs
# 需要导入模块: from couchexport.models import Format [as 别名]
# 或者: from couchexport.models.Format import from_format [as 别名]
def _render_report_configs(request, configs, domain, owner_id, couch_user, email, notes=None, attach_excel=False):
from dimagi.utils.web import get_url_base
report_outputs = []
excel_attachments = []
format = Format.from_format(request.GET.get('format') or Format.XLS_2007)
for config in configs:
content, excel_file = config.get_report_content(attach_excel=attach_excel)
if excel_file:
excel_attachments.append({
'title': config.full_name + "." + format.extension,
'file_obj': excel_file,
'mimetype': format.mimetype
})
report_outputs.append({
'title': config.full_name,
'url': config.url,
'content': content
})
date_range = config.get_date_range()
return render(request, "reports/report_email.html", {
"reports": report_outputs,
"domain": domain,
"couch_user": owner_id,
"DNS_name": get_url_base(),
"owner_name": couch_user.full_name or couch_user.get_email(),
"email": email,
"notes": notes or getattr(config, "description", ""),
"startdate": date_range["startdate"] if date_range else "",
"enddate": date_range["enddate"] if date_range else "",
}), excel_attachments
示例4: export_async
# 需要导入模块: from couchexport.models import Format [as 别名]
# 或者: from couchexport.models.Format import from_format [as 别名]
def export_async(download_id, export_tag, format=None, filename=None,
previous_export_id=None, filter=None,
expiry=10*60*60):
if not filename:
filename = export_tag
(tmp, checkpoint) = get_export_files(export_tag, format, previous_export_id, filter)
if checkpoint:
temp_id = uuid.uuid4().hex
fd, path = tempfile.mkstemp()
with os.fdopen(fd, 'wb') as file:
file.write(tmp.getvalue())
# make file globally read/writeable in case celery runs as root
os.chmod(path, stat.S_IRUSR | stat.S_IWUSR | stat.S_IRGRP | \
stat.S_IWGRP | stat.S_IROTH | stat.S_IWOTH)
format = Format.from_format(format)
try:
filename = unidecode(filename)
except Exception:
pass
cache.set(download_id, FileDownload(path, mimetype=format.mimetype,
content_disposition='attachment; filename=%s.%s' % \
(filename, format.extension),
extras={'X-CommCareHQ-Export-Token': checkpoint.get_id}),
expiry)
else:
temp_id = uuid.uuid4().hex
cache.set(temp_id, "Sorry, there wasn't any data.", expiry)
cache.set(download_id, CachedDownload(temp_id,content_disposition="",
mimetype="text/html"), expiry)
示例5: download_cases
# 需要导入模块: from couchexport.models import Format [as 别名]
# 或者: from couchexport.models.Format import from_format [as 别名]
def download_cases(request, domain):
include_closed = json.loads(request.GET.get('include_closed', 'false'))
format = Format.from_format(request.GET.get('format') or Format.XLS_2007)
view_name = 'hqcase/all_cases' if include_closed else 'hqcase/open_cases'
key = [domain, {}, {}]
cases = CommCareCase.view(view_name, startkey=key, endkey=key + [{}], reduce=False, include_docs=True)
# group, users = util.get_group_params(domain, **json_request(request.GET))
group = request.GET.get('group', None)
user_filter, _ = FilterUsersField.get_user_filter(request)
# todo deal with cached user dict here
users = get_all_users_by_domain(domain, group=group, user_filter=user_filter)
groups = Group.get_case_sharing_groups(domain)
# if not group:
# users.extend(CommCareUser.by_domain(domain, is_active=False))
workbook = WorkBook()
export_cases_and_referrals(cases, workbook, users=users, groups=groups)
export_users(users, workbook)
response = HttpResponse(workbook.format(format.slug))
response['Content-Type'] = "%s" % format.mimetype
response['Content-Disposition'] = "attachment; filename={domain}_data.{ext}".format(domain=domain, ext=format.extension)
return response
示例6: cache_file_to_be_served
# 需要导入模块: from couchexport.models import Format [as 别名]
# 或者: from couchexport.models.Format import from_format [as 别名]
def cache_file_to_be_served(tmp, checkpoint, download_id, format=None, filename=None, expiry=10*60*60):
"""
tmp can be either either a path to a tempfile or a StringIO
(the APIs for tempfiles vs StringIO are unfortunately... not similar)
"""
if checkpoint:
format = Format.from_format(format)
try:
filename = unidecode(filename)
except Exception:
pass
escaped_filename = escape_quotes('%s.%s' % (filename, format.extension))
payload = tmp.payload
expose_cached_download(payload, expiry, ".{}".format(format.extension),
mimetype=format.mimetype,
content_disposition='attachment; filename="%s"' % escaped_filename,
extras={'X-CommCareHQ-Export-Token': checkpoint.get_id},
download_id=download_id)
tmp.delete()
else:
# this just gives you a link saying there wasn't anything there
expose_cached_download("Sorry, there wasn't any data.", expiry, None,
content_disposition="",
mimetype="text/html",
download_id=download_id).save(expiry)
示例7: download_products
# 需要导入模块: from couchexport.models import Format [as 别名]
# 或者: from couchexport.models.Format import from_format [as 别名]
def download_products(request, domain):
def _get_products(domain):
for p_doc in iter_docs(Product.get_db(), Product.ids_by_domain(domain)):
# filter out archived products from export
if not ('is_archived' in p_doc and p_doc['is_archived']):
yield Product.wrap(p_doc)
def _build_row(keys, product):
row = []
for key in keys:
row.append(product.get(key, '') or '')
return row
file = StringIO()
writer = Excel2007ExportWriter()
product_keys = [
'id',
'name',
'unit',
'product_id',
'description',
'category',
'program_id',
'cost',
]
data_keys = set()
products = []
for product in _get_products(domain):
product_dict = product.to_dict()
custom_properties = product.custom_property_dict()
data_keys.update(custom_properties.keys())
product_dict.update(custom_properties)
products.append(product_dict)
keys = product_keys + list(data_keys)
writer.open(
header_table=[
('products', [keys])
],
file=file,
)
for product in products:
writer.write([('products', [_build_row(keys, product)])])
writer.close()
response = HttpResponse(mimetype=Format.from_format('xlsx').mimetype)
response['Content-Disposition'] = 'attachment; filename="products.xlsx"'
response.write(file.getvalue())
return response
示例8: location_export
# 需要导入模块: from couchexport.models import Format [as 别名]
# 或者: from couchexport.models.Format import from_format [as 别名]
def location_export(request, domain):
if not LocationType.objects.filter(domain=domain).exists():
messages.error(request, _("You need to define location types before "
"you can do a bulk import or export."))
return HttpResponseRedirect(reverse(LocationsListView.urlname, args=[domain]))
include_consumption = request.GET.get('include_consumption') == 'true'
response = HttpResponse(content_type=Format.from_format('xlsx').mimetype)
response['Content-Disposition'] = 'attachment; filename="locations.xlsx"'
dump_locations(response, domain, include_consumption)
return response
示例9: filename
# 需要导入模块: from couchexport.models import Format [as 别名]
# 或者: from couchexport.models.Format import from_format [as 别名]
def filename(self):
file_ext = Format.from_format(self.format).extension
filename = "%s.%s" % (self.export_id, file_ext)
try:
app = Application.get(self.export_id)
if app:
filename = "%s-%s.%s" %(app.name, app.get_id, file_ext)
except Exception:
pass
return filename
示例10: formdefs
# 需要导入模块: from couchexport.models import Format [as 别名]
# 或者: from couchexport.models.Format import from_format [as 别名]
def formdefs(request, domain, app_id):
# TODO: Looks like this function is never used
langs = [json.loads(request.GET.get('lang', '"en"'))]
format = request.GET.get('format', 'json')
app = get_app(domain, app_id)
def get_questions(form):
xform = XForm(form.source)
prefix = '/%s/' % xform.data_node.tag_name
def remove_prefix(string):
if string.startswith(prefix):
return string[len(prefix):]
else:
raise Exception()
def transform_question(q):
return {
'id': remove_prefix(q['value']),
'type': q['tag'],
'text': q['label'] if q['tag'] != 'hidden' else ''
}
return [transform_question(q) for q in xform.get_questions(langs)]
formdefs = [{
'name': "%s, %s" % (
f['form'].get_module().name['en'],
f['form'].name['en']
) if f['type'] == 'module_form' else 'User Registration',
'columns': ['id', 'type', 'text'],
'rows': get_questions(f['form'])
} for f in app.get_forms(bare=False)]
if format == 'xlsx':
f = StringIO()
writer = Excel2007ExportWriter()
writer.open([(sheet['name'], [FormattedRow(sheet['columns'])]) for sheet in formdefs], f)
writer.write([(
sheet['name'],
[
FormattedRow([
cell for (_, cell) in
sorted(row.items(), key=lambda item: sheet['columns'].index(item[0]))
])
for row in sheet['rows']
]
) for sheet in formdefs])
writer.close()
response = HttpResponse(f.getvalue(), content_type=Format.from_format('xlsx').mimetype)
set_file_download(response, 'formdefs.xlsx')
return response
else:
return json_response(formdefs)
示例11: download_daily_saved_export
# 需要导入模块: from couchexport.models import Format [as 别名]
# 或者: from couchexport.models.Format import from_format [as 别名]
def download_daily_saved_export(req, domain, export_instance_id):
with CriticalSection(['export-last-accessed-{}'.format(export_instance_id)]):
try:
export_instance = get_properly_wrapped_export_instance(export_instance_id)
except ResourceNotFound:
raise Http404(_("Export not found"))
assert domain == export_instance.domain
if export_instance.export_format == "html":
if not domain_has_privilege(domain, EXCEL_DASHBOARD):
raise Http404
elif export_instance.is_daily_saved_export:
if not domain_has_privilege(domain, DAILY_SAVED_EXPORT):
raise Http404
if not export_instance.filters.is_location_safe_for_user(req):
return location_restricted_response(req)
if not can_download_daily_saved_export(export_instance, domain, req.couch_user):
raise Http404
if export_instance.export_format == "html":
message = "Download Excel Dashboard"
else:
message = "Download Saved Export"
track_workflow(req.couch_user.username, message, properties={
'domain': domain,
'is_dimagi': req.couch_user.is_dimagi
})
if should_update_export(export_instance.last_accessed):
try:
rebuild_saved_export(export_instance_id, manual=False)
except Exception:
notify_exception(
req,
'Failed to rebuild export during download',
{
'export_instance_id': export_instance_id,
'domain': domain,
},
)
export_instance.last_accessed = datetime.utcnow()
export_instance.save()
payload = export_instance.get_payload(stream=True)
format = Format.from_format(export_instance.export_format)
return get_download_response(payload, export_instance.file_size, format, export_instance.filename, req)
示例12: populate_export_download_task
# 需要导入模块: from couchexport.models import Format [as 别名]
# 或者: from couchexport.models.Format import from_format [as 别名]
def populate_export_download_task(export_instances, filters, download_id, filename=None, expiry=10 * 60 * 60):
export_file = get_export_file(export_instances, filters)
file_format = Format.from_format(export_file.format)
filename = filename or export_instances[0].name
escaped_filename = escape_quotes('%s.%s' % (filename, file_format.extension))
payload = export_file.file.payload
expose_cached_download(
payload,
expiry,
".{}".format(file_format.extension),
mimetype=file_format.mimetype,
content_disposition='attachment; filename="%s"' % escaped_filename,
download_id=download_id,
)
export_file.file.delete()
示例13: expose_download
# 需要导入模块: from couchexport.models import Format [as 别名]
# 或者: from couchexport.models.Format import from_format [as 别名]
def expose_download(use_transfer, file_path, filename, download_id, file_type):
common_kwargs = dict(
mimetype=Format.from_format(file_type).mimetype,
content_disposition='attachment; filename="{fname}"'.format(fname=filename),
download_id=download_id, expiry=(1 * 60 * 60),
)
if use_transfer:
expose_file_download(
file_path,
use_transfer=use_transfer,
**common_kwargs
)
else:
expose_cached_download(
FileWrapper(open(file_path, 'rb')),
file_extension=file_type,
**common_kwargs
)
示例14: expose_zipped_blob_download
# 需要导入模块: from couchexport.models import Format [as 别名]
# 或者: from couchexport.models.Format import from_format [as 别名]
def expose_zipped_blob_download(data_path, filename, format, domain):
"""Expose zipped file content as a blob download
:param data_path: Path to data file. Will be deleted.
:param filename: File name.
:param format: `couchexport.models.Format` constant.
:param domain: Domain name.
:returns: A link to download the file.
"""
try:
_, zip_temp_path = tempfile.mkstemp(".zip")
with ZipFile(zip_temp_path, 'w') as zip_file_:
zip_file_.write(data_path, filename)
finally:
os.remove(data_path)
try:
expiry_mins = 60 * 24
file_format = Format.from_format(format)
file_name_header = safe_filename_header(filename, file_format.extension)
ref = expose_blob_download(
filename,
expiry=expiry_mins * 60,
mimetype=file_format.mimetype,
content_disposition=file_name_header
)
with open(zip_temp_path, 'rb') as file_:
get_blob_db().put(
file_,
domain=domain,
parent_id=domain,
type_code=CODES.tempfile,
key=ref.download_id,
timeout=expiry_mins
)
finally:
os.remove(zip_temp_path)
return "%s%s?%s" % (
get_url_base(),
reverse('retrieve_download', kwargs={'download_id': ref.download_id}),
"get_file" # download immediately rather than rendering page
)
示例15: download_commcare_users
# 需要导入模块: from couchexport.models import Format [as 别名]
# 或者: from couchexport.models.Format import from_format [as 别名]
def download_commcare_users(request, domain):
response = HttpResponse(mimetype=Format.from_format("xlsx").mimetype)
response["Content-Disposition"] = 'attachment; filename="%s_users.xlsx"' % domain
try:
dump_users_and_groups(response, domain)
except GroupNameError as e:
group_urls = [reverse("group_members", args=[domain, group.get_id]) for group in e.blank_groups]
def make_link(url, i):
return format_html('<a href="{}" target="_blank">{}</a>', url, _("Blank Group %s") % i)
group_links = [make_link(url, i + 1) for i, url in enumerate(group_urls)]
msg = format_html(
_("The following groups have no name. " "Please name them before continuing: {}"),
mark_safe(", ".join(group_links)),
)
messages.error(request, msg, extra_tags="html")
return HttpResponseRedirect(reverse("upload_commcare_users", args=[domain]))
return response