pydgraph


Namepydgraph JSON
Version 24.3.0 PyPI version JSON
download
home_pageNone
SummaryOfficial Dgraph client implementation for Python
upload_time2025-08-05 00:50:19
maintainerNone
docs_urlNone
authorNone
requires_python>=3.7
licenseApache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS
keywords
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # pydgraph

This is the official Dgraph database client implementation for Python (Python >= v3.7), using
[gRPC][grpc].

[grpc]: https://grpc.io/

This client follows the [Dgraph Go client][goclient] closely.

[goclient]: https://github.com/dgraph-io/dgo

Before using this client, we highly recommend that you read the the product documentation at
[dgraph.io/docs].

[dgraph.io/docs]: https://dgraph.io/docs

## Table of contents

- [pydgraph](#pydgraph)
  - [Table of contents](#table-of-contents)
  - [Install](#install)
  - [Supported Versions](#supported-versions)
  - [Quickstart](#quickstart)
  - [Using a client](#using-a-client)
    - [Creating a Client](#creating-a-client)
    - [Login into a Namespace](#login-into-a-namespace)
    - [Connecting To Dgraph Cloud](#connecting-to-dgraph-cloud)
    - [Altering the Database](#altering-the-database)
    - [Creating a Transaction](#creating-a-transaction)
    - [Running a Mutation](#running-a-mutation)
    - [Running a Query](#running-a-query)
    - [Query with RDF response](#query-with-rdf-response)
    - [Running an Upsert: Query + Mutation](#running-an-upsert-query--mutation)
    - [Running a Conditional Upsert](#running-a-conditional-upsert)
    - [Committing a Transaction](#committing-a-transaction)
    - [Cleaning Up Resources](#cleaning-up-resources)
    - [Setting Metadata Headers](#setting-metadata-headers)
    - [Setting a timeout](#setting-a-timeout)
    - [Async methods](#async-methods)
  - [Examples](#examples)
  - [Development](#development)
    - [Setting up environment](#setting-up-environment)
    - [Build from source](#build-from-source)
    - [Running tests](#running-tests)

## Install

Install using pip:

```sh
pip install pydgraph
```

## Supported Versions

Depending on the version of Dgraph that you are connecting to, you will have to use a different
version of this client.

| Dgraph version | pydgraph version |
| :------------: | :--------------: |
|    21.03.x     |    _21.03.x_     |
|    23.0.x+     |     _23.0.x_     |

## Quickstart

Build and run the [simple project][simple] in the `examples` folder, which contains an end-to-end
example of using the Dgraph python client. For additional details, follow the instructions in the
project's [README](./examples/simple/README.md).

[simple]: ./examples/simple

## Using a client

### Creating a Client

You can initialize a `DgraphClient` object by passing it a list of `DgraphClientStub` clients as
variadic arguments. Connecting to multiple Dgraph servers in the same cluster allows for better
distribution of workload.

The following code snippet shows just one connection.

```python3
import pydgraph

client_stub = pydgraph.DgraphClientStub('localhost:9080')
client = pydgraph.DgraphClient(client_stub)
```

### Using Dgraph Connection Strings

The pydgraph package supports connecting to a Dgraph cluster using connection strings. Dgraph
connections strings take the form `dgraph://{username:password@}host:port?args`.

`username` and `password` are optional. If username is provided, a password must also be present. If
supplied, these credentials are used to log into a Dgraph cluster through the ACL mechanism.

Valid connection string args:

| Arg         | Value                           | Description                                                                                                                                                   |
| ----------- | ------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| apikey      | \<key\>                         | a Dgraph Cloud API Key                                                                                                                                        |
| bearertoken | \<token\>                       | an access token                                                                                                                                               |
| sslmode     | disable \| require \| verify-ca | TLS option, the default is `disable`. If `verify-ca` is set, the TLS certificate configured in the Dgraph cluster must be from a valid certificate authority. |

Note the `sslmode=require` pair is not supported and will throw an Exception if used. Python grpc
does not support traffic over TLS that does not fully verify the certificate and domain. Developers
should use the existing stub/client initialization steps for self-signed certs as demonstrated in
/examples/tls/tls_example.py

Some example connection strings:

| Value                                                                                                        | Explanation                                                                         |
| ------------------------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------- |
| dgraph://localhost:9080                                                                                      | Connect to localhost, no ACL, no TLS                                                |
| dgraph://sally:supersecret@dg.example.com:443?sslmode=verify-ca                                              | Connect to remote server, use ACL and require TLS and a valid certificate from a CA |
| dgraph://foo-bar.grpc.us-west-2.aws.cloud.dgraph.io:443?sslmode=verify-ca&apikey=\<your-api-connection-key\> | Connect to a Dgraph Cloud cluster                                                   |
| dgraph://foo-bar.grpc.hypermode.com:443?sslmode=verify-ca&bearertoken=\<some access token\>                  | Connect to a Dgraph cluster protected by a secure gateway                           |

Using the `Open` function with a connection string:

```go
// open a connection to an ACL-enabled, non-TLS cluster and login as groot
client = pydgraph.open("dgraph://groot:password@localhost:8090")

// Use the client
...

client.close()
```

### Login into a Namespace

If your server has Access Control Lists enabled (Dgraph v1.1 or above), the client must be logged in
for accessing data. If you didn't use the `open` function with credentials, use the `login`
endpoint.

Calling `login` will obtain and remember the access and refresh JWT tokens. All subsequent
operations via the logged in client will send along the stored access token.

```python3
client.login("groot", "password")
```

If your server additionally has namespaces (Dgraph v21.03 or above), use the `login_into_namespace`
API.

```python3
client.login_into_namespace("groot", "password", "123")
```

### Connecting To Dgraph Cloud

If you want to connect to Dgraph running on [Dgraph Cloud](https://cloud.dgraph.io) instance, then
get the gRPC endpoint of your cluster that you can find in the
[Settings section](https://cloud.dgraph.io/_/settings) of Dgraph Cloud console and obtain a Client
or Admin API key (created in the [API key tab](https://cloud.dgraph.io/_/settings?tab=api-keys) of
the Setting section). Create the `client_stub` using the gRPC endpoint and the API key:

```python3
client_stub = pydgraph.DgraphClientStub.from_cloud(
    "https://morning-glade.grpc.us-east-1.aws.cloud.dgraph.io:443", "<api-key>")
client = pydgraph.DgraphClient(client_stub)
```

Alternatively, you can simply use a Dgraph connection string with the `open` function. For example:

```python
conn_str = "dgraph://foo-bar.grpc.us-west-2.aws.cloud.dgraph.io:443?sslmode=verify-ca&apikey=<your-api-connection-key>"
client = pydgraph.open(conn_str)

# some time later...
client.close()
```

The `DgraphClientStub.from_slash_endpoint()` method has been removed v23.0. Please use
`DgraphClientStub.from_cloud()` instead.

### Altering the Database

#### Set the Dgraph types schema

To set the Dgraph types schema (aka DQL schema), create an `Operation` object, set the schema and
pass it to `DgraphClient#alter(Operation)` method.

```python3
schema = 'name: string @index(exact) .'
op = pydgraph.Operation(schema=schema)
client.alter(op)
```

Indexes can be computed in the background. You can set the `run_in_background` field of
`pydgraph.Operation` to `True` before passing it to the `Alter` function. You can find more details
[here](https://docs.dgraph.io/master/query-language/#indexes-in-background).

**Note** To deploy the GraphQL schema in python you have to use GraphQL client such as
[python-graphql-client](https://github.com/prodigyeducation/python-graphql-client) to invoke the
GraphQL admin mutation
[updateGQLSchema](https://dgraph.io/docs/graphql/admin/#using-updategqlschema-to-add-or-modify-a-schema)

```python3
schema = 'name: string @index(exact) .'
op = pydgraph.Operation(schema=schema, run_in_background=True)
client.alter(op)
```

#### Drop data

To drop all data and schema:

```python3
# Drop all data including schema from the Dgraph instance. This is a useful
# for small examples such as this since it puts Dgraph into a clean state.
op = pydgraph.Operation(drop_all=True)
client.alter(op)
```

**Note** If the Dgraph cluster contains a GraphQL Schema, it will also be deleted by this operation.

To drop all data and preserve the DQL schema:

```python3
# Drop all data from the Dgraph instance. Keep the DQL Schema.
op = pydgraph.Operation(drop_op="DATA")
client.alter(op)
```

To drop a predicate:

```python3
# Drop the data associated to a predicate and the predicate from the schema.
op = pydgraph.Operation(drop_op="ATTR", drop_value="<predicate_name>")
client.alter(op)
```

the same result is obtained using

```python3
# Drop the data associated to a predicate and the predicate from the schema.
op = pydgraph.Operation(drop_attr="<predicate_name>")
client.alter(op)
```

To drop a type definition from DQL Schema:

```python3
# Drop a type from the schema.
op = pydgraph.Operation(drop_op="TYPE", drop_value="<predicate_name>")
client.alter(op)
```

**Note** `drop_op="TYPE"` just removes a type definition from the DQL schema. No data is removed
from the cluster. The operation does not drop the predicates associated with the type.

### Creating a Transaction

To create a transaction, call the `DgraphClient#txn()` method, which returns a new `Txn` object.
This operation incurs no network overhead.

It is good practice to call `Txn#discard()` in a `finally` block after running the transaction.
Calling `Txn#discard()` after `Txn#commit()` is a no-op and you can call `Txn#discard()` multiple
times with no additional side-effects.

```python3
txn = client.txn()
try:
  # Do something here
  # ...
finally:
  txn.discard()
  # ...
```

To create a read-only transaction, call `DgraphClient#txn(read_only=True)`. Read-only transactions
are ideal for transactions which only involve queries. Mutations and commits are not allowed.

```python3
txn = client.txn(read_only=True)
try:
  # Do some queries here
  # ...
finally:
  txn.discard()
  # ...
```

To create a read-only transaction that executes best-effort queries, call
`DgraphClient#txn(read_only=True, best_effort=True)`. Best-effort queries are faster than normal
queries because they bypass the normal consensus protocol. For this same reason, best-effort queries
cannot guarantee to return the latest data. Best-effort queries are only supported by read-only
transactions.

### Running a Mutation

`Txn#mutate(mu=Mutation)` runs a mutation. It takes in a `Mutation` object, which provides two main
ways to set data: JSON and RDF N-Quad. You can choose whichever way is convenient.

`Txn#mutate()` provides convenience keyword arguments `set_obj` and `del_obj` for setting JSON
values and `set_nquads` and `del_nquads` for setting N-Quad values. See examples below for usage.

We define a person object to represent a person and use it in a transaction.

```python3
# Create data.
p = { 'name': 'Alice' }

# Run mutation.
txn.mutate(set_obj=p)

# If you want to use a mutation object, use this instead:
# mu = pydgraph.Mutation(set_json=json.dumps(p).encode('utf8'))
# txn.mutate(mu)

# If you want to use N-Quads, use this instead:
# txn.mutate(set_nquads='_:alice <name> "Alice" .')
```

```python3
# Delete data

query = """query all($a: string)
 {
   all(func: eq(name, $a))
    {
      uid
    }
  }"""
variables = {'$a': 'Bob'}

res = txn.query(query, variables=variables)
ppl = json.loads(res.json)

# For a mutation to delete a node, use this:
txn.mutate(del_obj=person)
```

For a complete example with multiple fields and relationships, look at the [simple project][simple]
in the `examples` folder.

Sometimes, you only want to commit a mutation, without querying anything further. In such cases, you
can set the keyword argument `commit_now=True` to indicate that the mutation must be immediately
committed.

A mutation can be executed using `txn.do_request` as well.

```python3
mutation = txn.create_mutation(set_nquads='_:alice <name> "Alice" .')
request = txn.create_request(mutations=[mutation], commit_now=True)
txn.do_request(request)
```

### Running a Query

You can run a query by calling `Txn#query(string)`. You will need to pass in a
[DQL](https://dgraph.io/docs/query-language/) query string. If you want to pass an additional
dictionary of any variables that you might want to set in the query, call
`Txn#query(string, variables=d)` with the variables dictionary `d`.

The query response contains the `json` field, which returns the JSON response. Let’s run a query
with a variable `$a`, deserialize the result from JSON and print it out:

```python3
# Run query.
query = """query all($a: string) {
  all(func: eq(name, $a))
  {
    name
  }
}"""
variables = {'$a': 'Alice'}

res = txn.query(query, variables=variables)

# If not doing a mutation in the same transaction, simply use:
# res = client.txn(read_only=True).query(query, variables=variables)

ppl = json.loads(res.json)

# Print results.
print('Number of people named "Alice": {}'.format(len(ppl['all'])))
for person in ppl['all']:
  print(person)
```

This should print:

```console
Number of people named "Alice": 1
Alice
```

You can also use `txn.do_request` function to run the query.

```python3
request = txn.create_request(query=query)
txn.do_request(request)
```

### Query with RDF response

You can get query result as a RDF response by calling `Txn#query(string)` with `resp_format` set to
`RDF`. The response would contain a `rdf` field, which has the RDF encoded result.

**Note:** If you are querying only for `uid` values, use a JSON format response.

```python3
res = txn.query(query, variables=variables, resp_format="RDF")
print(res.rdf)
```

### Running an Upsert: Query + Mutation

The `txn.do_request` function allows you to use upsert blocks. An upsert block contains one query
block and one or more mutation blocks, so it lets you perform queries and mutations in a single
request. Variables defined in the query block can be used in the mutation blocks using the `uid` and
`val` functions implemented by DQL.

To learn more about upsert blocks, see the
[Upsert Block documentation](https://dgraph.io/docs/mutations/upsert-block/).

```python3
query = """{
  u as var(func: eq(name, "Alice"))
}"""

nquad = """
  uid(u) <name> "Alice" .
  uid(u) <age> "25" .
"""

mutation = txn.create_mutation(set_nquads=nquad)
request = txn.create_request(query=query, mutations=[mutation], commit_now=True)
txn.do_request(request)
```

### Running a Conditional Upsert

The upsert block also allows specifying a conditional mutation block using an `@if` directive. The
mutation is executed only when the specified condition is true. If the condition is false, the
mutation is silently ignored.

See more about Conditional Upserts [here](https://docs.dgraph.io/mutations/#conditional-upsert).

```python3
query = """
  {
    user as var(func: eq(email, "wrong_email@dgraph.io"))
  }
"""

cond = "@if(eq(len(user), 1))"
nquads = """
  uid(user) <email> "correct_email@dgraph.io" .
"""

mutation = txn.create_mutation(cond=cond, set_nquads=nquads)
request = txn.create_request(mutations=[mutation], query=query, commit_now=True)
txn.do_request(request)
```

### Committing a Transaction

A transaction can be committed using the `Txn#commit()` method. If your transaction consist solely
of `Txn#query` or `Txn#queryWithVars` calls, and no calls to `Txn#mutate`, then calling
`Txn#commit()` is not necessary.

An error is raised if another transaction(s) modify the same data concurrently that was modified in
the current transaction. It is up to the user to retry transactions when they fail.

```python3
txn = client.txn()
try:
  # ...
  # Perform any number of queries and mutations
  # ...
  # and finally...
  txn.commit()
except pydgraph.AbortedError:
  # Retry or handle exception.
finally:
  # Clean up. Calling this after txn.commit() is a no-op
  # and hence safe.
  txn.discard()
```

### Cleaning Up Resources

To clean up resources, you have to call `DgraphClientStub#close()` individually for all the
instances of `DgraphClientStub`.

```python3
SERVER_ADDR1 = "localhost:9080"
SERVER_ADDR2 = "localhost:9080"

# Create instances of DgraphClientStub.
stub1 = pydgraph.DgraphClientStub(SERVER_ADDR1)
stub2 = pydgraph.DgraphClientStub(SERVER_ADDR2)

# Create an instance of DgraphClient.
client = pydgraph.DgraphClient(stub1, stub2)

# Use client
...

# Clean up resources by closing all client stubs.
stub1.close()
stub2.close()
```

### Setting Metadata Headers

Metadata headers such as authentication tokens can be set through the metadata of gRPC methods.
Below is an example of how to set a header named "auth-token".

```python3
# The following piece of code shows how one can set metadata with
# auth-token, to allow Alter operation, if the server requires it.
# metadata is a list of arbitrary key-value pairs.
metadata = [("auth-token", "the-auth-token-value")]
dg.alter(op, metadata=metadata)
```

### Setting a timeout

A timeout value representing the number of seconds can be passed to the `login`, `alter`, `query`,
and `mutate` methods using the `timeout` keyword argument.

For example, the following alters the schema with a timeout of ten seconds:
`dg.alter(op, timeout=10)`

### Async methods

The `alter` method in the client has an asynchronous version called `async_alter`. The async methods
return a future. You can directly call the `result` method on the future. However. The DgraphClient
class provides a static method `handle_alter_future` to handle any possible exception.

```python3
alter_future = self.client.async_alter(pydgraph.Operation(schema="name: string @index(term) ."))
response = pydgraph.DgraphClient.handle_alter_future(alter_future)
```

The `query` and `mutate` methods int the `Txn` class also have async versions called `async_query`
and `async_mutation` respectively. These functions work just like `async_alter`.

You can use the `handle_query_future` and `handle_mutate_future` static methods in the `Txn` class
to retrieve the result. A short example is given below:

```python3
txn = client.txn()
query = "query body here"
future = txn.async_query()
response = pydgraph.Txn.handle_query_future(future)
```

Keep in mind that due to the nature of async calls, the async functions cannot retry the request if
the login is invalid. You will have to check for this error and retry the login (with the function
`retry_login` in both the `Txn` and `Client` classes). A short example is given below:

```python3
client = DgraphClient(client_stubs) # client_stubs is a list of gRPC stubs.
alter_future = client.async_alter()
try:
    response = alter_future.result()
except Exception as e:
  # You can use this function in the util package to check for JWT
    # expired errors.
    if pydgraph.util.is_jwt_expired(e):
        # retry your request here.
```

## Examples

[tls]: ./examples/tls
[parse_datetime]: ./examples/parse_datetime

- [simple][]: Quickstart example of using pydgraph.
- [tls][]: Quickstart example that uses TLS.
- [parse_datetime]: Demonstration of converting Dgraph's DateTime strings to native python datetime.

## Development

### Setting up environment

There are many ways to set up your local Python environment. We suggest some sane defaults here.

- Use [pyenv](https://github.com/pyenv/pyenv) to manage your Python installations.
- Most recent versions of Python should work, but the version of Python officially supported is
  located in `.python-version`
- Create a Python virtual environment using `python -m venv .venv`
- Activate virtual environment via `source .venv/bin/activate`

### Build from source

To build and install pydgraph locally, run

```sh
pip install -e ".[dev]"
```

#### Regenerating protobufs

If you have made changes to the `pydgraph/proto/api.proto` file, you need need to regenerate the
source files generated by Protocol Buffer tools. To do that, install the
[grpcio-tools][grpcio-tools] library and then run the following command:

[grpcio-tools]: https://pypi.python.org/pypi/grpcio-tools

```sh
python scripts/protogen.py
```

**Important**: This project uses grpcio-tools 1.65.x to ensure compatibility with the minimum
supported grpcio version (1.65.0). This version generates code that issues warnings (not errors) for
users with older grpcio versions, providing a graceful upgrade path. It also uses protobuf 5.x which
eliminates Python 3.12+ deprecation warnings. The dev dependencies in `pyproject.toml` are pinned to
the correct version (grpcio-tools 1.65.x)

If you are using python version 3.13 or higher, an error will be raised if you try to run
`scripts/protogen.py`. This is to prevent generating protobufs that are incompatible with older
grpcio-tools versions.

#### grpcio 1.65.0 is the minimum version

Older grpcio versions have practical limitations:

- **Compilation failures**: grpcio versions older than ~1.60.0 fail to compile from source on modern
  systems (macOS with recent Xcode, newer Linux distributions) due to C++ compiler compatibility
  issues and outdated build configurations.
- **No pre-built wheels**: PyPI doesn't provide pre-built wheels for very old grpcio versions on
  modern Python versions (3.11+), forcing compilation from source.
- **Build tool incompatibility**: The build process for older grpcio versions uses deprecated
  compiler flags and build patterns that modern toolchains reject.

### Running tests

To run the tests in your local machine, run:

```bash
bash scripts/local-test.sh
```

You can run a specific test suite:

```bash
bash scripts/local-test.sh -v tests/test_connect.py::TestOpen
```

or an individual test:

```bash
bash scripts/local-test.sh -v tests/test_connect.py::TestOpen::test_connection_with_auth
```

The test script requires that `docker` and `docker compose` are installed on your machine.

The script will take care of bringing up a Dgraph cluster and bringing it down after the tests are
executed. The script connects to randomly selected ports for HTTP and gRPC requests to prevent
interference with clusters running on the default port. Docker and docker-compose need to be
installed before running the script. Refer to the official
[Docker documentation](https://docs.docker.com/) for instructions on how to install those packages.

            

Raw data

            {
    "_id": null,
    "home_page": null,
    "name": "pydgraph",
    "maintainer": null,
    "docs_url": null,
    "requires_python": ">=3.7",
    "maintainer_email": null,
    "keywords": null,
    "author": null,
    "author_email": "\"Hypermode Inc.\" <hello@hypermode.com>",
    "download_url": "https://files.pythonhosted.org/packages/99/3f/cc4236257e616fa3394c53f75650a3e7145cc95472f6d811604e3a662411/pydgraph-24.3.0.tar.gz",
    "platform": null,
    "description": "# pydgraph\n\nThis is the official Dgraph database client implementation for Python (Python >= v3.7), using\n[gRPC][grpc].\n\n[grpc]: https://grpc.io/\n\nThis client follows the [Dgraph Go client][goclient] closely.\n\n[goclient]: https://github.com/dgraph-io/dgo\n\nBefore using this client, we highly recommend that you read the the product documentation at\n[dgraph.io/docs].\n\n[dgraph.io/docs]: https://dgraph.io/docs\n\n## Table of contents\n\n- [pydgraph](#pydgraph)\n  - [Table of contents](#table-of-contents)\n  - [Install](#install)\n  - [Supported Versions](#supported-versions)\n  - [Quickstart](#quickstart)\n  - [Using a client](#using-a-client)\n    - [Creating a Client](#creating-a-client)\n    - [Login into a Namespace](#login-into-a-namespace)\n    - [Connecting To Dgraph Cloud](#connecting-to-dgraph-cloud)\n    - [Altering the Database](#altering-the-database)\n    - [Creating a Transaction](#creating-a-transaction)\n    - [Running a Mutation](#running-a-mutation)\n    - [Running a Query](#running-a-query)\n    - [Query with RDF response](#query-with-rdf-response)\n    - [Running an Upsert: Query + Mutation](#running-an-upsert-query--mutation)\n    - [Running a Conditional Upsert](#running-a-conditional-upsert)\n    - [Committing a Transaction](#committing-a-transaction)\n    - [Cleaning Up Resources](#cleaning-up-resources)\n    - [Setting Metadata Headers](#setting-metadata-headers)\n    - [Setting a timeout](#setting-a-timeout)\n    - [Async methods](#async-methods)\n  - [Examples](#examples)\n  - [Development](#development)\n    - [Setting up environment](#setting-up-environment)\n    - [Build from source](#build-from-source)\n    - [Running tests](#running-tests)\n\n## Install\n\nInstall using pip:\n\n```sh\npip install pydgraph\n```\n\n## Supported Versions\n\nDepending on the version of Dgraph that you are connecting to, you will have to use a different\nversion of this client.\n\n| Dgraph version | pydgraph version |\n| :------------: | :--------------: |\n|    21.03.x     |    _21.03.x_     |\n|    23.0.x+     |     _23.0.x_     |\n\n## Quickstart\n\nBuild and run the [simple project][simple] in the `examples` folder, which contains an end-to-end\nexample of using the Dgraph python client. For additional details, follow the instructions in the\nproject's [README](./examples/simple/README.md).\n\n[simple]: ./examples/simple\n\n## Using a client\n\n### Creating a Client\n\nYou can initialize a `DgraphClient` object by passing it a list of `DgraphClientStub` clients as\nvariadic arguments. Connecting to multiple Dgraph servers in the same cluster allows for better\ndistribution of workload.\n\nThe following code snippet shows just one connection.\n\n```python3\nimport pydgraph\n\nclient_stub = pydgraph.DgraphClientStub('localhost:9080')\nclient = pydgraph.DgraphClient(client_stub)\n```\n\n### Using Dgraph Connection Strings\n\nThe pydgraph package supports connecting to a Dgraph cluster using connection strings. Dgraph\nconnections strings take the form `dgraph://{username:password@}host:port?args`.\n\n`username` and `password` are optional. If username is provided, a password must also be present. If\nsupplied, these credentials are used to log into a Dgraph cluster through the ACL mechanism.\n\nValid connection string args:\n\n| Arg         | Value                           | Description                                                                                                                                                   |\n| ----------- | ------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| apikey      | \\<key\\>                         | a Dgraph Cloud API Key                                                                                                                                        |\n| bearertoken | \\<token\\>                       | an access token                                                                                                                                               |\n| sslmode     | disable \\| require \\| verify-ca | TLS option, the default is `disable`. If `verify-ca` is set, the TLS certificate configured in the Dgraph cluster must be from a valid certificate authority. |\n\nNote the `sslmode=require` pair is not supported and will throw an Exception if used. Python grpc\ndoes not support traffic over TLS that does not fully verify the certificate and domain. Developers\nshould use the existing stub/client initialization steps for self-signed certs as demonstrated in\n/examples/tls/tls_example.py\n\nSome example connection strings:\n\n| Value                                                                                                        | Explanation                                                                         |\n| ------------------------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------- |\n| dgraph://localhost:9080                                                                                      | Connect to localhost, no ACL, no TLS                                                |\n| dgraph://sally:supersecret@dg.example.com:443?sslmode=verify-ca                                              | Connect to remote server, use ACL and require TLS and a valid certificate from a CA |\n| dgraph://foo-bar.grpc.us-west-2.aws.cloud.dgraph.io:443?sslmode=verify-ca&apikey=\\<your-api-connection-key\\> | Connect to a Dgraph Cloud cluster                                                   |\n| dgraph://foo-bar.grpc.hypermode.com:443?sslmode=verify-ca&bearertoken=\\<some access token\\>                  | Connect to a Dgraph cluster protected by a secure gateway                           |\n\nUsing the `Open` function with a connection string:\n\n```go\n// open a connection to an ACL-enabled, non-TLS cluster and login as groot\nclient = pydgraph.open(\"dgraph://groot:password@localhost:8090\")\n\n// Use the client\n...\n\nclient.close()\n```\n\n### Login into a Namespace\n\nIf your server has Access Control Lists enabled (Dgraph v1.1 or above), the client must be logged in\nfor accessing data. If you didn't use the `open` function with credentials, use the `login`\nendpoint.\n\nCalling `login` will obtain and remember the access and refresh JWT tokens. All subsequent\noperations via the logged in client will send along the stored access token.\n\n```python3\nclient.login(\"groot\", \"password\")\n```\n\nIf your server additionally has namespaces (Dgraph v21.03 or above), use the `login_into_namespace`\nAPI.\n\n```python3\nclient.login_into_namespace(\"groot\", \"password\", \"123\")\n```\n\n### Connecting To Dgraph Cloud\n\nIf you want to connect to Dgraph running on [Dgraph Cloud](https://cloud.dgraph.io) instance, then\nget the gRPC endpoint of your cluster that you can find in the\n[Settings section](https://cloud.dgraph.io/_/settings) of Dgraph Cloud console and obtain a Client\nor Admin API key (created in the [API key tab](https://cloud.dgraph.io/_/settings?tab=api-keys) of\nthe Setting section). Create the `client_stub` using the gRPC endpoint and the API key:\n\n```python3\nclient_stub = pydgraph.DgraphClientStub.from_cloud(\n    \"https://morning-glade.grpc.us-east-1.aws.cloud.dgraph.io:443\", \"<api-key>\")\nclient = pydgraph.DgraphClient(client_stub)\n```\n\nAlternatively, you can simply use a Dgraph connection string with the `open` function. For example:\n\n```python\nconn_str = \"dgraph://foo-bar.grpc.us-west-2.aws.cloud.dgraph.io:443?sslmode=verify-ca&apikey=<your-api-connection-key>\"\nclient = pydgraph.open(conn_str)\n\n# some time later...\nclient.close()\n```\n\nThe `DgraphClientStub.from_slash_endpoint()` method has been removed v23.0. Please use\n`DgraphClientStub.from_cloud()` instead.\n\n### Altering the Database\n\n#### Set the Dgraph types schema\n\nTo set the Dgraph types schema (aka DQL schema), create an `Operation` object, set the schema and\npass it to `DgraphClient#alter(Operation)` method.\n\n```python3\nschema = 'name: string @index(exact) .'\nop = pydgraph.Operation(schema=schema)\nclient.alter(op)\n```\n\nIndexes can be computed in the background. You can set the `run_in_background` field of\n`pydgraph.Operation` to `True` before passing it to the `Alter` function. You can find more details\n[here](https://docs.dgraph.io/master/query-language/#indexes-in-background).\n\n**Note** To deploy the GraphQL schema in python you have to use GraphQL client such as\n[python-graphql-client](https://github.com/prodigyeducation/python-graphql-client) to invoke the\nGraphQL admin mutation\n[updateGQLSchema](https://dgraph.io/docs/graphql/admin/#using-updategqlschema-to-add-or-modify-a-schema)\n\n```python3\nschema = 'name: string @index(exact) .'\nop = pydgraph.Operation(schema=schema, run_in_background=True)\nclient.alter(op)\n```\n\n#### Drop data\n\nTo drop all data and schema:\n\n```python3\n# Drop all data including schema from the Dgraph instance. This is a useful\n# for small examples such as this since it puts Dgraph into a clean state.\nop = pydgraph.Operation(drop_all=True)\nclient.alter(op)\n```\n\n**Note** If the Dgraph cluster contains a GraphQL Schema, it will also be deleted by this operation.\n\nTo drop all data and preserve the DQL schema:\n\n```python3\n# Drop all data from the Dgraph instance. Keep the DQL Schema.\nop = pydgraph.Operation(drop_op=\"DATA\")\nclient.alter(op)\n```\n\nTo drop a predicate:\n\n```python3\n# Drop the data associated to a predicate and the predicate from the schema.\nop = pydgraph.Operation(drop_op=\"ATTR\", drop_value=\"<predicate_name>\")\nclient.alter(op)\n```\n\nthe same result is obtained using\n\n```python3\n# Drop the data associated to a predicate and the predicate from the schema.\nop = pydgraph.Operation(drop_attr=\"<predicate_name>\")\nclient.alter(op)\n```\n\nTo drop a type definition from DQL Schema:\n\n```python3\n# Drop a type from the schema.\nop = pydgraph.Operation(drop_op=\"TYPE\", drop_value=\"<predicate_name>\")\nclient.alter(op)\n```\n\n**Note** `drop_op=\"TYPE\"` just removes a type definition from the DQL schema. No data is removed\nfrom the cluster. The operation does not drop the predicates associated with the type.\n\n### Creating a Transaction\n\nTo create a transaction, call the `DgraphClient#txn()` method, which returns a new `Txn` object.\nThis operation incurs no network overhead.\n\nIt is good practice to call `Txn#discard()` in a `finally` block after running the transaction.\nCalling `Txn#discard()` after `Txn#commit()` is a no-op and you can call `Txn#discard()` multiple\ntimes with no additional side-effects.\n\n```python3\ntxn = client.txn()\ntry:\n  # Do something here\n  # ...\nfinally:\n  txn.discard()\n  # ...\n```\n\nTo create a read-only transaction, call `DgraphClient#txn(read_only=True)`. Read-only transactions\nare ideal for transactions which only involve queries. Mutations and commits are not allowed.\n\n```python3\ntxn = client.txn(read_only=True)\ntry:\n  # Do some queries here\n  # ...\nfinally:\n  txn.discard()\n  # ...\n```\n\nTo create a read-only transaction that executes best-effort queries, call\n`DgraphClient#txn(read_only=True, best_effort=True)`. Best-effort queries are faster than normal\nqueries because they bypass the normal consensus protocol. For this same reason, best-effort queries\ncannot guarantee to return the latest data. Best-effort queries are only supported by read-only\ntransactions.\n\n### Running a Mutation\n\n`Txn#mutate(mu=Mutation)` runs a mutation. It takes in a `Mutation` object, which provides two main\nways to set data: JSON and RDF N-Quad. You can choose whichever way is convenient.\n\n`Txn#mutate()` provides convenience keyword arguments `set_obj` and `del_obj` for setting JSON\nvalues and `set_nquads` and `del_nquads` for setting N-Quad values. See examples below for usage.\n\nWe define a person object to represent a person and use it in a transaction.\n\n```python3\n# Create data.\np = { 'name': 'Alice' }\n\n# Run mutation.\ntxn.mutate(set_obj=p)\n\n# If you want to use a mutation object, use this instead:\n# mu = pydgraph.Mutation(set_json=json.dumps(p).encode('utf8'))\n# txn.mutate(mu)\n\n# If you want to use N-Quads, use this instead:\n# txn.mutate(set_nquads='_:alice <name> \"Alice\" .')\n```\n\n```python3\n# Delete data\n\nquery = \"\"\"query all($a: string)\n {\n   all(func: eq(name, $a))\n    {\n      uid\n    }\n  }\"\"\"\nvariables = {'$a': 'Bob'}\n\nres = txn.query(query, variables=variables)\nppl = json.loads(res.json)\n\n# For a mutation to delete a node, use this:\ntxn.mutate(del_obj=person)\n```\n\nFor a complete example with multiple fields and relationships, look at the [simple project][simple]\nin the `examples` folder.\n\nSometimes, you only want to commit a mutation, without querying anything further. In such cases, you\ncan set the keyword argument `commit_now=True` to indicate that the mutation must be immediately\ncommitted.\n\nA mutation can be executed using `txn.do_request` as well.\n\n```python3\nmutation = txn.create_mutation(set_nquads='_:alice <name> \"Alice\" .')\nrequest = txn.create_request(mutations=[mutation], commit_now=True)\ntxn.do_request(request)\n```\n\n### Running a Query\n\nYou can run a query by calling `Txn#query(string)`. You will need to pass in a\n[DQL](https://dgraph.io/docs/query-language/) query string. If you want to pass an additional\ndictionary of any variables that you might want to set in the query, call\n`Txn#query(string, variables=d)` with the variables dictionary `d`.\n\nThe query response contains the `json` field, which returns the JSON response. Let\u2019s run a query\nwith a variable `$a`, deserialize the result from JSON and print it out:\n\n```python3\n# Run query.\nquery = \"\"\"query all($a: string) {\n  all(func: eq(name, $a))\n  {\n    name\n  }\n}\"\"\"\nvariables = {'$a': 'Alice'}\n\nres = txn.query(query, variables=variables)\n\n# If not doing a mutation in the same transaction, simply use:\n# res = client.txn(read_only=True).query(query, variables=variables)\n\nppl = json.loads(res.json)\n\n# Print results.\nprint('Number of people named \"Alice\": {}'.format(len(ppl['all'])))\nfor person in ppl['all']:\n  print(person)\n```\n\nThis should print:\n\n```console\nNumber of people named \"Alice\": 1\nAlice\n```\n\nYou can also use `txn.do_request` function to run the query.\n\n```python3\nrequest = txn.create_request(query=query)\ntxn.do_request(request)\n```\n\n### Query with RDF response\n\nYou can get query result as a RDF response by calling `Txn#query(string)` with `resp_format` set to\n`RDF`. The response would contain a `rdf` field, which has the RDF encoded result.\n\n**Note:** If you are querying only for `uid` values, use a JSON format response.\n\n```python3\nres = txn.query(query, variables=variables, resp_format=\"RDF\")\nprint(res.rdf)\n```\n\n### Running an Upsert: Query + Mutation\n\nThe `txn.do_request` function allows you to use upsert blocks. An upsert block contains one query\nblock and one or more mutation blocks, so it lets you perform queries and mutations in a single\nrequest. Variables defined in the query block can be used in the mutation blocks using the `uid` and\n`val` functions implemented by DQL.\n\nTo learn more about upsert blocks, see the\n[Upsert Block documentation](https://dgraph.io/docs/mutations/upsert-block/).\n\n```python3\nquery = \"\"\"{\n  u as var(func: eq(name, \"Alice\"))\n}\"\"\"\n\nnquad = \"\"\"\n  uid(u) <name> \"Alice\" .\n  uid(u) <age> \"25\" .\n\"\"\"\n\nmutation = txn.create_mutation(set_nquads=nquad)\nrequest = txn.create_request(query=query, mutations=[mutation], commit_now=True)\ntxn.do_request(request)\n```\n\n### Running a Conditional Upsert\n\nThe upsert block also allows specifying a conditional mutation block using an `@if` directive. The\nmutation is executed only when the specified condition is true. If the condition is false, the\nmutation is silently ignored.\n\nSee more about Conditional Upserts [here](https://docs.dgraph.io/mutations/#conditional-upsert).\n\n```python3\nquery = \"\"\"\n  {\n    user as var(func: eq(email, \"wrong_email@dgraph.io\"))\n  }\n\"\"\"\n\ncond = \"@if(eq(len(user), 1))\"\nnquads = \"\"\"\n  uid(user) <email> \"correct_email@dgraph.io\" .\n\"\"\"\n\nmutation = txn.create_mutation(cond=cond, set_nquads=nquads)\nrequest = txn.create_request(mutations=[mutation], query=query, commit_now=True)\ntxn.do_request(request)\n```\n\n### Committing a Transaction\n\nA transaction can be committed using the `Txn#commit()` method. If your transaction consist solely\nof `Txn#query` or `Txn#queryWithVars` calls, and no calls to `Txn#mutate`, then calling\n`Txn#commit()` is not necessary.\n\nAn error is raised if another transaction(s) modify the same data concurrently that was modified in\nthe current transaction. It is up to the user to retry transactions when they fail.\n\n```python3\ntxn = client.txn()\ntry:\n  # ...\n  # Perform any number of queries and mutations\n  # ...\n  # and finally...\n  txn.commit()\nexcept pydgraph.AbortedError:\n  # Retry or handle exception.\nfinally:\n  # Clean up. Calling this after txn.commit() is a no-op\n  # and hence safe.\n  txn.discard()\n```\n\n### Cleaning Up Resources\n\nTo clean up resources, you have to call `DgraphClientStub#close()` individually for all the\ninstances of `DgraphClientStub`.\n\n```python3\nSERVER_ADDR1 = \"localhost:9080\"\nSERVER_ADDR2 = \"localhost:9080\"\n\n# Create instances of DgraphClientStub.\nstub1 = pydgraph.DgraphClientStub(SERVER_ADDR1)\nstub2 = pydgraph.DgraphClientStub(SERVER_ADDR2)\n\n# Create an instance of DgraphClient.\nclient = pydgraph.DgraphClient(stub1, stub2)\n\n# Use client\n...\n\n# Clean up resources by closing all client stubs.\nstub1.close()\nstub2.close()\n```\n\n### Setting Metadata Headers\n\nMetadata headers such as authentication tokens can be set through the metadata of gRPC methods.\nBelow is an example of how to set a header named \"auth-token\".\n\n```python3\n# The following piece of code shows how one can set metadata with\n# auth-token, to allow Alter operation, if the server requires it.\n# metadata is a list of arbitrary key-value pairs.\nmetadata = [(\"auth-token\", \"the-auth-token-value\")]\ndg.alter(op, metadata=metadata)\n```\n\n### Setting a timeout\n\nA timeout value representing the number of seconds can be passed to the `login`, `alter`, `query`,\nand `mutate` methods using the `timeout` keyword argument.\n\nFor example, the following alters the schema with a timeout of ten seconds:\n`dg.alter(op, timeout=10)`\n\n### Async methods\n\nThe `alter` method in the client has an asynchronous version called `async_alter`. The async methods\nreturn a future. You can directly call the `result` method on the future. However. The DgraphClient\nclass provides a static method `handle_alter_future` to handle any possible exception.\n\n```python3\nalter_future = self.client.async_alter(pydgraph.Operation(schema=\"name: string @index(term) .\"))\nresponse = pydgraph.DgraphClient.handle_alter_future(alter_future)\n```\n\nThe `query` and `mutate` methods int the `Txn` class also have async versions called `async_query`\nand `async_mutation` respectively. These functions work just like `async_alter`.\n\nYou can use the `handle_query_future` and `handle_mutate_future` static methods in the `Txn` class\nto retrieve the result. A short example is given below:\n\n```python3\ntxn = client.txn()\nquery = \"query body here\"\nfuture = txn.async_query()\nresponse = pydgraph.Txn.handle_query_future(future)\n```\n\nKeep in mind that due to the nature of async calls, the async functions cannot retry the request if\nthe login is invalid. You will have to check for this error and retry the login (with the function\n`retry_login` in both the `Txn` and `Client` classes). A short example is given below:\n\n```python3\nclient = DgraphClient(client_stubs) # client_stubs is a list of gRPC stubs.\nalter_future = client.async_alter()\ntry:\n    response = alter_future.result()\nexcept Exception as e:\n  # You can use this function in the util package to check for JWT\n    # expired errors.\n    if pydgraph.util.is_jwt_expired(e):\n        # retry your request here.\n```\n\n## Examples\n\n[tls]: ./examples/tls\n[parse_datetime]: ./examples/parse_datetime\n\n- [simple][]: Quickstart example of using pydgraph.\n- [tls][]: Quickstart example that uses TLS.\n- [parse_datetime]: Demonstration of converting Dgraph's DateTime strings to native python datetime.\n\n## Development\n\n### Setting up environment\n\nThere are many ways to set up your local Python environment. We suggest some sane defaults here.\n\n- Use [pyenv](https://github.com/pyenv/pyenv) to manage your Python installations.\n- Most recent versions of Python should work, but the version of Python officially supported is\n  located in `.python-version`\n- Create a Python virtual environment using `python -m venv .venv`\n- Activate virtual environment via `source .venv/bin/activate`\n\n### Build from source\n\nTo build and install pydgraph locally, run\n\n```sh\npip install -e \".[dev]\"\n```\n\n#### Regenerating protobufs\n\nIf you have made changes to the `pydgraph/proto/api.proto` file, you need need to regenerate the\nsource files generated by Protocol Buffer tools. To do that, install the\n[grpcio-tools][grpcio-tools] library and then run the following command:\n\n[grpcio-tools]: https://pypi.python.org/pypi/grpcio-tools\n\n```sh\npython scripts/protogen.py\n```\n\n**Important**: This project uses grpcio-tools 1.65.x to ensure compatibility with the minimum\nsupported grpcio version (1.65.0). This version generates code that issues warnings (not errors) for\nusers with older grpcio versions, providing a graceful upgrade path. It also uses protobuf 5.x which\neliminates Python 3.12+ deprecation warnings. The dev dependencies in `pyproject.toml` are pinned to\nthe correct version (grpcio-tools 1.65.x)\n\nIf you are using python version 3.13 or higher, an error will be raised if you try to run\n`scripts/protogen.py`. This is to prevent generating protobufs that are incompatible with older\ngrpcio-tools versions.\n\n#### grpcio 1.65.0 is the minimum version\n\nOlder grpcio versions have practical limitations:\n\n- **Compilation failures**: grpcio versions older than ~1.60.0 fail to compile from source on modern\n  systems (macOS with recent Xcode, newer Linux distributions) due to C++ compiler compatibility\n  issues and outdated build configurations.\n- **No pre-built wheels**: PyPI doesn't provide pre-built wheels for very old grpcio versions on\n  modern Python versions (3.11+), forcing compilation from source.\n- **Build tool incompatibility**: The build process for older grpcio versions uses deprecated\n  compiler flags and build patterns that modern toolchains reject.\n\n### Running tests\n\nTo run the tests in your local machine, run:\n\n```bash\nbash scripts/local-test.sh\n```\n\nYou can run a specific test suite:\n\n```bash\nbash scripts/local-test.sh -v tests/test_connect.py::TestOpen\n```\n\nor an individual test:\n\n```bash\nbash scripts/local-test.sh -v tests/test_connect.py::TestOpen::test_connection_with_auth\n```\n\nThe test script requires that `docker` and `docker compose` are installed on your machine.\n\nThe script will take care of bringing up a Dgraph cluster and bringing it down after the tests are\nexecuted. The script connects to randomly selected ports for HTTP and gRPC requests to prevent\ninterference with clusters running on the default port. Docker and docker-compose need to be\ninstalled before running the script. Refer to the official\n[Docker documentation](https://docs.docker.com/) for instructions on how to install those packages.\n",
    "bugtrack_url": null,
    "license": "Apache License\n                                   Version 2.0, January 2004\n                                http://www.apache.org/licenses/\n        \n           TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION\n        \n           1. Definitions.\n        \n              \"License\" shall mean the terms and conditions for use, reproduction,\n              and distribution as defined by Sections 1 through 9 of this document.\n        \n              \"Licensor\" shall mean the copyright owner or entity authorized by\n              the copyright owner that is granting the License.\n        \n              \"Legal Entity\" shall mean the union of the acting entity and all\n              other entities that control, are controlled by, or are under common\n              control with that entity. For the purposes of this definition,\n              \"control\" means (i) the power, direct or indirect, to cause the\n              direction or management of such entity, whether by contract or\n              otherwise, or (ii) ownership of fifty percent (50%) or more of the\n              outstanding shares, or (iii) beneficial ownership of such entity.\n        \n              \"You\" (or \"Your\") shall mean an individual or Legal Entity\n              exercising permissions granted by this License.\n        \n              \"Source\" form shall mean the preferred form for making modifications,\n              including but not limited to software source code, documentation\n              source, and configuration files.\n        \n              \"Object\" form shall mean any form resulting from mechanical\n              transformation or translation of a Source form, including but\n              not limited to compiled object code, generated documentation,\n              and conversions to other media types.\n        \n              \"Work\" shall mean the work of authorship, whether in Source or\n              Object form, made available under the License, as indicated by a\n              copyright notice that is included in or attached to the work\n              (an example is provided in the Appendix below).\n        \n              \"Derivative Works\" shall mean any work, whether in Source or Object\n              form, that is based on (or derived from) the Work and for which the\n              editorial revisions, annotations, elaborations, or other modifications\n              represent, as a whole, an original work of authorship. For the purposes\n              of this License, Derivative Works shall not include works that remain\n              separable from, or merely link (or bind by name) to the interfaces of,\n              the Work and Derivative Works thereof.\n        \n              \"Contribution\" shall mean any work of authorship, including\n              the original version of the Work and any modifications or additions\n              to that Work or Derivative Works thereof, that is intentionally\n              submitted to Licensor for inclusion in the Work by the copyright owner\n              or by an individual or Legal Entity authorized to submit on behalf of\n              the copyright owner. For the purposes of this definition, \"submitted\"\n              means any form of electronic, verbal, or written communication sent\n              to the Licensor or its representatives, including but not limited to\n              communication on electronic mailing lists, source code control systems,\n              and issue tracking systems that are managed by, or on behalf of, the\n              Licensor for the purpose of discussing and improving the Work, but\n              excluding communication that is conspicuously marked or otherwise\n              designated in writing by the copyright owner as \"Not a Contribution.\"\n        \n              \"Contributor\" shall mean Licensor and any individual or Legal Entity\n              on behalf of whom a Contribution has been received by Licensor and\n              subsequently incorporated within the Work.\n        \n           2. Grant of Copyright License. Subject to the terms and conditions of\n              this License, each Contributor hereby grants to You a perpetual,\n              worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n              copyright license to reproduce, prepare Derivative Works of,\n              publicly display, publicly perform, sublicense, and distribute the\n              Work and such Derivative Works in Source or Object form.\n        \n           3. Grant of Patent License. Subject to the terms and conditions of\n              this License, each Contributor hereby grants to You a perpetual,\n              worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n              (except as stated in this section) patent license to make, have made,\n              use, offer to sell, sell, import, and otherwise transfer the Work,\n              where such license applies only to those patent claims licensable\n              by such Contributor that are necessarily infringed by their\n              Contribution(s) alone or by combination of their Contribution(s)\n              with the Work to which such Contribution(s) was submitted. If You\n              institute patent litigation against any entity (including a\n              cross-claim or counterclaim in a lawsuit) alleging that the Work\n              or a Contribution incorporated within the Work constitutes direct\n              or contributory patent infringement, then any patent licenses\n              granted to You under this License for that Work shall terminate\n              as of the date such litigation is filed.\n        \n           4. Redistribution. You may reproduce and distribute copies of the\n              Work or Derivative Works thereof in any medium, with or without\n              modifications, and in Source or Object form, provided that You\n              meet the following conditions:\n        \n              (a) You must give any other recipients of the Work or\n                  Derivative Works a copy of this License; and\n        \n              (b) You must cause any modified files to carry prominent notices\n                  stating that You changed the files; and\n        \n              (c) You must retain, in the Source form of any Derivative Works\n                  that You distribute, all copyright, patent, trademark, and\n                  attribution notices from the Source form of the Work,\n                  excluding those notices that do not pertain to any part of\n                  the Derivative Works; and\n        \n              (d) If the Work includes a \"NOTICE\" text file as part of its\n                  distribution, then any Derivative Works that You distribute must\n                  include a readable copy of the attribution notices contained\n                  within such NOTICE file, excluding those notices that do not\n                  pertain to any part of the Derivative Works, in at least one\n                  of the following places: within a NOTICE text file distributed\n                  as part of the Derivative Works; within the Source form or\n                  documentation, if provided along with the Derivative Works; or,\n                  within a display generated by the Derivative Works, if and\n                  wherever such third-party notices normally appear. The contents\n                  of the NOTICE file are for informational purposes only and\n                  do not modify the License. You may add Your own attribution\n                  notices within Derivative Works that You distribute, alongside\n                  or as an addendum to the NOTICE text from the Work, provided\n                  that such additional attribution notices cannot be construed\n                  as modifying the License.\n        \n              You may add Your own copyright statement to Your modifications and\n              may provide additional or different license terms and conditions\n              for use, reproduction, or distribution of Your modifications, or\n              for any such Derivative Works as a whole, provided Your use,\n              reproduction, and distribution of the Work otherwise complies with\n              the conditions stated in this License.\n        \n           5. Submission of Contributions. Unless You explicitly state otherwise,\n              any Contribution intentionally submitted for inclusion in the Work\n              by You to the Licensor shall be under the terms and conditions of\n              this License, without any additional terms or conditions.\n              Notwithstanding the above, nothing herein shall supersede or modify\n              the terms of any separate license agreement you may have executed\n              with Licensor regarding such Contributions.\n        \n           6. Trademarks. This License does not grant permission to use the trade\n              names, trademarks, service marks, or product names of the Licensor,\n              except as required for reasonable and customary use in describing the\n              origin of the Work and reproducing the content of the NOTICE file.\n        \n           7. Disclaimer of Warranty. Unless required by applicable law or\n              agreed to in writing, Licensor provides the Work (and each\n              Contributor provides its Contributions) on an \"AS IS\" BASIS,\n              WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n              implied, including, without limitation, any warranties or conditions\n              of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A\n              PARTICULAR PURPOSE. You are solely responsible for determining the\n              appropriateness of using or redistributing the Work and assume any\n              risks associated with Your exercise of permissions under this License.\n        \n           8. Limitation of Liability. In no event and under no legal theory,\n              whether in tort (including negligence), contract, or otherwise,\n              unless required by applicable law (such as deliberate and grossly\n              negligent acts) or agreed to in writing, shall any Contributor be\n              liable to You for damages, including any direct, indirect, special,\n              incidental, or consequential damages of any character arising as a\n              result of this License or out of the use or inability to use the\n              Work (including but not limited to damages for loss of goodwill,\n              work stoppage, computer failure or malfunction, or any and all\n              other commercial damages or losses), even if such Contributor\n              has been advised of the possibility of such damages.\n        \n           9. Accepting Warranty or Additional Liability. While redistributing\n              the Work or Derivative Works thereof, You may choose to offer,\n              and charge a fee for, acceptance of support, warranty, indemnity,\n              or other liability obligations and/or rights consistent with this\n              License. However, in accepting such obligations, You may act only\n              on Your own behalf and on Your sole responsibility, not on behalf\n              of any other Contributor, and only if You agree to indemnify,\n              defend, and hold each Contributor harmless for any liability\n              incurred by, or claims asserted against, such Contributor by reason\n              of your accepting any such warranty or additional liability.\n        \n           END OF TERMS AND CONDITIONS",
    "summary": "Official Dgraph client implementation for Python",
    "version": "24.3.0",
    "project_urls": {
        "Homepage": "https://github.com/hypermodeinc/pydgraph"
    },
    "split_keywords": [],
    "urls": [
        {
            "comment_text": null,
            "digests": {
                "blake2b_256": "496defab9acf2d72ed139e609579627334ba073a7647c17b9f3ff0a09acfa608",
                "md5": "25974e674cab575ace91e2be1eee7ca2",
                "sha256": "770ea703301dcce5e92eda94a8fc1bec17d53de4232bfdd78089a87ad32aa975"
            },
            "downloads": -1,
            "filename": "pydgraph-24.3.0-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "25974e674cab575ace91e2be1eee7ca2",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.7",
            "size": 30511,
            "upload_time": "2025-08-05T00:50:17",
            "upload_time_iso_8601": "2025-08-05T00:50:17.821034Z",
            "url": "https://files.pythonhosted.org/packages/49/6d/efab9acf2d72ed139e609579627334ba073a7647c17b9f3ff0a09acfa608/pydgraph-24.3.0-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": null,
            "digests": {
                "blake2b_256": "993fcc4236257e616fa3394c53f75650a3e7145cc95472f6d811604e3a662411",
                "md5": "f4e4617deec115e1b707ea01b681ec53",
                "sha256": "1f42541cd542c379b5048695e55b847614367bdfb7774cd0198e9d61b0455af4"
            },
            "downloads": -1,
            "filename": "pydgraph-24.3.0.tar.gz",
            "has_sig": false,
            "md5_digest": "f4e4617deec115e1b707ea01b681ec53",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.7",
            "size": 47428,
            "upload_time": "2025-08-05T00:50:19",
            "upload_time_iso_8601": "2025-08-05T00:50:19.067879Z",
            "url": "https://files.pythonhosted.org/packages/99/3f/cc4236257e616fa3394c53f75650a3e7145cc95472f6d811604e3a662411/pydgraph-24.3.0.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2025-08-05 00:50:19",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "hypermodeinc",
    "github_project": "pydgraph",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": true,
    "lcname": "pydgraph"
}
        
Elapsed time: 1.36119s