Beispiel #1
0
    def _render_nvs_rdf(self):
        if "/standard_name/" in self.concept.uri:
            api_concept_uri = "$DB2RDF_STANDARD_NAME_URI" + self.concept.uri.split(
                "/standard_name/")[1]
        else:
            api_concept_uri = "$DB2RDF_COLLECTIONS_URI" + self.concept.uri.split(
                "/collection/")[1]
        r = requests.get(api_concept_uri)

        if self.mediatype in [
                "application/rdf+xml", "application/xml", "text/xml"
        ]:
            return Response(
                r.text,
                mimetype=self.mediatype,
                headers=self.headers,
            )
        else:
            g = Graph().parse(data=r.text, format="xml")

            # serialise in other RDF format
            if self.mediatype in ["application/rdf+json", "application/json"]:
                graph_text = g.serialize(format="json-ld")
            else:
                graph_text = g.serialize(format=self.mediatype)

            return Response(
                graph_text,
                mimetype=self.mediatype,
                headers=self.headers,
            )
Beispiel #2
0
    def pickle_to_file(vocab_id, g):
        logging.debug("Pickling file: {}".format(vocab_id))
        path = os.path.join(config.APP_DIR, "vocab_files", vocab_id)
        # TODO: Check if file_name already has extension
        with open(path + ".p", "wb") as f:
            pickle.dump(g, f)
            f.close()

        g.serialize(path + ".ttl", format="turtle")
Beispiel #3
0
    def _render_skos_rdf(self):
        # get Collection RDF
        # TODO: re-assemble RDF from Concept object
        g = Graph()

        # serialise in the appropriate RDF format
        if self.mediatype in ["application/rdf+json", "application/json"]:
            return g.serialize(format="json-ld")
        else:
            return g.serialize(format=self.mediatype)
Beispiel #4
0
    def get_sparql_service_description(rdf_format="turtle"):
        """Return an RDF description of PROMS' read only SPARQL endpoint in a requested format

        :param rdf_format: 'turtle', 'n3', 'xml', 'json-ld'
        :return: string of RDF in the requested format
        """
        sd_ttl = """
            @prefix rdf:    <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .
            @prefix sd:     <http://www.w3.org/ns/sparql-service-description#> .
            @prefix sdf:    <http://www.w3.org/ns/formats/> .
            @prefix void: <http://rdfs.org/ns/void#> .
            @prefix xsd: <http://www.w3.org/2001/XMLSchema#> .

            <http://gnafld.net/sparql>
                a                       sd:Service ;
                sd:endpoint             <%(BASE_URI)s/function/sparql> ;
                sd:supportedLanguage    sd:SPARQL11Query ; # yes, read only, sorry!
                sd:resultFormat         sdf:SPARQL_Results_JSON ;  # yes, we only deliver JSON results, sorry!
                sd:feature sd:DereferencesURIs ;
                sd:defaultDataset [
                    a sd:Dataset ;
                    sd:defaultGraph [
                        a sd:Graph ;
                        void:triples "100"^^xsd:integer
                    ]
                ]
            .
        """
        g = Graph().parse(io.StringIO(sd_ttl), format="turtle")
        rdf_formats = list(set([x for x in Renderer.RDF_SERIALIZER_TYPES_MAP]))
        if rdf_format in rdf_formats:
            return g.serialize(format=rdf_format)
        else:
            raise ValueError("Input parameter rdf_format must be one of: " +
                             ", ".join(rdf_formats))
Beispiel #5
0
def edit_glass(id):
    """ Edit the name of a glass-type.

    |  **URL:** /beer/api/v0.1/glasses/<glass_id>
    |  **Method:** PUT
    |  **Query Args:** None
    |  **Authentication:** Token/Password

    Example:

    *Rename glass with id# 2 to 'Goblet'* ::

      PUT http://domain.tld/beer/api/v0.1/glasses/2
      data={"name":"Goblet"}

    """

    g = Glass.query.get_or_404(id)
    if 'name' in request.json and type(request.json['name']) != str:
        flash(u'Invalid input', 'error')
        abort(400)
    name = request.json.get('name')

    if name is not None:
        if Glass.query.filter_by(name=name).first() is not None:
            flash(u'Glass with that name already exists', 'error')
            abort(400)
        g.name = name
    db.session.commit()
    return jsonify({'status': 'Glass-type updated successfully',\
            'results': g.serialize()})
Beispiel #6
0
def list_glasses():
    """ List glass types in the database.

    |  **URL:** /beer/api/v0.1/glasses
    |  **Method:** GET
    |  **Query Args:** sort_by=<column name> <desc>
    |  **Authentication:** None

    Example:

    *List all glass styles in the database* ::

      GET http://domain.tld/beer/api/v0.1/glasses

    *List glass styles by name descending* ::

      GET http://domain.tld/beer/api/v0.1/glasses?sort_by=name%20desc
    
    """
    sort = request.args.get('sort_by') or None
    if sort:
        try:
            glasses = Glass.query.order_by(sort).all()
        except OperationalError:
            flash(u'Invalid sorting value specified', 'error')
            abort(400)
    else:
        glasses = Glass.query.all()
    return jsonify(results=[g.serialize() for g in glasses])
Beispiel #7
0
    def _render_skos_rdf(self):
        g = Graph()
        g.bind("dct", DCTERMS)
        g.bind("skos", SKOS)

        c = URIRef(self.concept.uri)

        # Concept SKOS metadata
        g.add((c, RDF.type, SKOS.Concept))
        g.add((c, SKOS.prefLabel,
               Literal(self.concept.prefLabel, lang=config.DEFAULT_LANGUAGE)))
        g.add((c, SKOS.definition,
               Literal(self.concept.definition, lang=config.DEFAULT_LANGUAGE)))

        for k, v in self.concept.related_instances.items():
            for k2, v2 in v.items():
                if k2 == "instances":
                    for inst in v2:
                        g.add((
                            c,
                            URIRef(k),
                            URIRef(inst[0]
                                   )  # only URIs for RDF, not prefLabels too
                        ))

        if self.concept.other_properties is not None:
            for prop in self.concept.other_properties:
                if str(prop.value).startswith("http"):
                    g.add((c, URIRef(prop.uri), URIRef(prop.value)))
                else:
                    g.add((c, URIRef(prop.uri), Literal(prop.value)))

        # serialise in the appropriate RDF format
        if self.mediatype in ["application/rdf+json", "application/json"]:
            graph_text = g.serialize(format="json-ld")
        else:
            graph_text = g.serialize(format=self.mediatype)

        return Response(
            graph_text,
            mimetype=self.mediatype,
            headers=self.headers,
        )
Beispiel #8
0
def get_glass(id):
    """ Get data about a particular glass in the database.

    |  **URL:** /beer/api/v0.1/glasses/<glass_id>
    |  **Method:** GET
    |  **Query Args:** None
    |  **Authentication:** None

    Example:

    *Get data about glass with id# 3* ::

      GET http://domain.tld/beer/api/v0.1/glasses/3

    """
    g = Glass.query.get_or_404(id)
    return jsonify(results=g.serialize())
Beispiel #9
0
def tobj(objname):
    SCHEMA = Namespace('http://schema.org/')
    SPDX = Namespace('http://www.spdx.org/rdf/terms#')
    n = NamespaceManager(Graph())
    n.bind("schema", SCHEMA)
    n.bind("spdx", SPDX)
    c = get_db().cursor()
    c.execute('SELECT * FROM objects WHERE id=?', (objname,))
    obj = c.fetchone()
    g = Graph()
    g.namespace_manager = n
    objuri = URIRef("http://localhost:5000/b/" + obj[0])
    robjuri = URIRef("http://localhost:5000/r/" + obj[0])
    md5node = BNode()
    g.add((md5node, SPDX.checksumValue, Literal(obj[2])))
    g.add((md5node, SPDX.algorithm, URIRef("http://packages.qa.debian.org/#checksumAlgorithm_md5sum")))
    g.add((objuri, SPDX.checksum, md5node))
    g.add((objuri, SCHEMA.fileSize, Literal(obj[1])))
    return Response(g.serialize(format="turtle"), mimetype="text/plain")
Beispiel #10
0
    def _render_skos_rdf(self):
        # make Collection RDF from Collection object in memory
        # (this is faster than re-querying for RDF from the main cache or a vocab's source)
        # this is the SKOS view - only SKOS stuff
        g = Graph()
        g.bind("dcterms", DCTERMS)
        g.bind("skos", SKOS)

        c = URIRef(self.collection.uri)

        # Collection metadata
        g.add((
            c,
            RDF.type,
            SKOS.Collection
        ))
        g.add((
            c,
            SKOS.prefLabel,
            Literal(self.collection.prefLabel, lang=config.DEFAULT_LANGUAGE)
        ))
        if self.collection.definition is not None:
            g.add((
                c,
                SKOS.definition,
                Literal(self.collection.definition, lang=config.DEFAULT_LANGUAGE)
            ))
        for k, v in self.collection.source.items():
            if k == "provenance" and v is not None:
                g.add((
                    c,
                    DCTERMS.provenance,
                    Literal(self.collection.source["provenance"], lang=config.DEFAULT_LANGUAGE)
                ))
            elif k == "source" and v is not None:
                g.add((
                    c,
                    DCTERMS.source,
                    URIRef(self.collection.source["source"])
                ))
            elif k == "wasDerivedFrom" and v is not None:
                g.add((
                    c,
                    DCTERMS.provenance,
                    URIRef(self.collection.source["wasDerivedFrom"])
                ))
        # vocab
        if self.collection.vocab_uri is not None:
            g.add((
                c,
                SKOS.inScheme,
                URIRef(self.collection.vocab_uri),
            ))

        # members
        for m in self.collection.members:
            g.add((
                c,
                SKOS.member,
                URIRef(m[0]),
            ))

        # serialise in the appropriate RDF format
        if self.mediatype in ["application/rdf+json", "application/json"]:
            graph_text = g.serialize(format="json-ld")
        else:
            graph_text = g.serialize(format=self.mediatype)

        return Response(
            graph_text,
            mimetype=self.mediatype,
            headers=self.headers,
        )