本文整理汇总了Python中wirecloud.commons.utils.template.TemplateParser类的典型用法代码示例。如果您正苦于以下问题:Python TemplateParser类的具体用法?Python TemplateParser怎么用?Python TemplateParser使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了TemplateParser类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: check_packaged_resource
def check_packaged_resource(wgt_file, resource_info=None):
if resource_info 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')
check_invalid_embedded_resources(wgt_file, resource_info)
示例2: buildWorkspaceFromTemplate
def buildWorkspaceFromTemplate(template, user, allow_renaming=False, new_name=None, new_title=None, searchable=True, public=False):
if not isinstance(template, TemplateParser):
template = TemplateParser(template)
if template.get_resource_type() != 'mashup':
raise TypeError('Unsupported resource type: %s' % template.get_resource_type())
if (new_name is None or new_name.strip() == '') and (new_title is None or new_title.strip() == ''):
processed_info = template.get_resource_processed_info(process_urls=False)
new_name = processed_info['name']
new_title = processed_info['title']
elif new_title is None or new_title.strip() == '':
new_title = new_name
elif new_name is None or new_name.strip() == '':
new_name = URLify(new_title)
# Workspace creation
workspace = Workspace(title=new_title, name=new_name, creator=user, searchable=searchable, public=public)
if allow_renaming:
save_alternative(Workspace, 'name', workspace)
else:
workspace.save()
# Adding user reference to workspace in the many to many relationship
user_workspace = UserWorkspace(user=user, workspace=workspace)
user_workspace.save()
fillWorkspaceUsingTemplate(workspace, template)
return (workspace, user_workspace)
示例3: buildWorkspaceFromTemplate
def buildWorkspaceFromTemplate(template, user, allow_renaming=False, new_name=None):
if not isinstance(template, TemplateParser):
template = TemplateParser(template)
if template.get_resource_type() != 'mashup':
raise Exception()
if new_name is not None:
name = new_name
else:
name = template.get_resource_name()
# Workspace creation
workspace = Workspace(name=name, creator=user)
if allow_renaming:
save_alternative(Workspace, 'name', workspace)
else:
workspace.save()
# Adding user reference to workspace in the many to many relationship
user_workspace = UserWorkspace(user=user, workspace=workspace, active=False)
user_workspace.save()
fillWorkspaceUsingTemplate(workspace, template)
return (workspace, user_workspace)
示例4: add_widget_from_wgt
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)
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)
示例5: buildWorkspaceFromTemplate
def buildWorkspaceFromTemplate(template, user, allow_renaming=False, new_name=None):
if not isinstance(template, TemplateParser):
template = TemplateParser(template)
if template.get_resource_type() != 'mashup':
raise TypeError('Unsupported resource type: %s' % template.get_resource_type())
if new_name is not None:
name = new_name
else:
name = template.get_resource_processed_info(process_urls=False)['title']
# Workspace creation
workspace = Workspace(name=name, creator=user)
if allow_renaming:
save_alternative(Workspace, 'name', workspace)
else:
workspace.save()
# Adding user reference to workspace in the many to many relationship
user_workspace = UserWorkspace(user=user, workspace=workspace, active=False)
user_workspace.save()
fillWorkspaceUsingTemplate(workspace, template)
return (workspace, user_workspace)
示例6: test_basic_operator_creation_from_rdf
def test_basic_operator_creation_from_rdf(self):
template = self.read_template("operatorTemplate1.rdf")
parser = TemplateParser(template)
data = parser.get_resource_info()
self.assertEqual(data["vendor"], "Wirecloud")
self.assertEqual(data["name"], "test operator")
self.assertEqual(data["type"], "operator")
self.assertEqual(data["version"], "0.1")
self.assertEqual(data["email"], "[email protected]")
self.assertEqual(data["wiring"]["inputs"][0]["label"], "slot")
self.assertEqual(data["wiring"]["inputs"][0]["type"], "text")
self.assertEqual(data["wiring"]["inputs"][0]["friendcode"], "test_friend_code")
self.assertEqual(data["wiring"]["outputs"][0]["label"], "event")
self.assertEqual(data["wiring"]["outputs"][0]["type"], "text")
self.assertEqual(data["wiring"]["outputs"][0]["friendcode"], "test_friend_code")
self.assertEqual(data["preferences"][0]["label"], "Preference label")
self.assertEqual(data["preferences"][0]["description"], "Preference description")
self.assertEqual(data["preferences"][0]["default_value"], "value")
self.assertEqual(len(data["js_files"]), 5)
self.assertEqual(data["js_files"][0], "/examplecode1.js")
self.assertEqual(data["js_files"][1], "/examplecode2.js")
self.assertEqual(data["js_files"][2], "/examplecode3.js")
self.assertEqual(data["js_files"][3], "/examplecode4.js")
self.assertEqual(data["js_files"][4], "/examplecode5.js")
示例7: install_resource
def install_resource(file_contents, templateURL, executor_user, packaged):
if packaged:
if isinstance(file_contents, basestring):
file_contents = StringIO(file_contents)
wgt_file = WgtFile(file_contents)
elif isinstance(file_contents, WgtFile):
wgt_file = file_contents
file_contents = wgt_file.get_underlying_file()
else:
raise Exception
template_contents = wgt_file.get_template()
else:
template_contents = file_contents
template = TemplateParser(template_contents)
resources = CatalogueResource.objects.filter(vendor=template.get_resource_vendor(), short_name=template.get_resource_name(), version=template.get_resource_version())[:1]
# Create/recover catalogue resource
if len(resources) == 1:
resource = resources[0]
else:
if packaged:
resource = add_widget_from_wgt(file_contents, executor_user, wgt_file=wgt_file)
else:
resource = add_resource_from_template(templateURL, template_contents, executor_user)
return resource
示例8: publish
def publish(self, endpoint, wgt_file, user, request=None, template=None):
if template is None:
template = TemplateParser(wgt_file.get_template())
resource_info = template.get_resource_info()
mimetypes = {
'widget': 'application/x-widget+mashable-application-component',
'operator': 'application/x-operator+mashable-application-component',
'mashup': 'application/x-mashup+mashable-application-component',
}
store = endpoint['store']
adaptor = get_market_adaptor(self._user, self._name)
user_data = get_market_user_data(user, self._user, self._name)
storeclient = adaptor.get_store(store)
store_token_key = store + '/token'
if store_token_key in user_data:
token = user_data[store_token_key]
else:
token = user_data['idm_token']
storeclient.upload_resource(
resource_info['title'],
resource_info['version'],
"_".join((resource_info['vendor'], resource_info['name'], resource_info['version'])) + '.wgt',
resource_info['description'],
mimetypes[resource_info['type']],
wgt_file.get_underlying_file(),
token
)
示例9: test_basic_operator_creation_from_rdf
def test_basic_operator_creation_from_rdf(self):
template = self.read_file('operatorTemplate1.rdf')
parser = TemplateParser(template)
data = parser.get_resource_info()
self.assertEqual(data['vendor'], 'Wirecloud')
self.assertEqual(data['name'], 'test operator')
self.assertEqual(data['type'], 'operator')
self.assertEqual(data['version'], '0.1')
self.assertEqual(data['email'], '[email protected]')
self.assertEqual(data['wiring']['inputs'][0]['label'], 'slot')
self.assertEqual(data['wiring']['inputs'][0]['type'], 'text')
self.assertEqual(data['wiring']['inputs'][0]['friendcode'], 'test_friend_code')
self.assertEqual(data['wiring']['outputs'][0]['label'], 'event')
self.assertEqual(data['wiring']['outputs'][0]['type'], 'text')
self.assertEqual(data['wiring']['outputs'][0]['friendcode'], 'test_friend_code')
self.assertEqual(data['preferences'][0]['label'], 'Preference label')
self.assertEqual(data['preferences'][0]['description'], 'Preference description')
self.assertEqual(data['preferences'][0]['default'], 'value')
self.assertEqual(len(data['js_files']), 5)
self.assertEqual(data['js_files'][0], '/examplecode1.js')
self.assertEqual(data['js_files'][1], '/examplecode2.js')
self.assertEqual(data['js_files'][2], '/examplecode3.js')
self.assertEqual(data['js_files'][3], '/examplecode4.js')
self.assertEqual(data['js_files'][4], '/examplecode5.js')
示例10: check_mashup_dependencies
def check_mashup_dependencies(template, user):
if not isinstance(template, TemplateParser):
template = TemplateParser(template)
missing_dependencies = []
workspace_info = template.get_resource_info()
for tab_entry in workspace_info['tabs']:
for resource in tab_entry['resources']:
try:
catalogue_resource = CatalogueResource.objects.get(vendor=resource.get('vendor'), short_name=resource.get('name'), version=resource.get('version'))
if not catalogue_resource.is_available_for(user):
raise CatalogueResource.DoesNotExist
except CatalogueResource.DoesNotExist:
missing_dependencies.append('/'.join((resource.get('vendor'), resource.get('name'), resource.get('version'))))
for id_, op in workspace_info['wiring']['operators'].iteritems():
(vendor, name, version) = op['name'].split('/')
try:
resource = CatalogueResource.objects.get(vendor=vendor, short_name=name, version=version)
if not resource.is_available_for(user):
raise CatalogueResource.DoesNotExist
except CatalogueResource.DoesNotExist:
missing_dependencies.append('/'.join((vendor, name, version)))
if len(missing_dependencies) > 0:
raise MissingDependencies(missing_dependencies)
示例11: undeploy_tenant_ac
def undeploy_tenant_ac(request):
id_4CaaSt, wgt_file, fileURL = _parse_ac_request(request)
# Process 4CaaSt Id
username = parse_username(id_4CaaSt)
user = get_object_or_404(User, username=username)
try:
if user.tenantprofile_4CaaSt.id_4CaaSt != id_4CaaSt:
raise Http404
except TenantProfile.DoesNotExist:
raise Http404
# If the resource is a mashup, remove the assigned workspace
template = TemplateParser(wgt_file.get_template())
if template.get_resource_type() == 'mashup':
Workspace.objects.filter(creator=user, name=template.get_resource_info()['display_name']).delete()
# Uninstall de resource
template = TemplateParser(wgt_file.get_template())
resource = CatalogueResource.objects.get(vendor=template.get_resource_vendor(), short_name=template.get_resource_name(), version=template.get_resource_version())
resource.users.remove(user)
return HttpResponse(status=204)
示例12: test_basic_widget_creation_from_rdf
def test_basic_widget_creation_from_rdf(self):
template_uri = "http://example.com/path/widget.rdf"
template = self.read_template('template1.rdf')
parser = TemplateParser(template)
data = parser.get_resource_info()
self.assertIn('requirements', data)
self.assertItemsEqual(data['requirements'], ({'type': 'feature', 'name': 'Wirecloud'},))
downloader.download_http_content.set_response(template_uri, template)
downloader.download_http_content.set_response('http://example.com/path/test.html', BASIC_HTML_GADGET_CODE)
widget = install_resource(template, template_uri, self.user, False).widget
self.changeLanguage('en')
data = get_widget_data(widget)
self.assertEqual(data['uri'], 'Wirecloud/test/0.1')
self.assertEqual(data['vendor'], 'Wirecloud')
self.assertEqual(data['name'], 'test')
self.assertEqual(data['version'], '0.1')
self.assertEqual(data['variables']['prop']['label'], u'Property Label')
self.assertEqual(data['variables']['prop']['aspect'], 'PROP')
self.assertEqual(data['variables']['pref']['label'], u'Preference Label')
self.assertEqual(data['variables']['pref']['value_options'], [[u'1', u'Option Name']])
self.assertEqual(data['variables']['pref']['aspect'], 'PREF')
self.assertEqual(data['variables']['event']['label'], u'Event Label')
self.assertEqual(data['variables']['event']['aspect'], 'EVEN')
self.assertEqual(data['variables']['slot']['label'], u'Slot Label')
self.assertEqual(data['variables']['slot']['aspect'], 'SLOT')
示例13: _parse_ac_request
def _parse_ac_request(request):
fileURL = None
file_contents = None
content_type = get_content_type(request)[0]
try:
data = json.loads(request.body)
except Exception as e:
msg = _("malformed json data: %s") % unicode(e)
return build_error_response(request, 400, msg)
if 'url' not in data:
return build_error_response(request, 400, _('Missing widget URL'))
fileURL = data.get('url')
id_4CaaSt = data.get('4CaaStID')
if id_4CaaSt is None:
return build_error_response(request, 400, _('Missing 4CaaStID'))
if not isinstance(id_4CaaSt, string_types) or id_4CaaSt.strip() == '':
return build_error_response(request, 400, _('Invalid 4CaaStID'))
try:
downloaded_file = download_http_content(fileURL)
except:
return build_error_response(request, 409, _('Mashable application component could not be downloaded'))
downloaded_file = StringIO(downloaded_file)
file_contents = WgtFile(downloaded_file)
# Create a custom version of the resource
template = TemplateParser(file_contents.get_template())
template_info = template.get_resource_info()
template_info['name'] += '@' + id_4CaaSt
for pref_name, pref_value in six.iteritems(data.get('preferences', {})):
for widget_pref_index, widget_pref in enumerate(template_info['preferences']):
if widget_pref['name'] == pref_name:
template_info['preferences'][widget_pref_index]['readonly'] = True
template_info['preferences'][widget_pref_index]['value'] = pref_value
break
# Write a new Wgt file
new_file = StringIO()
zin = zipfile.ZipFile(downloaded_file, 'r')
zout = zipfile.ZipFile(new_file, 'w')
zout.writestr('config.xml', write_rdf_description(template_info))
for item in zin.infolist():
if item.filename == 'config.xml':
continue
zout.writestr(item, zin.read(item.filename))
zin.close()
zout.close()
file_contents = WgtFile(new_file)
return id_4CaaSt, file_contents, fileURL
示例14: add_packaged_resource
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()
resource_id = (
resource_info['vendor'],
resource_info['name'],
resource_info['version'],
)
file_name = '_'.join(resource_id) + '.wgt'
check_packaged_resource(wgt_file, resource_info)
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
示例15: publish
def publish(self, endpoint, wgt_file, user, request=None, template=None):
if template is None:
template = TemplateParser(wgt_file.get_template())
resource_info = template.get_resource_processed_info(lang='en')
mimetypes = {
'widget': 'application/x-widget+mashable-application-component',
'operator': 'application/x-operator+mashable-application-component',
'mashup': 'application/x-mashup+mashable-application-component',
}
store = endpoint['store']
adaptor = get_market_adaptor(self._user, self._name)
user_data = get_market_user_data(user, self._user, self._name)
storeclient = adaptor.get_store(store)
store_token_key = store + '/token'
if store_token_key in user_data:
token = user_data[store_token_key]
else:
token = user_data['idm_token']
wirecloud_plugin_supported = False
try:
supported_plugins = storeclient.get_supported_plugins(token)
for plugin in supported_plugins:
if plugin.get('name', '').lower() == 'wirecloud component':
wirecloud_plugin_supported = True
except UnexpectedResponse as e:
if e.status != 404:
raise e
if wirecloud_plugin_supported:
storeclient.upload_resource(
resource_info['title'],
resource_info['version'],
"_".join((resource_info['vendor'], resource_info['name'], resource_info['version'])) + '.wgt',
resource_info['description'],
"Mashable application component",
wgt_file.get_underlying_file(),
token,
resource_type="Wirecloud component")
else:
storeclient.upload_resource(
resource_info['title'],
resource_info['version'],
"_".join((resource_info['vendor'], resource_info['name'], resource_info['version'])) + '.wgt',
resource_info['description'],
mimetypes[resource_info['type']],
wgt_file.get_underlying_file(),
token)