本文整理汇总了Python中wirecloud.commons.utils.wgt.WgtFile.read方法的典型用法代码示例。如果您正苦于以下问题:Python WgtFile.read方法的具体用法?Python WgtFile.read怎么用?Python WgtFile.read使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类wirecloud.commons.utils.wgt.WgtFile
的用法示例。
在下文中一共展示了WgtFile.read方法的7个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: wrapper
# 需要导入模块: from wirecloud.commons.utils.wgt import WgtFile [as 别名]
# 或者: from wirecloud.commons.utils.wgt.WgtFile import read [as 别名]
def wrapper(self, *args, **kwargs):
owner_user = User.objects.get(username=owner)
if shared:
base = self.shared_test_data_dir
else:
base = self.test_data_dir
with open(os.path.join(base, file_name), 'rb') as f:
wgt = WgtFile(f)
template = TemplateParser(wgt.get_template())
resource_info = template.get_resource_processed_info(process_urls=False)
if resource_info["type"] != 'mashup':
raise Exception
for embedded_resource in resource_info['embedded']:
if embedded_resource['src'].startswith('https://'):
resource_file = download_http_content(embedded_resource['src'])
else:
resource_file = BytesIO(wgt.read(embedded_resource['src']))
extra_resource_contents = WgtFile(resource_file)
install_resource_to_user(owner_user, file_contents=extra_resource_contents)
buildWorkspaceFromTemplate(template, owner_user)
return test_func(self, *args, **kwargs)
示例2: add_widget_from_wgt
# 需要导入模块: from wirecloud.commons.utils.wgt import WgtFile [as 别名]
# 或者: from wirecloud.commons.utils.wgt.WgtFile import read [as 别名]
def add_widget_from_wgt(file, user, wgt_file=None, template=None, deploy_only=False):
close_wgt = False
if wgt_file is None:
wgt_file = WgtFile(file)
close_wgt = True
if template is None:
template_contents = wgt_file.get_template()
template = TemplateParser(template_contents)
if template.get_resource_type() == 'widget':
resource_info = template.get_resource_info()
code_url = resource_info['code_url']
if not code_url.startswith(('http://', 'https://')):
code = wgt_file.read(code_url)
try:
unicode(code, resource_info['code_charset'])
except UnicodeDecodeError:
msg = _('%(file_name)s was not encoded using the specified charset (%(charset)s according to the widget descriptor file).')
raise InvalidContents(msg % {'file_name': code_url, 'charset': resource_info['code_charset']})
resource_id = (
template.get_resource_vendor(),
template.get_resource_name(),
template.get_resource_version(),
)
file_name = '_'.join(resource_id) + '.wgt'
local_dir = wgt_deployer.get_base_dir(*resource_id)
local_wgt = os.path.join(local_dir, file_name)
if not os.path.exists(local_dir):
os.makedirs(local_dir)
overrides = extract_resource_media_from_package(template, wgt_file, local_dir)
if close_wgt:
wgt_file.close()
f = open(local_wgt, "wb")
file.seek(0)
f.write(file.read())
f.close()
if not deploy_only:
return add_resource_from_template(file_name, template, user, fromWGT=True, overrides=overrides)
示例3: create
# 需要导入模块: from wirecloud.commons.utils.wgt import WgtFile [as 别名]
# 或者: from wirecloud.commons.utils.wgt.WgtFile import read [as 别名]
#.........这里部分代码省略.........
"install_embedded_resources", data.get("install_embedded_resources", False)
)
force_create = data.get("force_create", False)
templateURL = data.get("template_uri")
market_endpoint = data.get("market_endpoint", None)
else:
force_create = request.POST.get("force_create", False) == "true"
if "url" in request.POST:
templateURL = request.POST["url"]
if market_endpoint is not None:
if "name" not in market_endpoint:
msg = _("Missing market name")
return build_error_response(request, 400, msg)
market_id = market_endpoint["name"]
market_managers = get_market_managers(request.user)
if market_id not in market_managers:
return build_error_response(request, 409, _("Unknown market: %s") % market_id)
market_manager = market_managers[market_id]
downloaded_file = market_manager.download_resource(request.user, templateURL, market_endpoint)
else:
try:
downloaded_file = download_http_content(templateURL)
except:
return build_error_response(request, 409, _("Content cannot be downloaded from the marketplace"))
try:
downloaded_file = BytesIO(downloaded_file)
file_contents = WgtFile(downloaded_file)
except zipfile.BadZipfile:
return build_error_response(
request, 400, _("The file downloaded from the marketplace is not a zip file")
)
try:
resource = install_resource_to_user(
request.user, file_contents=file_contents, templateURL=templateURL, raise_conflicts=force_create
)
except OSError as e:
if e.errno == errno.EACCES:
return build_error_response(
request,
500,
_("Error writing the resource into the filesystem. Please, contact the server administrator."),
)
else:
raise
except TemplateParseException as e:
msg = "Error parsing config.xml descriptor file: %s" % e
details = "%s" % e
return build_error_response(request, 400, msg, details=details)
except (InvalidContents, UnsupportedFeature) as e:
return build_error_response(request, 400, unicode(e))
except IntegrityError:
return build_error_response(request, 409, _("Resource already exists"))
if install_embedded_resources:
info = {"resource_details": resource.get_processed_info(request), "extra_resources": []}
if resource.resource_type() == "mashup":
resource_info = resource.get_processed_info(process_urls=False)
for embedded_resource in resource_info["embedded"]:
if embedded_resource["src"].startswith("https://"):
resource_file = download_http_content(embedded_resource["src"])
else:
resource_file = BytesIO(file_contents.read(embedded_resource["src"]))
extra_resource_contents = WgtFile(resource_file)
extra_resource = install_resource_to_user(
request.user, file_contents=extra_resource_contents, raise_conflicts=False
)
info["extra_resources"].append(extra_resource.get_processed_info(request))
return HttpResponse(json.dumps(info), status=201, content_type="application/json; charset=UTF-8")
else:
return HttpResponse(
json.dumps(resource.get_processed_info(request)),
status=201,
content_type="application/json; charset=UTF-8",
)
示例4: add_packaged_resource
# 需要导入模块: from wirecloud.commons.utils.wgt import WgtFile [as 别名]
# 或者: from wirecloud.commons.utils.wgt.WgtFile import read [as 别名]
def add_packaged_resource(file, user, wgt_file=None, template=None, deploy_only=False):
close_wgt = False
if wgt_file is None:
wgt_file = WgtFile(file)
close_wgt = True
if template is None:
template_contents = wgt_file.get_template()
template = TemplateParser(template_contents)
resource_info = template.get_resource_info()
if resource_info['type'] == 'widget':
code_url = resource_info['contents']['src']
if not code_url.startswith(('http://', 'https://')):
try:
code = wgt_file.read(code_url)
except KeyError:
msg = _('Missing contents file: %(file_name)s.')
raise InvalidContents(msg % {'file_name': code_url})
try:
unicode(code, resource_info['contents']['charset'])
except UnicodeDecodeError:
msg = _('%(file_name)s was not encoded using the specified charset (%(charset)s according to the widget descriptor file).')
raise InvalidContents(msg % {'file_name': code_url, 'charset': resource_info['contents']['charset']})
resource_id = (
template.get_resource_vendor(),
template.get_resource_name(),
template.get_resource_version(),
)
file_name = '_'.join(resource_id) + '.wgt'
local_dir = wgt_deployer.get_base_dir(*resource_id)
local_wgt = os.path.join(local_dir, file_name)
if not os.path.exists(local_dir):
os.makedirs(local_dir)
overrides = extract_resource_media_from_package(template, wgt_file, local_dir)
if close_wgt:
wgt_file.close()
f = open(local_wgt, "wb")
file.seek(0)
f.write(file.read())
f.close()
if not deploy_only:
resource_info.update(overrides)
resource = CatalogueResource.objects.create(
short_name=resource_info['name'],
vendor=resource_info['vendor'],
version=resource_info['version'],
type=CatalogueResource.RESOURCE_TYPES.index(resource_info['type']),
creator=user,
template_uri=file_name,
creation_date=now(),
popularity='0.0',
json_description=json.dumps(resource_info)
)
return resource
示例5: create
# 需要导入模块: from wirecloud.commons.utils.wgt import WgtFile [as 别名]
# 或者: from wirecloud.commons.utils.wgt.WgtFile import read [as 别名]
def create(self, request):
status_code = 201
force_create = False
install_embedded_resources = False
templateURL = None
file_contents = None
content_type = get_content_type(request)[0]
if content_type == 'multipart/form-data':
force_create = request.POST.get('force_create', 'false').strip().lower() == 'true'
public = request.POST.get('public', 'false').strip().lower() == 'true'
install_embedded_resources = request.POST.get('install_embedded_resources', 'false').strip().lower() == 'true'
if 'file' not in request.FILES:
return build_error_response(request, 400, _('Missing component file in the request'))
downloaded_file = request.FILES['file']
try:
file_contents = WgtFile(downloaded_file)
except zipfile.BadZipfile:
return build_error_response(request, 400, _('The uploaded file is not a zip file'))
elif content_type == 'application/octet-stream':
downloaded_file = BytesIO(request.body)
try:
file_contents = WgtFile(downloaded_file)
except zipfile.BadZipfile:
return build_error_response(request, 400, _('The uploaded file is not a zip file'))
force_create = request.GET.get('force_create', 'false').strip().lower() == 'true'
public = request.GET.get('public', 'false').strip().lower() == 'true'
install_embedded_resources = request.GET.get('install_embedded_resources', 'false').strip().lower() == 'true'
else: # if content_type == 'application/json'
market_endpoint = None
data = parse_json_request(request)
install_embedded_resources = normalize_boolean_param(request, 'install_embedded_resources', data.get('install_embedded_resources', False))
force_create = data.get('force_create', False)
public = request.GET.get('public', 'false').strip().lower() == 'true'
templateURL = data.get('url')
market_endpoint = data.get('market_endpoint', None)
headers = data.get('headers', {})
if market_endpoint is not None:
if 'name' not in market_endpoint:
msg = _('Missing market name')
return build_error_response(request, 400, msg)
market_id = market_endpoint['name']
market_managers = get_market_managers(request.user)
if market_id not in market_managers:
return build_error_response(request, 409, _('Unknown market: %s') % market_id)
market_manager = market_managers[market_id]
downloaded_file = market_manager.download_resource(request.user, templateURL, market_endpoint)
else:
try:
context = parse_context_from_referer(request)
except:
context = {}
try:
context["headers"] = CaseInsensitiveDict(headers)
response = WIRECLOUD_PROXY.do_request(request, templateURL, "GET", context)
if response.status_code >= 300 or response.status_code < 200:
raise Exception()
downloaded_file = b''.join(response)
except:
return build_error_response(request, 409, _('Content cannot be downloaded from the specified url'))
try:
downloaded_file = BytesIO(downloaded_file)
file_contents = WgtFile(downloaded_file)
except zipfile.BadZipfile:
return build_error_response(request, 400, _('The file downloaded from the marketplace is not a zip file'))
if public and not request.user.is_superuser:
return build_error_response(request, 403, _('You are not allowed to make resources publicly available to all users'))
try:
fix_dev_version(file_contents, request.user)
added, resource = install_resource_to_user(request.user, file_contents=file_contents, templateURL=templateURL)
if not added and force_create:
return build_error_response(request, 409, _('Resource already exists'))
elif not added:
status_code = 200
if public:
install_resource_to_all_users(executor_user=request.user, file_contents=file_contents)
except zipfile.BadZipfile as e:
#.........这里部分代码省略.........
示例6: create
# 需要导入模块: from wirecloud.commons.utils.wgt import WgtFile [as 别名]
# 或者: from wirecloud.commons.utils.wgt.WgtFile import read [as 别名]
def create(self, request):
status_code = 201
force_create = False
install_embedded_resources = False
templateURL = None
file_contents = None
content_type = get_content_type(request)[0]
if content_type == 'multipart/form-data':
force_create = request.POST.get('force_create', 'false').strip().lower() == 'true'
install_embedded_resources = request.POST.get('install_embedded_resources', 'false').strip().lower() == 'true'
if not 'file' in request.FILES:
return build_error_response(request, 400, _('Missing component file in the request'))
downloaded_file = request.FILES['file']
try:
file_contents = WgtFile(downloaded_file)
except zipfile.BadZipfile:
return build_error_response(request, 400, _('The uploaded file is not a zip file'))
elif content_type == 'application/octet-stream':
downloaded_file = BytesIO(request.body)
try:
file_contents = WgtFile(downloaded_file)
except zipfile.BadZipfile:
return build_error_response(request, 400, _('The uploaded file is not a zip file'))
force_create = request.GET.get('force_create', 'false').strip().lower() == 'true'
install_embedded_resources = request.GET.get('install_embedded_resources', 'false').strip().lower() == 'true'
else: # if content_type == 'application/json'
market_endpoint = None
data = parse_json_request(request)
install_embedded_resources = normalize_boolean_param(request, 'install_embedded_resources', data.get('install_embedded_resources', False))
force_create = data.get('force_create', False)
templateURL = data.get('url')
market_endpoint = data.get('market_endpoint', None)
if market_endpoint is not None:
if 'name' not in market_endpoint:
msg = _('Missing market name')
return build_error_response(request, 400, msg)
market_id = market_endpoint['name']
market_managers = get_market_managers(request.user)
if market_id not in market_managers:
return build_error_response(request, 409, _('Unknown market: %s') % market_id)
market_manager = market_managers[market_id]
downloaded_file = market_manager.download_resource(request.user, templateURL, market_endpoint)
else:
try:
downloaded_file = download_http_content(templateURL)
except:
return build_error_response(request, 409, _('Content cannot be downloaded from the specified url'))
try:
downloaded_file = BytesIO(downloaded_file)
file_contents = WgtFile(downloaded_file)
except zipfile.BadZipfile:
return build_error_response(request, 400, _('The file downloaded from the marketplace is not a zip file'))
try:
added, resource = install_resource_to_user(request.user, file_contents=file_contents, templateURL=templateURL)
if not added and force_create:
return build_error_response(request, 409, _('Resource already exists'))
elif not added:
status_code = 200
except zipfile.BadZipfile as e:
return build_error_response(request, 400, _('The uploaded file is not a valid zip file'), details="{}".format(e))
except OSError as e:
if e.errno == errno.EACCES:
return build_error_response(request, 500, _('Error writing the resource into the filesystem. Please, contact the server administrator.'))
else:
raise
except TemplateParseException as e:
msg = "Error parsing config.xml descriptor file: %s" % e
details = "%s" % e
return build_error_response(request, 400, msg, details=details)
except (InvalidContents, UnsupportedFeature) as e:
details = e.details if hasattr(e, 'details') else None
#.........这里部分代码省略.........
示例7: add_packaged_resource
# 需要导入模块: from wirecloud.commons.utils.wgt import WgtFile [as 别名]
# 或者: from wirecloud.commons.utils.wgt.WgtFile import read [as 别名]
def add_packaged_resource(file, user, wgt_file=None, template=None, deploy_only=False):
close_wgt = False
if wgt_file is None:
wgt_file = WgtFile(file)
close_wgt = True
if template is None:
template_contents = wgt_file.get_template()
template = TemplateParser(template_contents)
resource_info = template.get_resource_info()
if resource_info["type"] == "widget":
code_url = resource_info["contents"]["src"]
if not code_url.startswith(("http://", "https://")):
try:
code = wgt_file.read(code_url)
except KeyError:
msg = _("Missing contents file: %(file_name)s.")
raise InvalidContents(msg % {"file_name": code_url})
try:
code.decode(resource_info["contents"]["charset"])
except UnicodeDecodeError:
msg = _(
"%(file_name)s was not encoded using the specified charset (%(charset)s according to the widget descriptor file)."
)
raise InvalidContents(msg % {"file_name": code_url, "charset": resource_info["contents"]["charset"]})
check_invalid_doc_content(wgt_file, resource_info, "longdescription")
check_invalid_doc_content(wgt_file, resource_info, "doc")
check_invalid_doc_content(wgt_file, resource_info, "changelog")
resource_id = (template.get_resource_vendor(), template.get_resource_name(), template.get_resource_version())
file_name = "_".join(resource_id) + ".wgt"
local_dir = wgt_deployer.get_base_dir(*resource_id)
local_wgt = os.path.join(local_dir, file_name)
if not os.path.exists(local_dir):
os.makedirs(local_dir)
overrides = extract_resource_media_from_package(template, wgt_file, local_dir)
if close_wgt:
wgt_file.close()
f = open(local_wgt, "wb")
file.seek(0)
f.write(file.read())
f.close()
if not deploy_only:
resource_info.update(overrides)
resource = CatalogueResource.objects.create(
short_name=resource_info["name"],
vendor=resource_info["vendor"],
version=resource_info["version"],
type=CatalogueResource.RESOURCE_TYPES.index(resource_info["type"]),
creator=user,
template_uri=file_name,
creation_date=now(),
popularity="0.0",
json_description=json.dumps(resource_info),
)
return resource