rdflib-endpoint


Namerdflib-endpoint JSON
Version 0.5.0 PyPI version JSON
download
home_page
SummaryA package to deploy SPARQL endpoint to serve local RDF files, machine learning models, or any other logic implemented in Python, using RDFLib and FastAPI.
upload_time2023-12-08 20:25:49
maintainer
docs_urlNone
author
requires_python>=3.8
licenseMIT License Copyright (c) 2022-present Vincent Emonet <vincent.emonet@gmail.com> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
keywords python rdf rdflib sparql endpoint
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            <div align="center">

# đŸ’Ģ SPARQL endpoint for RDFLib

[![PyPI - Version](https://img.shields.io/pypi/v/rdflib-endpoint.svg?logo=pypi&label=PyPI&logoColor=silver)](https://pypi.org/project/rdflib-endpoint/)
[![PyPI - Python Version](https://img.shields.io/pypi/pyversions/rdflib-endpoint.svg?logo=python&label=Python&logoColor=silver)](https://pypi.org/project/rdflib-endpoint/)

[![Test package](https://github.com/vemonet/rdflib-endpoint/actions/workflows/test.yml/badge.svg)](https://github.com/vemonet/rdflib-endpoint/actions/workflows/test.yml)
[![Publish package](https://github.com/vemonet/rdflib-endpoint/actions/workflows/release.yml/badge.svg)](https://github.com/vemonet/rdflib-endpoint/actions/workflows/release.yml)
[![Coverage Status](https://coveralls.io/repos/github/vemonet/rdflib-endpoint/badge.svg?branch=main)](https://coveralls.io/github/vemonet/rdflib-endpoint?branch=main)

[![license](https://img.shields.io/pypi/l/rdflib-endpoint.svg?color=%2334D058)](https://github.com/vemonet/rdflib-endpoint/blob/main/LICENSE.txt)
[![code style - black](https://img.shields.io/badge/code%20style-black-000000.svg)](https://github.com/psf/black)
[![types - Mypy](https://img.shields.io/badge/types-mypy-blue.svg)](https://github.com/python/mypy)

</div>

`rdflib-endpoint` is a SPARQL endpoint based on RDFLib to **easily serve RDF files locally**, machine learning models, or any other logic implemented in Python via **custom SPARQL functions**.

It aims to enable python developers to easily deploy functions that can be queried in a federated fashion using SPARQL. For example: using a python function to resolve labels for specific identifiers, or run a classifier given entities retrieved using a `SERVICE` query to another SPARQL endpoint.

> Feel free to create an [issue](/issues), or send a pull request if you are facing issues or would like to see a feature implemented.

## ℹī¸ How it works

`rdflib-endpoint` can be used directly from the terminal to quickly serve RDF files through a SPARQL endpoint automatically deployed locally.

It can also be used to define custom SPARQL functions: the user defines and registers custom SPARQL functions, and/or populate the RDFLib Graph using Python, then the endpoint is started using `uvicorn`/`gunicorn`.

The deployed SPARQL endpoint can be used as a `SERVICE` in a federated SPARQL query from regular triplestores SPARQL endpoints. Tested on OpenLink Virtuoso (Jena based) and Ontotext GraphDB (RDF4J based). The endpoint is CORS enabled by default to enable querying it from client JavaScript (can be turned off).

Built with [RDFLib](https://github.com/RDFLib/rdflib) and [FastAPI](https://fastapi.tiangolo.com/).

## đŸ“Ļī¸ Installation

This package requires Python >=3.8, install it  from [PyPI](https://pypi.org/project/rdflib-endpoint/) with:

```shell
pip install rdflib-endpoint
```

The `uvicorn` and `gunicorn` dependencies are not included by default, if you want to install them use the optional dependency `web`:

```bash
pip install "rdflib-endpoint[web]"
```

If you want to use `rdlib-endpoint` as a CLI you can install with the optional dependency `cli`:

```bash
pip install "rdflib-endpoint[cli]"
```

If you want to use [oxigraph](https://github.com/oxigraph/oxigraph) as backend triplestore you can install with the optional dependency `oxigraph`:

```bash
pip install "rdflib-endpoint[oxigraph,cli]"
```

> [!WARNING]
> Oxigraph and `oxrdflib` do not support custom functions, so it can be only used to deploy graphs without custom functions.

## ⌨ī¸ Use the CLI

`rdflib-endpoint` can be used from the command line interface to perform basic utility tasks, such as serving or converting RDF files locally.

Make sure you installed `rdflib-endpoint` with the `cli` optional dependencies:

```bash
pip install "rdflib-endpoint[cli]"
```

### ⚡ī¸ Quickly serve RDF files through a SPARQL endpoint

Use `rdflib-endpoint` as a command line interface (CLI) in your terminal to quickly serve one or multiple RDF files as a SPARQL endpoint.

You can use wildcard and provide multiple files, for example to serve all turtle, JSON-LD and nquads files in the current folder you could run:

```bash
rdflib-endpoint serve *.ttl *.jsonld *.nq
```

> Then access the YASGUI SPARQL editor on http://localhost:8000

If you installed with the Oxigraph optional dependency you can use it as backend triplestore, it is faster and supports some functions that are not supported by the RDFLib query engine (such as `COALESCE()`):

```bash
rdflib-endpoint serve --store Oxigraph "*.ttl" "*.jsonld" "*.nq"
```

### 🔄 Convert RDF files to another format

`rdflib-endpoint` can also be used to quickly merge and convert files from multiple formats to a specific format:

```bash
rdflib-endpoint convert "*.ttl" "*.jsonld" "*.nq" --output "merged.trig"
```

## ✨ Deploy your SPARQL endpoint

`rdflib-endpoint` enables you to easily define and deploy SPARQL endpoints based on RDFLib Graph, ConjunctiveGraph, and Dataset. Additionally it provides helpers to defines custom functions in the endpoint.

Checkout the [`example`](https://github.com/vemonet/rdflib-endpoint/tree/main/example) folder for a complete working app example to get started, including a docker deployment. A good way to create a new SPARQL endpoint is to copy this `example` folder, and start from it.

### 🚨 Deploy as a standalone API

Deploy your SPARQL endpoint as a standalone API:

```python
from rdflib import ConjunctiveGraph
from rdflib_endpoint import SparqlEndpoint

# Start the SPARQL endpoint based on a RDFLib Graph and register your custom functions
g = ConjunctiveGraph()
# TODO: Add triples in your graph

# Then use either SparqlEndpoint or SparqlRouter, they take the same arguments
app = SparqlEndpoint(
    graph=g,
    path="/",
    cors_enabled=True,
    # Metadata used for the SPARQL service description and Swagger UI:
    title="SPARQL endpoint for RDFLib graph",
    description="A SPARQL endpoint to serve machine learning models, or any other logic implemented in Python. \n[Source code](https://github.com/vemonet/rdflib-endpoint)",
    version="0.1.0",
    public_url='https://your-endpoint-url/',
    # Example query displayed in YASGUI default tab
    example_query="""PREFIX myfunctions: <https://w3id.org/um/sparql-functions/>
SELECT ?concat ?concatLength WHERE {
    BIND("First" AS ?first)
    BIND(myfunctions:custom_concat(?first, "last") AS ?concat)
}""",
    # Additional example queries displayed in additional YASGUI tabs
    example_queries = {
    	"Bio2RDF query": {
        	"endpoint": "https://bio2rdf.org/sparql",
        	"query": """SELECT DISTINCT * WHERE {
    ?s a ?o .
} LIMIT 10""",
    	},
    	"Custom function": {
        	"query": """PREFIX myfunctions: <https://w3id.org/um/sparql-functions/>
SELECT ?concat ?concatLength WHERE {
    BIND("First" AS ?first)
    BIND(myfunctions:custom_concat(?first, "last") AS ?concat)
}""",
    	}
	}
)
```

Finally deploy this app using `uvicorn` (see below)

### đŸ›Ŗī¸ Deploy as a router to include in an existing API

Deploy your SPARQL endpoint as an `APIRouter` to include in an existing `FastAPI` API. The `SparqlRouter` constructor takes the same arguments as the `SparqlEndpoint`, apart from `enable_cors` which needs be enabled at the API level.

```python
from fastapi import FastAPI
from rdflib import ConjunctiveGraph
from rdflib_endpoint import SparqlRouter

g = ConjunctiveGraph()
sparql_router = SparqlRouter(
    graph=g,
    path="/",
    # Metadata used for the SPARQL service description and Swagger UI:
    title="SPARQL endpoint for RDFLib graph",
    description="A SPARQL endpoint to serve machine learning models, or any other logic implemented in Python. \n[Source code](https://github.com/vemonet/rdflib-endpoint)",
    version="0.1.0",
    public_url='https://your-endpoint-url/',
)

app = FastAPI()
app.include_router(sparql_router)
```

### 📝 Define custom SPARQL functions

This option makes it easier to define functions in your SPARQL endpoint, e.g. `BIND(myfunction:custom_concat("start", "end") AS ?concat)`. It can be used with the `SparqlEndpoint` and `SparqlRouter` classes.

Create a `app/main.py` file in your project folder with your custom SPARQL functions, and endpoint parameters:

````python
import rdflib
from rdflib import ConjunctiveGraph
from rdflib.plugins.sparql.evalutils import _eval
from rdflib_endpoint import SparqlEndpoint

def custom_concat(query_results, ctx, part, eval_part):
    """Concat 2 strings in the 2 senses and return the length as additional Length variable
    """
    # Retrieve the 2 input arguments
    argument1 = str(_eval(part.expr.expr[0], eval_part.forget(ctx, _except=part.expr._vars)))
    argument2 = str(_eval(part.expr.expr[1], eval_part.forget(ctx, _except=part.expr._vars)))
    evaluation = []
    scores = []
    # Prepare the 2 result string, 1 for eval, 1 for scores
    evaluation.append(argument1 + argument2)
    evaluation.append(argument2 + argument1)
    scores.append(len(argument1 + argument2))
    scores.append(len(argument2 + argument1))
    # Append the results for our custom function
    for i, result in enumerate(evaluation):
        query_results.append(eval_part.merge({
            part.var: rdflib.Literal(result),
            # With an additional custom var for the length
            rdflib.term.Variable(part.var + 'Length'): rdflib.Literal(scores[i])
        }))
    return query_results, ctx, part, eval_part

# Start the SPARQL endpoint based on a RDFLib Graph and register your custom functions
g = ConjunctiveGraph()
# Use either SparqlEndpoint or SparqlRouter, they take the same arguments
app = SparqlEndpoint(
    graph=g,
    path="/",
    # Register the functions:
    functions={
        'https://w3id.org/um/sparql-functions/custom_concat': custom_concat
    },
    cors_enabled=True,
    # Metadata used for the SPARQL service description and Swagger UI:
    title="SPARQL endpoint for RDFLib graph",
    description="A SPARQL endpoint to serve machine learning models, or any other logic implemented in Python. \n[Source code](https://github.com/vemonet/rdflib-endpoint)",
    version="0.1.0",
    public_url='https://your-endpoint-url/',
    # Example queries displayed in the Swagger UI to help users try your function
    example_query="""PREFIX myfunctions: <https://w3id.org/um/sparql-functions/>
SELECT ?concat ?concatLength WHERE {
    BIND("First" AS ?first)
    BIND(myfunctions:custom_concat(?first, "last") AS ?concat)
}"""
)
````

### ✒ī¸ Or directly define the custom evaluation

You can also directly provide the custom evaluation function, this will override the `functions`.

Refer to the [RDFLib documentation](https://rdflib.readthedocs.io/en/stable/_modules/examples/custom_eval.html) to define the custom evaluation function. Then provide it when instantiating the SPARQL endpoint:

```python
import rdflib
from rdflib.plugins.sparql.evaluate import evalBGP
from rdflib.namespace import FOAF, RDF, RDFS

def custom_eval(ctx, part):
    """Rewrite triple patterns to get super-classes"""
    if part.name == "BGP":
        # rewrite triples
        triples = []
        for t in part.triples:
            if t[1] == RDF.type:
                bnode = rdflib.BNode()
                triples.append((t[0], t[1], bnode))
                triples.append((bnode, RDFS.subClassOf, t[2]))
            else:
                triples.append(t)
        # delegate to normal evalBGP
        return evalBGP(ctx, triples)
    raise NotImplementedError()

app = SparqlEndpoint(
    graph=g,
    custom_eval=custom_eval
)
```

### đŸĻ„ Run the SPARQL endpoint

You can then run the SPARQL endpoint server from the folder where your script is defined with `uvicorn` on http://localhost:8000 (it is installed automatically when you install the `rdflib-endpoint` package)

```bash
uvicorn main:app --app-dir example/app --reload
```

> Checkout in the `example/README.md` for more details, such as deploying it with docker.

## 📂 Projects using rdflib-endpoint

Here are some projects using `rdflib-endpoint` to deploy custom SPARQL endpoints with python:

* [The Bioregistry](https://bioregistry.io/), an open source, community curated registry, meta-registry, and compact identifier resolver.
* [proycon/codemeta-server](https://github.com/proycon/codemeta-server), server for codemeta, in memory triple store, SPARQL endpoint and simple web-based visualisation for end-user

## 🛠ī¸ Contributing

To run the project in development and make a contribution checkout the [contributing page](https://github.com/vemonet/rdflib-endpoint/blob/main/CONTRIBUTING.md).

            

Raw data

            {
    "_id": null,
    "home_page": "",
    "name": "rdflib-endpoint",
    "maintainer": "",
    "docs_url": null,
    "requires_python": ">=3.8",
    "maintainer_email": "Vincent Emonet <vincent.emonet@gmail.com>",
    "keywords": "Python,RDF,RDFLib,SPARQL,endpoint",
    "author": "",
    "author_email": "Vincent Emonet <vincent.emonet@gmail.com>",
    "download_url": "https://files.pythonhosted.org/packages/7b/3a/fdba3782265d39340ff01e7fe79887b6d866ddfb53f6567bd231a51248a9/rdflib_endpoint-0.5.0.tar.gz",
    "platform": null,
    "description": "<div align=\"center\">\n\n# \ud83d\udcab SPARQL endpoint for RDFLib\n\n[![PyPI - Version](https://img.shields.io/pypi/v/rdflib-endpoint.svg?logo=pypi&label=PyPI&logoColor=silver)](https://pypi.org/project/rdflib-endpoint/)\n[![PyPI - Python Version](https://img.shields.io/pypi/pyversions/rdflib-endpoint.svg?logo=python&label=Python&logoColor=silver)](https://pypi.org/project/rdflib-endpoint/)\n\n[![Test package](https://github.com/vemonet/rdflib-endpoint/actions/workflows/test.yml/badge.svg)](https://github.com/vemonet/rdflib-endpoint/actions/workflows/test.yml)\n[![Publish package](https://github.com/vemonet/rdflib-endpoint/actions/workflows/release.yml/badge.svg)](https://github.com/vemonet/rdflib-endpoint/actions/workflows/release.yml)\n[![Coverage Status](https://coveralls.io/repos/github/vemonet/rdflib-endpoint/badge.svg?branch=main)](https://coveralls.io/github/vemonet/rdflib-endpoint?branch=main)\n\n[![license](https://img.shields.io/pypi/l/rdflib-endpoint.svg?color=%2334D058)](https://github.com/vemonet/rdflib-endpoint/blob/main/LICENSE.txt)\n[![code style - black](https://img.shields.io/badge/code%20style-black-000000.svg)](https://github.com/psf/black)\n[![types - Mypy](https://img.shields.io/badge/types-mypy-blue.svg)](https://github.com/python/mypy)\n\n</div>\n\n`rdflib-endpoint` is a SPARQL endpoint based on RDFLib to **easily serve RDF files locally**, machine learning models, or any other logic implemented in Python via **custom SPARQL functions**.\n\nIt aims to enable python developers to easily deploy functions that can be queried in a federated fashion using SPARQL. For example: using a python function to resolve labels for specific identifiers, or run a classifier given entities retrieved using a `SERVICE` query to another SPARQL endpoint.\n\n> Feel free to create an [issue](/issues), or send a pull request if you are facing issues or would like to see a feature implemented.\n\n## \u2139\ufe0f How it works\n\n`rdflib-endpoint` can be used directly from the terminal to quickly serve RDF files through a SPARQL endpoint automatically deployed locally.\n\nIt can also be used to define custom SPARQL functions: the user defines and registers custom SPARQL functions, and/or populate the RDFLib Graph using Python, then the endpoint is started using `uvicorn`/`gunicorn`.\n\nThe deployed SPARQL endpoint can be used as a `SERVICE` in a federated SPARQL query from regular triplestores SPARQL endpoints. Tested on OpenLink Virtuoso (Jena based) and Ontotext GraphDB (RDF4J based). The endpoint is CORS enabled by default to enable querying it from client JavaScript (can be turned off).\n\nBuilt with [RDFLib](https://github.com/RDFLib/rdflib) and [FastAPI](https://fastapi.tiangolo.com/).\n\n## \ud83d\udce6\ufe0f Installation\n\nThis package requires Python >=3.8, install it  from [PyPI](https://pypi.org/project/rdflib-endpoint/) with:\n\n```shell\npip install rdflib-endpoint\n```\n\nThe `uvicorn` and `gunicorn` dependencies are not included by default, if you want to install them use the optional dependency `web`:\n\n```bash\npip install \"rdflib-endpoint[web]\"\n```\n\nIf you want to use `rdlib-endpoint` as a CLI you can install with the optional dependency `cli`:\n\n```bash\npip install \"rdflib-endpoint[cli]\"\n```\n\nIf you want to use [oxigraph](https://github.com/oxigraph/oxigraph) as backend triplestore you can install with the optional dependency `oxigraph`:\n\n```bash\npip install \"rdflib-endpoint[oxigraph,cli]\"\n```\n\n> [!WARNING]\n> Oxigraph and `oxrdflib` do not support custom functions, so it can be only used to deploy graphs without custom functions.\n\n## \u2328\ufe0f Use the CLI\n\n`rdflib-endpoint` can be used from the command line interface to perform basic utility tasks, such as serving or converting RDF files locally.\n\nMake sure you installed `rdflib-endpoint` with the `cli` optional dependencies:\n\n```bash\npip install \"rdflib-endpoint[cli]\"\n```\n\n### \u26a1\ufe0f Quickly serve RDF files through a SPARQL endpoint\n\nUse `rdflib-endpoint` as a command line interface (CLI) in your terminal to quickly serve one or multiple RDF files as a SPARQL endpoint.\n\nYou can use wildcard and provide multiple files, for example to serve all turtle, JSON-LD and nquads files in the current folder you could run:\n\n```bash\nrdflib-endpoint serve *.ttl *.jsonld *.nq\n```\n\n> Then access the YASGUI SPARQL editor on http://localhost:8000\n\nIf you installed with the Oxigraph optional dependency you can use it as backend triplestore, it is faster and supports some functions that are not supported by the RDFLib query engine (such as `COALESCE()`):\n\n```bash\nrdflib-endpoint serve --store Oxigraph \"*.ttl\" \"*.jsonld\" \"*.nq\"\n```\n\n### \ud83d\udd04 Convert RDF files to another format\n\n`rdflib-endpoint` can also be used to quickly merge and convert files from multiple formats to a specific format:\n\n```bash\nrdflib-endpoint convert \"*.ttl\" \"*.jsonld\" \"*.nq\" --output \"merged.trig\"\n```\n\n## \u2728 Deploy your SPARQL endpoint\n\n`rdflib-endpoint` enables you to easily define and deploy SPARQL endpoints based on RDFLib Graph, ConjunctiveGraph, and Dataset. Additionally it provides helpers to defines custom functions in the endpoint.\n\nCheckout the [`example`](https://github.com/vemonet/rdflib-endpoint/tree/main/example) folder for a complete working app example to get started, including a docker deployment. A good way to create a new SPARQL endpoint is to copy this `example` folder, and start from it.\n\n### \ud83d\udea8 Deploy as a standalone API\n\nDeploy your SPARQL endpoint as a standalone API:\n\n```python\nfrom rdflib import ConjunctiveGraph\nfrom rdflib_endpoint import SparqlEndpoint\n\n# Start the SPARQL endpoint based on a RDFLib Graph and register your custom functions\ng = ConjunctiveGraph()\n# TODO: Add triples in your graph\n\n# Then use either SparqlEndpoint or SparqlRouter, they take the same arguments\napp = SparqlEndpoint(\n    graph=g,\n    path=\"/\",\n    cors_enabled=True,\n    # Metadata used for the SPARQL service description and Swagger UI:\n    title=\"SPARQL endpoint for RDFLib graph\",\n    description=\"A SPARQL endpoint to serve machine learning models, or any other logic implemented in Python. \\n[Source code](https://github.com/vemonet/rdflib-endpoint)\",\n    version=\"0.1.0\",\n    public_url='https://your-endpoint-url/',\n    # Example query displayed in YASGUI default tab\n    example_query=\"\"\"PREFIX myfunctions: <https://w3id.org/um/sparql-functions/>\nSELECT ?concat ?concatLength WHERE {\n    BIND(\"First\" AS ?first)\n    BIND(myfunctions:custom_concat(?first, \"last\") AS ?concat)\n}\"\"\",\n    # Additional example queries displayed in additional YASGUI tabs\n    example_queries = {\n    \t\"Bio2RDF query\": {\n        \t\"endpoint\": \"https://bio2rdf.org/sparql\",\n        \t\"query\": \"\"\"SELECT DISTINCT * WHERE {\n    ?s a ?o .\n} LIMIT 10\"\"\",\n    \t},\n    \t\"Custom function\": {\n        \t\"query\": \"\"\"PREFIX myfunctions: <https://w3id.org/um/sparql-functions/>\nSELECT ?concat ?concatLength WHERE {\n    BIND(\"First\" AS ?first)\n    BIND(myfunctions:custom_concat(?first, \"last\") AS ?concat)\n}\"\"\",\n    \t}\n\t}\n)\n```\n\nFinally deploy this app using `uvicorn` (see below)\n\n### \ud83d\udee3\ufe0f Deploy as a router to include in an existing API\n\nDeploy your SPARQL endpoint as an `APIRouter` to include in an existing `FastAPI` API. The `SparqlRouter` constructor takes the same arguments as the `SparqlEndpoint`, apart from `enable_cors` which needs be enabled at the API level.\n\n```python\nfrom fastapi import FastAPI\nfrom rdflib import ConjunctiveGraph\nfrom rdflib_endpoint import SparqlRouter\n\ng = ConjunctiveGraph()\nsparql_router = SparqlRouter(\n    graph=g,\n    path=\"/\",\n    # Metadata used for the SPARQL service description and Swagger UI:\n    title=\"SPARQL endpoint for RDFLib graph\",\n    description=\"A SPARQL endpoint to serve machine learning models, or any other logic implemented in Python. \\n[Source code](https://github.com/vemonet/rdflib-endpoint)\",\n    version=\"0.1.0\",\n    public_url='https://your-endpoint-url/',\n)\n\napp = FastAPI()\napp.include_router(sparql_router)\n```\n\n### \ud83d\udcdd Define custom SPARQL functions\n\nThis option makes it easier to define functions in your SPARQL endpoint, e.g. `BIND(myfunction:custom_concat(\"start\", \"end\") AS ?concat)`. It can be used with the `SparqlEndpoint` and `SparqlRouter` classes.\n\nCreate a `app/main.py` file in your project folder with your custom SPARQL functions, and endpoint parameters:\n\n````python\nimport rdflib\nfrom rdflib import ConjunctiveGraph\nfrom rdflib.plugins.sparql.evalutils import _eval\nfrom rdflib_endpoint import SparqlEndpoint\n\ndef custom_concat(query_results, ctx, part, eval_part):\n    \"\"\"Concat 2 strings in the 2 senses and return the length as additional Length variable\n    \"\"\"\n    # Retrieve the 2 input arguments\n    argument1 = str(_eval(part.expr.expr[0], eval_part.forget(ctx, _except=part.expr._vars)))\n    argument2 = str(_eval(part.expr.expr[1], eval_part.forget(ctx, _except=part.expr._vars)))\n    evaluation = []\n    scores = []\n    # Prepare the 2 result string, 1 for eval, 1 for scores\n    evaluation.append(argument1 + argument2)\n    evaluation.append(argument2 + argument1)\n    scores.append(len(argument1 + argument2))\n    scores.append(len(argument2 + argument1))\n    # Append the results for our custom function\n    for i, result in enumerate(evaluation):\n        query_results.append(eval_part.merge({\n            part.var: rdflib.Literal(result),\n            # With an additional custom var for the length\n            rdflib.term.Variable(part.var + 'Length'): rdflib.Literal(scores[i])\n        }))\n    return query_results, ctx, part, eval_part\n\n# Start the SPARQL endpoint based on a RDFLib Graph and register your custom functions\ng = ConjunctiveGraph()\n# Use either SparqlEndpoint or SparqlRouter, they take the same arguments\napp = SparqlEndpoint(\n    graph=g,\n    path=\"/\",\n    # Register the functions:\n    functions={\n        'https://w3id.org/um/sparql-functions/custom_concat': custom_concat\n    },\n    cors_enabled=True,\n    # Metadata used for the SPARQL service description and Swagger UI:\n    title=\"SPARQL endpoint for RDFLib graph\",\n    description=\"A SPARQL endpoint to serve machine learning models, or any other logic implemented in Python. \\n[Source code](https://github.com/vemonet/rdflib-endpoint)\",\n    version=\"0.1.0\",\n    public_url='https://your-endpoint-url/',\n    # Example queries displayed in the Swagger UI to help users try your function\n    example_query=\"\"\"PREFIX myfunctions: <https://w3id.org/um/sparql-functions/>\nSELECT ?concat ?concatLength WHERE {\n    BIND(\"First\" AS ?first)\n    BIND(myfunctions:custom_concat(?first, \"last\") AS ?concat)\n}\"\"\"\n)\n````\n\n### \u2712\ufe0f Or directly define the custom evaluation\n\nYou can also directly provide the custom evaluation function, this will override the `functions`.\n\nRefer to the [RDFLib documentation](https://rdflib.readthedocs.io/en/stable/_modules/examples/custom_eval.html) to define the custom evaluation function. Then provide it when instantiating the SPARQL endpoint:\n\n```python\nimport rdflib\nfrom rdflib.plugins.sparql.evaluate import evalBGP\nfrom rdflib.namespace import FOAF, RDF, RDFS\n\ndef custom_eval(ctx, part):\n    \"\"\"Rewrite triple patterns to get super-classes\"\"\"\n    if part.name == \"BGP\":\n        # rewrite triples\n        triples = []\n        for t in part.triples:\n            if t[1] == RDF.type:\n                bnode = rdflib.BNode()\n                triples.append((t[0], t[1], bnode))\n                triples.append((bnode, RDFS.subClassOf, t[2]))\n            else:\n                triples.append(t)\n        # delegate to normal evalBGP\n        return evalBGP(ctx, triples)\n    raise NotImplementedError()\n\napp = SparqlEndpoint(\n    graph=g,\n    custom_eval=custom_eval\n)\n```\n\n### \ud83e\udd84 Run the SPARQL endpoint\n\nYou can then run the SPARQL endpoint server from the folder where your script is defined with `uvicorn` on http://localhost:8000 (it is installed automatically when you install the `rdflib-endpoint` package)\n\n```bash\nuvicorn main:app --app-dir example/app --reload\n```\n\n> Checkout in the `example/README.md` for more details, such as deploying it with docker.\n\n## \ud83d\udcc2 Projects using rdflib-endpoint\n\nHere are some projects using `rdflib-endpoint` to deploy custom SPARQL endpoints with python:\n\n* [The Bioregistry](https://bioregistry.io/), an open source, community curated registry, meta-registry, and compact identifier resolver.\n* [proycon/codemeta-server](https://github.com/proycon/codemeta-server), server for codemeta, in memory triple store, SPARQL endpoint and simple web-based visualisation for end-user\n\n## \ud83d\udee0\ufe0f Contributing\n\nTo run the project in development and make a contribution checkout the [contributing page](https://github.com/vemonet/rdflib-endpoint/blob/main/CONTRIBUTING.md).\n",
    "bugtrack_url": null,
    "license": "MIT License  Copyright (c) 2022-present Vincent Emonet <vincent.emonet@gmail.com>  Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:  The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.  THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.",
    "summary": "A package to deploy SPARQL endpoint to serve local RDF files, machine learning models, or any other logic implemented in Python, using RDFLib and FastAPI.",
    "version": "0.5.0",
    "project_urls": {
        "Documentation": "https://github.com/vemonet/rdflib-endpoint",
        "History": "https://github.com/vemonet/rdflib-endpoint/releases",
        "Homepage": "https://github.com/vemonet/rdflib-endpoint",
        "Source": "https://github.com/vemonet/rdflib-endpoint",
        "Tracker": "https://github.com/vemonet/rdflib-endpoint/issues"
    },
    "split_keywords": [
        "python",
        "rdf",
        "rdflib",
        "sparql",
        "endpoint"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "d260d44a4172e9c66d225fe2b06766bad74792bc38b30eef79c222bb6310b1fe",
                "md5": "db71e5a0a68cfe71243cca92de1dadad",
                "sha256": "5034a4b07f497d7907748bb81861ea46b85058f134119e3244d504e0b603489e"
            },
            "downloads": -1,
            "filename": "rdflib_endpoint-0.5.0-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "db71e5a0a68cfe71243cca92de1dadad",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.8",
            "size": 16649,
            "upload_time": "2023-12-08T20:25:47",
            "upload_time_iso_8601": "2023-12-08T20:25:47.980959Z",
            "url": "https://files.pythonhosted.org/packages/d2/60/d44a4172e9c66d225fe2b06766bad74792bc38b30eef79c222bb6310b1fe/rdflib_endpoint-0.5.0-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "7b3afdba3782265d39340ff01e7fe79887b6d866ddfb53f6567bd231a51248a9",
                "md5": "2b3fd93c01574fbdd81e1585937d7992",
                "sha256": "79a99f0f92808990c62fe17564f546ac835344399314e8bb05677226464ab97c"
            },
            "downloads": -1,
            "filename": "rdflib_endpoint-0.5.0.tar.gz",
            "has_sig": false,
            "md5_digest": "2b3fd93c01574fbdd81e1585937d7992",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.8",
            "size": 24616,
            "upload_time": "2023-12-08T20:25:49",
            "upload_time_iso_8601": "2023-12-08T20:25:49.263832Z",
            "url": "https://files.pythonhosted.org/packages/7b/3a/fdba3782265d39340ff01e7fe79887b6d866ddfb53f6567bd231a51248a9/rdflib_endpoint-0.5.0.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2023-12-08 20:25:49",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "vemonet",
    "github_project": "rdflib-endpoint",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": true,
    "lcname": "rdflib-endpoint"
}
        
Elapsed time: 0.16174s