Python rdflib.namespace.RDF Examples

The following are 10 code examples of rdflib.namespace.RDF(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module rdflib.namespace , or try the search function .
Example #1
Source File: ldp_nr.py    From lakesuperior with Apache License 2.0 6 votes vote down vote up
def create_or_replace(self, create_only=False):
        """
        Create a new binary resource with a corresponding RDF representation.

        :param bool create_only: Whether the resource is being created or
            updated.
        """
        # Persist the stream.
        self.digest, self.size = nonrdfly.persist(
                self.uid, self.stream, prov_cksum_algo=self.prov_cksum_algo,
                prov_cksum=self.prov_cksum)

        # Try to persist metadata. If it fails, delete the file.
        logger.debug('Persisting LDP-NR triples in {}'.format(self.uri))
        try:
            ev_type = super().create_or_replace(create_only)
        except:
            # self.digest is also the file UID.
            nonrdfly.delete(self.digest)
            raise
        else:
            return ev_type


    ## PROTECTED METHODS ## 
Example #2
Source File: datatype_to_rdf_tests.py    From arches with GNU Affero General Public License v3.0 5 votes vote down vote up
def setUp(self):
        # for RDF/JSON-LD export tests
        self.DT = DataTypeFactory() 
Example #3
Source File: datatype_from_rdf_tests.py    From arches with GNU Affero General Public License v3.0 5 votes vote down vote up
def setUp(self):
        # for RDF/JSON-LD export tests
        self.DT = DataTypeFactory() 
Example #4
Source File: GraphUtils.py    From dipper with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def add_property_to_graph(results, graph, property_type, property_list):

        for row in results:
            if row in property_list:
                graph.add((row, RDF['type'], property_type))
        return graph 
Example #5
Source File: GraphUtils.py    From dipper with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def digest_id(wordage):   # same as source/Source.hash_id(wordage)
        '''
        Form a deterministic digest of input
        Leading 'b' is an experiment forcing the first char to be non numeric
        but valid hex
        Not required for RDF but some other contexts do not want the leading
        char to be a digit

        : param str wordage arbitrary string
        : return str
        '''
        return 'b' + hashlib.sha1(wordage.encode('utf-8')).hexdigest()[1:20] 
Example #6
Source File: serialize.py    From django-rdf-io with Creative Commons Zero v1.0 Universal 5 votes vote down vote up
def to_rdfbykey(request,model,key):
    """
        take a model name + object id reference to an instance and apply any RDF serialisers defined for this
        allows a key to de appended to the uri or supplied by parameter (easier for uri values)
    """
    if request.GET.get('key'):
        key = request.GET.get('key')
    try: 
        return _tordf(request,model,None,key)
    except Exception as e: 
        return HttpResponse("Model not serialisable to RDF: %s" % e, status=500) 
Example #7
Source File: serialize.py    From django-rdf-io with Creative Commons Zero v1.0 Universal 5 votes vote down vote up
def to_rdfbyid(request,model,id):
    """
        take a model name + object id reference to an instance and apply any RDF serialisers defined for this
    """
    try: 
        return _tordf(request,model,id,None)
    except Exception as e: 
        return HttpResponse("Model not serialisable to RDF: %s" % e, status=500) 
Example #8
Source File: serialize.py    From django-rdf-io with Creative Commons Zero v1.0 Universal 5 votes vote down vote up
def pub_rdf(request,model,id):
    """
        take a model name + object id reference to an instance serialise and push to the configured triplestore
    """
    if request.GET.get('pdb') :
        import pdb; pdb.set_trace()
    # find the model type referenced
    try:
        (app,model) = model.split('.')
        ct = ContentType.objects.get(app_label=app,model=model)
    except:
        ct = ContentType.objects.get(model=model)
    if not ct :
        raise Http404("No such model found")
    oml = ObjectMapping.objects.filter(content_type=ct)
    if not oml :
        raise HttpResponse("Model not serialisable to RDF", status=410 )
    
    obj = get_object_or_404(ct.model_class(), pk=id)
    # ok so object exists and is mappable, better get down to it..

    try:
        rdfstore = get_rdfstore(model,name=request.GET.get('rdfstore') )
    except:
        return  HttpResponse("RDF store not configured", status=410 )
    
    try:
        result = publish(obj, model, oml,rdfstore)
    except Exception as e:
        return HttpResponse("Exception publishing remote RDF content %s" % e,status=500 )
    return HttpResponse("Server reports %s" % result.content,status=result.status_code ) 
Example #9
Source File: ldp_nr.py    From lakesuperior with Apache License 2.0 5 votes vote down vote up
def _add_srv_mgd_triples(self, *args, **kwargs):
        """
        Add all metadata for the RDF representation of the LDP-NR.

        :param BufferedIO stream: The uploaded data stream.
        :param str mimetype: MIME type of the uploaded file.
        :param defaultdict disposition: The ``Content-Disposition`` header
            content, parsed through ``parse_rfc7240``.
        """
        super()._add_srv_mgd_triples(*args, **kwargs)

        # File size.
        logger.debug('Data stream size: {}'.format(self.size))
        self.provided_imr.set((
            self.uri, nsc['premis'].hasSize, Literal(self.size)))

        # Checksum.
        cksum_term = URIRef(f'urn:{default_hash_algo}:{self.digest}')
        self.provided_imr.set((
            self.uri, nsc['premis'].hasMessageDigest, cksum_term))

        # MIME type.
        self.provided_imr.set((
            self.uri, nsc['ebucore']['hasMimeType'], Literal(self.mimetype)))

        # File name.
        logger.debug('Disposition: {}'.format(self.disposition))
        try:
            self.provided_imr.set((
                self.uri, nsc['ebucore']['filename'], Literal(
                self.disposition['attachment']['parameters']['filename'])))
        except (KeyError, TypeError) as e:
            pass 
Example #10
Source File: serialize.py    From django-rdf-io with Creative Commons Zero v1.0 Universal 4 votes vote down vote up
def _tordf(request,model,id,key):
    if request.GET.get('pdb') :
        import pdb; pdb.set_trace()
    format = request.GET.get('_format')
    if format not in ('turtle','json-ld'):
        if format == 'json':
            format = "json-ld"
        else:
            format = "turtle"

    # find the model type referenced
    try:
        (app,model) = model.split('.')
        ct = ContentType.objects.get(app_label=app,model=model)
    except:
        ct = ContentType.objects.get(model=model)
    if not ct :
        raise Http404("No such model found")
    oml = ObjectMapping.objects.filter(content_type=ct)
    if not oml :
        return HttpResponse("Model not serialisable to RDF", status=410 )
    if id :    
        obj = get_object_or_404(ct.model_class(), pk=id)
    else :
        try:
            obj = ct.model_class().objects.get_by_natural_key(key)
        except Exception as e:
            try:
                (prefix,term) = key.split(':')
                ns = Namespace.objects.get(prefix=prefix)
                urikey = "".join((ns.uri,term))
                obj = ct.model_class().objects.get_by_natural_key(urikey)
            except Exception as e2:
                raise e
    
    # ok so object exists and is mappable, better get down to it..
 
    includemembers = True
    if request.GET.get('skip') :
        includemembers = request.GET.get('skip') != 'True'
        
    gr = Graph()
#    import pdb; pdb.set_trace()
#    ns_mgr = NamespaceManager(Graph())
#    gr.namespace_manager = ns_mgr
    try:
        gr = build_rdf(gr, obj, oml, includemembers)
    except Exception as e:
        raise Http404("Error during serialisation: " + str(e) )
    return HttpResponse(content_type="text/turtle; charset=utf-8", content=gr.serialize(format=format))