当前位置: 首页>>代码示例>>Python>>正文


Python XMLdata.unparse方法代码示例

本文整理汇总了Python中mgi.models.XMLdata.unparse方法的典型用法代码示例。如果您正苦于以下问题:Python XMLdata.unparse方法的具体用法?Python XMLdata.unparse怎么用?Python XMLdata.unparse使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在mgi.models.XMLdata的用法示例。


在下文中一共展示了XMLdata.unparse方法的8个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: test_update_publish_draft

# 需要导入模块: from mgi.models import XMLdata [as 别名]
# 或者: from mgi.models.XMLdata import unparse [as 别名]
 def test_update_publish_draft(self):
     status = Status.ACTIVE
     new_xml = "<Resource localid='' status='"+status+"'><identity>" \
            "<title>My new software</title></identity><curation><publisher>PF</publisher><contact><name></name>" \
            "</contact></curation><content><description>This is a new record</description><subject></subject>" \
            "<referenceURL></referenceURL></content></Resource>"
     id = self.createXMLData(ispublished=True)
     xmlData = XMLdata.get(id)
     self.assertNotEquals(new_xml, XMLdata.unparse(xmlData['content']))
     adminId = self.getAdmin().id
     template = self.createTemplate()
     elements = SchemaElement.objects().all()
     self.assertEqual(len(elements), 0)
     elementsForm = FormData.objects().all()
     self.assertEqual(len(elementsForm), 0)
     formData = self.createFormData(user=adminId, name='name', template=str(template.id), xml_data=new_xml,
                                    xml_data_id=str(id))
     url = '/dashboard/update_publish_draft'
     data = {'draft_id': str(formData.id)}
     r = self.doRequestGetAdminClientLogged(url=url, data=data)
     xmlDataInDatabase = XMLdata.get(id)
     elements = SchemaElement.objects().all()
     self.assertEqual(len(elements), 0)
     elementsForm = FormData.objects().all()
     self.assertEqual(len(elementsForm), 0)
     self.assertEquals(etree.XML(new_xml).text, etree.XML(str(XMLdata.unparse(xmlDataInDatabase['content']))).text)
     self.assertEquals(True, xmlDataInDatabase.get('ispublished'))
     self.assertEquals(str(adminId), xmlDataInDatabase.get('iduser'))
     self.assertNotEquals(xmlData.get('lastmodificationdate'), xmlDataInDatabase.get('lastmodificationdate'))
     self.assertNotEquals(xmlData.get('publicationdate'), xmlDataInDatabase.get('publicationdate'))
     self.assertEquals(status, xmlDataInDatabase.get('status'))
开发者ID:usnistgov,项目名称:MaterialsResourceRegistry,代码行数:33,代码来源:tests_ajax.py

示例2: explore_detail_result_process

# 需要导入模块: from mgi.models import XMLdata [as 别名]
# 或者: from mgi.models.XMLdata import unparse [as 别名]
def explore_detail_result_process(request):
    result_id = request.GET['id']
    xmlString = XMLdata.get(result_id)
    schemaId = xmlString['schema']
    if 'title' in request.GET:
        title = request.GET['title']
    else:
        title = xmlString['title']
    xmlString = XMLdata.unparse(xmlString['content']).encode('utf-8')
    xsltPath = os.path.join(settings.SITE_ROOT, 'static', 'resources', 'xsl', 'xml2html.xsl')
    xslt = etree.parse(xsltPath)
    transform = etree.XSLT(xslt)

    #Check if a custom detailed result XSLT has to be used
    schema = Template.objects.get(pk=schemaId)
    try:
        if (xmlString != ""):
            dom = etree.fromstring(str(xmlString))
            if schema.ResultXsltDetailed:
                shortXslt = etree.parse(BytesIO(schema.ResultXsltDetailed.content.encode('utf-8')))
                shortTransform = etree.XSLT(shortXslt)
                newdom = shortTransform(dom)
            else:
                newdom = transform(dom)
    except Exception, e:
        #We use the default one
        newdom = transform(dom)
开发者ID:usnistgov,项目名称:MaterialsResourceRegistry,代码行数:29,代码来源:views.py

示例3: explore_detail_result_keyword

# 需要导入模块: from mgi.models import XMLdata [as 别名]
# 或者: from mgi.models.XMLdata import unparse [as 别名]
def explore_detail_result_keyword(request):
    template = loader.get_template("oai_pmh/explore/explore_detail_results_keyword.html")
    result_id = request.GET["id"]
    record = OaiRecord.objects.get(pk=result_id)
    # schemaId = xmlString['schema']
    if "title" in request.GET:
        title = request.GET["title"]
    else:
        title = record.identifier
    xmlString = XMLdata.unparse(record.getMetadataOrdered()).encode("utf-8")
    xsltPath = os.path.join(settings.SITE_ROOT, "static", "resources", "xsl", "xml2html.xsl")
    xslt = etree.parse(xsltPath)
    transform = etree.XSLT(xslt)
    dom = etree.fromstring(str(xmlString))

    # Check if a custom list result XSLT has to be used
    try:
        metadataFormat = record.metadataformat
        if metadataFormat.template.ResultXsltDetailed:
            listXslt = etree.parse(BytesIO(metadataFormat.template.ResultXsltDetailed.content.encode("utf-8")))
            transform = etree.XSLT(listXslt)
            newdom = transform(dom)
        else:
            newdom = transform(dom)
    except Exception, e:
        # We use the default one
        newdom = transform(dom)
开发者ID:usnistgov,项目名称:MaterialsResourceRegistry,代码行数:29,代码来源:views.py

示例4: test_parse_unparse_test

# 需要导入模块: from mgi.models import XMLdata [as 别名]
# 或者: from mgi.models.XMLdata import unparse [as 别名]
 def test_parse_unparse_test(self):
     with open(join(RESOURCES_PATH, 'test.xml'), 'r') as data_file:
         data_content = data_file.read()
         # test parsing
         xml_data = XMLdata(xml=data_content)
         # test unparsing
         xml_string = XMLdata.unparse(xml_data.content['content'])
         self.assertEquals(_strip(data_content), _strip(xml_string))
开发者ID:usnistgov,项目名称:MaterialsResourceRegistry,代码行数:10,代码来源:tests_parse_unparse.py

示例5: dashboard_detail_resource

# 需要导入模块: from mgi.models import XMLdata [as 别名]
# 或者: from mgi.models.XMLdata import unparse [as 别名]
def dashboard_detail_resource(request) :
    template = loader.get_template('dashboard/my_dashboard_detail_resource.html')
    result_id = request.GET['id']
    type = request.GET['type']

    if type=='form':
        form_data = FormData.objects.get(pk=ObjectId(result_id))
        xmlString = form_data.xml_data.encode('utf-8')
        title = form_data.name
        schemaId = form_data.template
    elif type=='record':
        xmlString = XMLdata.get(result_id)
        title = xmlString['title']
        schemaId = xmlString['schema']
        xmlString = XMLdata.unparse(xmlString['content']).encode('utf-8')


    xsltPath = os.path.join(settings.SITE_ROOT, 'static', 'resources', 'xsl', 'xml2html.xsl')
    xslt = etree.parse(xsltPath)
    transform = etree.XSLT(xslt)

    #Check if a custom detailed result XSLT has to be used
    try:
        if (xmlString != ""):
            dom = etree.fromstring(str(xmlString))
            schema = Template.objects.get(pk=schemaId)
            if schema.ResultXsltDetailed:
                shortXslt = etree.parse(BytesIO(schema.ResultXsltDetailed.content.encode('utf-8')))
                shortTransform = etree.XSLT(shortXslt)
                newdom = shortTransform(dom)
            else:
                newdom = transform(dom)
        else:
            newdom = "No data to display"
    except Exception, e:
        #We use the default one
        newdom = transform(dom)
开发者ID:usnistgov,项目名称:MaterialsResourceRegistry,代码行数:39,代码来源:views.py

示例6: get_results_by_instance_keyword

# 需要导入模块: from mgi.models import XMLdata [as 别名]
# 或者: from mgi.models.XMLdata import unparse [as 别名]
def get_results_by_instance_keyword(request):
    print 'BEGIN def getResultsKeyword(request)'
    resultsByKeyword = []
    results = []
    resultString = ""

    #Instance
    json_instances = []
    if 'HTTPS' in request.META['SERVER_PROTOCOL']:
        protocol = "https"
    else:
        protocol = "http"
    instance = Instance(name="Local", protocol=protocol, address=request.META['REMOTE_ADDR'], port=request.META['SERVER_PORT'], access_token="token", refresh_token="token")
    json_instances.append(instance.to_json())
    request.session['instancesExplore'] = json_instances
    sessionName = "resultsExploreOaiPMh" + instance['name']


    try:
        keyword = request.GET['keyword']
        schemas = request.GET.getlist('schemas[]')
        userSchemas = request.GET.getlist('userSchemas[]')
        refinements = refinements_to_mongo(request.GET.getlist('refinements[]'))
        if 'onlySuggestions' in request.GET:
            onlySuggestions = json.loads(request.GET['onlySuggestions'])
        else:
            onlySuggestions = False
        registries = request.GET.getlist('registries[]')
    except:
        keyword = ''
        schemas = []
        userSchemas = []
        refinements = {}
        onlySuggestions = True
        registries = []

    #We get all template versions for the given schemas
    #First, we take care of user defined schema
    templatesIDUser = Template.objects(title__in=userSchemas).distinct(field="id")
    templatesIDUser = [str(x) for x in templatesIDUser]

    #Take care of the rest, with versions
    templatesVersions = Template.objects(title__in=schemas).distinct(field="templateVersion")

    #We get all templates ID, for all versions
    allTemplatesIDCommon = TemplateVersion.objects(pk__in=templatesVersions, isDeleted=False).distinct(field="versions")
    #We remove the removed version
    allTemplatesIDCommonRemoved = TemplateVersion.objects(pk__in=templatesVersions, isDeleted=False).distinct(field="deletedVersions")
    templatesIDCommon = list(set(allTemplatesIDCommon) - set(allTemplatesIDCommonRemoved))

    templatesID = templatesIDUser + templatesIDCommon
    if len(registries) == 0:
        #We retrieve deactivated registries so as not to get their metadata formats
        deactivatedRegistries = [str(x.id) for x in OaiRegistry.objects(isDeactivated=True).order_by('id')]
        metadataFormatsID = OaiMetadataFormat.objects(template__in=templatesID, registry__not__in=deactivatedRegistries).distinct(field="id")
    else:
        #We retrieve registries from the refinement
        metadataFormatsID = OaiMetadataFormat.objects(template__in=templatesID, registry__in=registries).distinct(field="id")


    instanceResults = OaiRecord.executeFullTextQuery(keyword, metadataFormatsID, refinements)
    if len(instanceResults) > 0:
        if not onlySuggestions:
            xsltPath = os.path.join(settings.SITE_ROOT, 'static/resources/xsl/xml2html.xsl')
            xslt = etree.parse(xsltPath)
            transform = etree.XSLT(xslt)
            template = loader.get_template('oai_pmh/explore/explore_result_keyword.html')

        #Retrieve schema and registries. Avoid to retrieve the information for each result
        registriesName = {}
        objMetadataFormats = {}
        listRegistriesID = set([x['registry'] for x in instanceResults])
        for registryId in listRegistriesID:
            obj = OaiRegistry.objects(pk=registryId).get()
            registriesName[str(registryId)] = obj.name
        listSchemaId = set([x['metadataformat'] for x in instanceResults])
        for schemaId in listSchemaId:
            obj = OaiMetadataFormat.objects(pk=schemaId).get()
            objMetadataFormats[str(schemaId)] = obj

        listItems = []
        xmltodictunparse = XMLdata.unparse
        appendResult = results.append
        toXML = etree.XML
        parse = etree.parse
        XSLT = etree.XSLT
        if not onlySuggestions:
            for instanceResult in instanceResults:
                custom_xslt = False
                appendResult({'title':instanceResult['identifier'], 'content':xmltodictunparse(instanceResult['metadata']),'id':str(instanceResult['_id'])})
                dom = toXML(str(xmltodictunparse(instanceResult['metadata']).encode('utf-8')))
                #Check if a custom list result XSLT has to be used
                try:
                    metadataFormat = objMetadataFormats[str(instanceResult['metadataformat'])]
                    if metadataFormat.template.ResultXsltList:
                        listXslt = parse(BytesIO(metadataFormat.template.ResultXsltList.content.encode('utf-8')))
                        listTransform = XSLT(listXslt)
                        newdom = listTransform(dom)
                        custom_xslt = True
                    else:
#.........这里部分代码省略.........
开发者ID:usnistgov,项目名称:MaterialsResourceRegistry,代码行数:103,代码来源:ajax.py

示例7: get_record

# 需要导入模块: from mgi.models import XMLdata [as 别名]
# 或者: from mgi.models.XMLdata import unparse [as 别名]
    def get_record(self):
        try:
            #Bool if we need to transform the XML via XSLT
            hasToBeTransformed = False
            #Check if the identifier pattern is OK
            id = self.check_identifier()
            #Template name
            self.template_name = 'oai_pmh/xml/get_record.xml'
            query = dict()
            #Convert id to ObjectId
            try:
                query['_id'] = ObjectId(id)
                #The record has to be published
                query['ispublished'] = True
            except Exception:
                raise idDoesNotExist(self.identifier)
            data = XMLdata.executeQueryFullResult(query)
            #This id doesn't exist
            if len(data) == 0:
                raise idDoesNotExist(self.identifier)
            data = data[0]
            #Get the template for the identifier
            template = data['schema']
            #Retrieve sets for this template
            sets = OaiMySet.objects(templates=template).all()
            #Retrieve the XSLT for the transformation
            try:
                #Get the metadataformat for the provided prefix
                myMetadataFormat = OaiMyMetadataFormat.objects.get(metadataPrefix=self.metadataPrefix)
                #If this metadata prefix is not associated to a template, we need to retrieve the XSLT to do the transformation
                if not myMetadataFormat.isTemplate:
                    hasToBeTransformed = True
                    #Get information about the XSLT for the MF and the template
                    objTempMfXslt = OaiTemplMfXslt.objects(myMetadataFormat=myMetadataFormat, template=template, activated=True).get()
                    #If no information or desactivated
                    if not objTempMfXslt.xslt:
                        raise cannotDisseminateFormat(self.metadataPrefix)
                    else:
                        #Get the XSLT for the transformation
                        xslt = objTempMfXslt.xslt
            except:
                raise cannotDisseminateFormat(self.metadataPrefix)

            #Transform XML data
            dataToTransform = [{'title': data['_id'], 'content': self.cleanXML(XMLdata.unparse(data['content']))}]
            if hasToBeTransformed:
                dataXML = self.getXMLTranformXSLT(dataToTransform, xslt)
            else:
                dataXML = dataToTransform

            #Fill the response
            record_info = {
                'identifier': self.identifier,
                'last_modified': self.get_last_modified_date(data),
                'sets': sets,
                'XML': dataXML[0]['content'],
                'deleted': data.get('status', '') == Status.DELETED
            }
            return self.render_to_response(record_info)
        except OAIExceptions, e:
            return self.errors(e.errors)
开发者ID:usnistgov,项目名称:MaterialsResourceRegistry,代码行数:63,代码来源:views.py

示例8: set

# 需要导入模块: from mgi.models import XMLdata [as 别名]
# 或者: from mgi.models.XMLdata import unparse [as 别名]
         templatesID = set(templatesID).intersection([str(x.id) for x in setsTemplates.templates])
     except Exception, e:
         raise noRecordsMatch
 #For each template found
 for template in templatesID:
     #Retrieve sets for this template
     sets = OaiMySet.objects(templates=template).all()
     query['schema'] = template
     #The record has to be published
     query['ispublished'] = True
     #Get all records for this template
     data = XMLdata.executeQueryFullResult(query)
     #IF no records, go to the next template
     if len(data) == 0:
         continue
     dataToTransform = [{'title': x['_id'], 'content': self.cleanXML(XMLdata.unparse(x['content']))} for x in data]
     if myMetadataFormat.isTemplate:
         #No transformation needed
         dataXML = dataToTransform
     else:
         #Get the XSLT file
         xslt = objTempMfXslt(template=template).get().xslt
         #Transform all XML data (1 call)
         dataXML = self.getXMLTranformXSLT(dataToTransform, xslt)
     #Add each record
     for elt in data:
         identifier = '%s:%s:id/%s' % (settings.OAI_SCHEME, settings.OAI_REPO_IDENTIFIER,
               elt['_id'])
         xmlStr = filter(lambda xml: xml['title'] == elt['_id'], dataXML)[0]
         record_info = {
             'identifier': identifier,
开发者ID:usnistgov,项目名称:MaterialsResourceRegistry,代码行数:33,代码来源:views.py


注:本文中的mgi.models.XMLdata.unparse方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。