Giter Site home page Giter Site logo

fauna / faunadb-python Goto Github PK

View Code? Open in Web Editor NEW
124.0 34.0 25.0 633 KB

Python driver for Fauna v4

Home Page: https://docs.fauna.com/fauna/v4/

License: Other

Python 98.25% Makefile 0.82% Shell 0.93%
driver drivers client clients fauna faunadb database python

faunadb-python's Introduction

The Official Python driver for v4 API of Fauna

image

image

image

Python driver for FaunaDB.

Note: This driver supports an older version of the Fauna API. The latest version of the official Fauna Python Driver is located [here](https://pypi.org/project/faunadb/) (we encourage all new development to use this new version where possible).

Installation

$ pip install faunadb

Compatibility

The following versions of Python are supported:

  • Python 3.6
  • Python 3.7
  • Python 3.8
  • Python 3.9
  • Python 3.10

Documentation

Driver documentation is available at https://fauna.github.io/faunadb-python/4.5.0/api/.

See the FaunaDB Documentation for a complete API reference, or look in tests for more examples.

Basic Usage

from faunadb import query as q
from faunadb.objects import Ref
from faunadb.client import FaunaClient

client = FaunaClient(secret="your-secret-here")

indexes = client.query(q.paginate(q.indexes()))

print(indexes)

Document Streaming

Fauna supports document streaming, where changes to a streamed document are pushed to all clients subscribing to that document.

The following section provides an example for managing a document stream.

The streaming API is blocking by default, the choice and mechanism for handling concurrent streams is left to the application developer:

from faunadb import query as q
from faunadb.objects import Ref
from faunadb.client import FaunaClient

client = FaunaClient(secret="your-secret-here")

coll = client.query(q.create_collection({"name":"sc"}))
doc  = client.query(q.create(coll["ref"], {"data":{"x": 0}}))

stream = None
def on_start(event):
    print("started stream at %s"%(event.txn))
    client.query(q.update(doc["ref"], {"data": {"x": "updated"}}))

def on_version(event):
    print("on_version event at %s"%(event.txn))
    print("    event: %s"%(event.event))
    stream.close()

def on_error(event):
    print("Received error event %s"%(event))
options = {"fields": ["document", "diff"]}
stream = client.stream(doc["ref"], options, on_start, on_error, on_version)
stream.start()

Observing Metrics

Its possible to observe each query's metrics by providing an "observer" callback.

More information on query metrics is available in the FaunaDB Documentation.

Here is a simple example:

from faunadb import query as q
from faunadb.client import FaunaClient
from faunadb.errors import FaunaError

# The observer callback, which takes the HTTP response for a query
def observe(response):
    h = response.response_headers
    print('bytesOut:', h["x-compute-ops"])
    print('queryTime:', h["x-query-time"])
    print('readOps:', h["x-byte-read-ops"])
    print('writeOps:', h["x-byte-write-ops"])
    print('retries:', h["x-txn-retries"])

# Connect to a local Fauna Dev instance
client = FaunaClient(
    secret="secret",
    domain="localhost",
    scheme="http",
    port=8443,
    observer=observe
)

try:
    result = client.query(
        q.paginate(q.collections())
    )
except FaunaError as err:
    print("err: ", err)
else:
    print(result)

Building it yourself

Setup

$ virtualenv venv
$ source venv/bin/activate
$ pip install .

Testing

To run the tests you must have a FaunaDB database available. Then set the environment variable FAUNA_ROOT_KEY to your database's root key. If you use FaunaDB cloud, this is the password you log in with.

Tip: Setting the FAUNA_QUERY_TIMEOUT_MS environment variable will set a timeout in milliseconds for all queries.

Then run make test. To test a single test, use e.g. python -m unittest tests.test_client.ClientTest.test_ping.

Tests can also be run via a Docker container with FAUNA_ROOT_KEY="your-cloud-secret" make docker-test (an alternate Alpine-based Python image can be provided via RUNTIME_IMAGE).

Coverage

To run the tests with coverage, install the coverage dependencies with pip install .[coverage], and then run make coverage. A summary will be displayed to the terminal, and a detailed coverage report will be available at htmlcov/index.html.

Contribute

GitHub pull requests are very welcome.

License

Copyright 2020 Fauna, Inc.

Licensed under the Mozilla Public License, Version 2.0 (the "License"); you may not use this software except in compliance with the License. You may obtain a copy of the License at

http://mozilla.org/MPL/2.0/

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

faunadb-python's People

Contributors

adambollen avatar alvarofauna avatar andy-faunadb avatar ashfire908 avatar bitbckt avatar clbray avatar cleve-fauna avatar cynicaljoy avatar dijkstracula avatar erickpintor avatar fauna-bot avatar faunaee avatar fireridlle avatar freels avatar henryfauna avatar macmv avatar macnealefauna avatar marrony avatar mwilde345 avatar n400 avatar parkhomenko avatar pnwpedro avatar ptpaterson avatar sprsquish avatar stigjb avatar yesha-fauna avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

faunadb-python's Issues

python 3.10 support

ImportError: cannot import name 'Iterable' from 'collections' (/usr/local/lib/python3.10/collections/__init__.py)

options = {"fields": ["document", "diff", "action"]}
stream = client.stream(doc["ref"], options, on_start, on_error, on_version)
stream.start()
Traceback (most recent call last):
  File "/workspaces/faunadb/github/faunadb-python/example.py", line 3, in <module>
    from faunadb.client import FaunaClient
  File "/workspaces/faunadb/github/faunadb-python/faunadb/client.py", line 19, in <module>
    from faunadb.streams import Subscription
  File "/workspaces/faunadb/github/faunadb-python/faunadb/streams/__init__.py", line 1, in <module>
    from .client import Connection
  File "/workspaces/faunadb/github/faunadb-python/faunadb/streams/client.py", line 12, in <module>
    from hyper import HTTP20Connection
  File "/home/vscode/.local/lib/python3.10/site-packages/hyper/__init__.py", line 11, in <module>
    from .common.connection import HTTPConnection
  File "/home/vscode/.local/lib/python3.10/site-packages/hyper/common/connection.py", line 9, in <module>
    from ..http11.connection import HTTP11Connection
  File "/home/vscode/.local/lib/python3.10/site-packages/hyper/http11/connection.py", line 13, in <module>
    from collections import Iterable, Mapping
ImportError: cannot import name 'Iterable' from 'collections' (/usr/local/lib/python3.10/collections/__init__.py)

This is due to hyper, for stream function (http/2)

from hyper import HTTP20Connection

self.conn = HTTP20Connection(

"This project is no longer maintained!
Please use an alternative, such as HTTPX or others.
We will not publish further updates for hyper."

https://github.com/python-hyper/hyper

(faunadb-python works with python 3.9)

Hyper deprecation

It looks like this driver uses the hyper library internally, however it seems to have been deprecated and archived. Any news of a rewrite with a maintained library?

why raising errors?

Why raising errors on not found? you need try-catch on every query - very ugly

Fauna version upgrade message provides invalid link

When interactively messing around with the faunadb python client, it appears to check if a new version is available. However, the chanelog URL pointed to by the upgrade message is invalid and results in a 404.

Reproduction steps:

  1. install an old version of the faunadb python client in your local environment
  2. drop into a python REPL
  3. instantiate the faunadb python client

Expected result:

A valid changelog link is provided, I.E. https://github.com/fauna/faunadb-python/blob/v4/CHANGELOG.md

Actual result:

An invalid changelog link is provided: https://github.com/fauna/faunadb-python/blob/main/CHANGELOG.md

>>> from faunadb.client import FaunaClient
>>> fauna_client = FaunaClient(secret="super_secret_key", domain="db.us.fauna.com", timeout=5)
+--------------------------------------------------------------------------------+
| New fauna version available 4.2.0 => 4.3.0                                     |
| Changelog: https://github.com/fauna/faunadb-python/blob/main/CHANGELOG.md      |
+--------------------------------------------------------------------------------+
>>>

Example Documentation for Lambdas

Please could we have some examples of using Lambda() FQL with this library?

I can't seem to find anything in the documentation...

Query parameter names

The website docs use short names like bool while we've often used longer names like boolean. Should we be consistently short or consistently long?

In particular, we should consistently name collection parameters coll or collection.
But when functions can only take an array we should call it arr or array instead.

Where did the documentation go?

Hi there!

The title sums it up pretty much, why is the readthedocs page not working? I'm having a hard time trying to find info about the driver.

TypeError: catching classes that do not inherit from BaseException is not allowed

I'm creating cli application to interact with the db using typer and I've the following code:

# app.py
from typing import Any
from faunadb.client import FaunaClient
from faunadb import query as q
import typer
from .settings import get_settings

settings = get_settings()
client = FaunaClient(secret=settings.DB_ADMIN_PYTHON)
app = typer.Typer()


@app.command()
def create_collection_with_index(name: str) -> Any:
    c = client.query(q.collection(name))
    if client.query(q.exists(c)) == False:
        c = client.query(q.create_collection({"name": name}))

    idx_name = f"{name}_index"
    ci = client.query(q.index(idx_name))
    if client.query(q.exists(ci)) == False:
        ci = client.query(
            q.create_index(
                {
                    "name": idx_name,
                    "unique": True,
                    "serialized": True,
                    "source": q.collection(name),
                }
            )
        )
    return c, ci


@app.command()
def initialize_db() -> None:
    typer.echo("Initializing db...")
# app.py
from typing import Any
from faunadb.client import FaunaClient
from faunadb import query as q
import typer
from .settings import get_settings

settings = get_settings()
client = FaunaClient(secret=settings.DB_ADMIN_PYTHON)
app = typer.Typer()


@app.command()
def create_collection_with_index(name: str) -> Any:
    c = client.query(q.collection(name))
    if client.query(q.exists(c)) == False:
        c = client.query(q.create_collection({"name": name}))

    idx_name = f"{name}_index"
    ci = client.query(q.index(idx_name))
    if client.query(q.exists(ci)) == False:
        ci = client.query(
            q.create_index(
                {
                    "name": idx_name,
                    "unique": True,
                    "serialized": True,
                    "source": q.collection(name),
                }
            )
        )
    return c, ci


@app.command()
def initialize_db() -> None:
    typer.echo("Initializing db...")
    uc, uci = create_collection_with_index(name="users")
    bc, bci = create_collection_with_index(name="brokers")
    dosc, dosci = create_collection_with_index(name="dos_paramters")
    typer.echo("Db initialized...")

if __name__ == "__main__":
    app()

    typer.echo("Db initialized...")

if __name__ == "__main__":
    app()
# settings.py
from pathlib import Path

from pydantic import BaseSettings


class Settings(BaseSettings):
    DB_ADMIN_PYTHON: str
    class Config:
        env_file = ".env"


def get_settings() -> Settings:
    try:
        env_file: str = "./credentials/faunadb.env"
        if Path(env_file).is_file():
            envs = Settings(_env_file=env_file)
        else:
            envs = Settings()
        return envs
    except Exception as e:
        raise e

When I run the application cli as python -m app:app initialize-db (note the - not as _ in the function declaration) I get the following errors after successful execution of the command:

(.venv) abbas@MKHM01:~/faunadb_base_exception$ python -m app.app initialize-db
Initializing db...
Db initialized...
Exception ignored in: <function FaunaClient.__del__ at 0x7f22cd3ba8b0>
Traceback (most recent call last):
  File "/faunadb_base_exception/.venv/lib/python3.9/site-packages/faunadb/client.py", line 282, in __del__
  File "/faunadb_base_exception/.venv/lib/python3.9/site-packages/requests/sessions.py", line 747, in close
  File "/faunadb_base_exception/.venv/lib/python3.9/site-packages/requests/adapters.py", line 325, in close
  File "/faunadb_base_exception/.venv/lib/python3.9/site-packages/urllib3/poolmanager.py", line 222, in clear
  File "/faunadb_base_exception/.venv/lib/python3.9/site-packages/urllib3/_collections.py", line 100, in clear
  File "/faunadb_base_exception/.venv/lib/python3.9/site-packages/urllib3/poolmanager.py", line 173, in <lambda>
  File "/faunadb_base_exception/.venv/lib/python3.9/site-packages/urllib3/connectionpool.py", line 494, in close
TypeError: catching classes that do not inherit from BaseException is not allowed

How can I resolve this issue?

To reproduce the issue clone repository
After cloning use poetry install to get the environment setup.

Usage with Django ORM

Hi, I've been reading about the Fauna and it looks very promising.

However, I maintain several Django applications and I wonder what would it take to integrate the Fauna clients with Django ORM so that the application does not require massive refactoring?

Thank you.

select() cannot use None as the default parameter

An optional default parameter was added to the query.select function in v4.1.0, making it possible to replace the use of select_with_default with select in many situations. However, there is no way to use select if you intend to use None as the value of the default parameter.

The two statements below look like they should behave the same, but the second one raises an error if the path cannot be found.

q.select_with_default(2, ["one", "two", "three", "four"], None)
q.select(2, ["one", "two", "three", "four"], default=None)

This can be fixed by using a sentinel value for the default value of the default parameter.

version 4.0.0 of the driver is not stable

The version 4.0.0 of the python faunadb driver has an error which needs to be resolved. While trying to run the sample code you'll get an error which says "ModuleNotFoundError: No module named 'faunadb.streams'" but this is not present on the 3.0.0 of the python driver

Screenshot 2020-11-19 at 1 16 51 AM

List of Illegal Characters

Would it be possible for the development team to compile a list of illegal characters when working with FaunaDB?

Valid JSON returns faunadb.errors.BadRequest: document data is not valid.

I have the following JSON:

{
	"_RAJ2000": 0.00046,
	"_DEJ2000": 62.52328000000001,
	"CXO": "J000000.1+623123",
	"RAJ2000": 0.00046,
	"DEJ2000": 62.52328000000001,
	"ePos": 2.69,
	"SN": 3.04,
	"Fb": 4.21e-15,
	"b_Fb": 2.77e-15,
	"B_Fb": 5.6299999999999996e-15,
	"Fw": "None",
	"hr2": 0.35600000000000004,
	"hr1": 0.09699999999999999,
	"fc": 0,
	"fe": 0,
	"fs": 0,
	"Vab": 0.0,
	"Vib": "None",
	"Vaw": "None",
	"Viw": "None"
}

Which is valid JSON.

When calling the Create() method, the API returns a faunadb.errors.BadRequest: document data is not valid error:

result = client.query(
    q.create(
        q.collection(collection_name),
        {
            "data": valid_json_data
        }
    )
)

Make the _json utilities public

Being able to readily convert FaunaDB objects to and from JSON is an important feature. Currently that feature is denoted as being a non-public API by naming the module _json meaning usage of these utilities is not officially supported.

I would like to see the _json module become officially supported and part of the public API this client provides by renaming it to json, E.G. from faunadb.json import to_json.

Cant get all documents from faunadb query

Tried converting this code to python didnt work for me

client.query(
    q.Map(
        q.Paginate(q.Documents(q.Collection("Article"))),
        q.Lambda(x => q.Get(x))
      )
client.query(q.map_(
    q.paginate(q.documents(q.collection("Article))),
    q.lambda_("x", q.get(q.var("x"))
    )
    )

Would love to query this data in python

Poetry fails to install faunadb

I use poetry to install packages. And poetry fails to install faunadb:

poetry add faunadb
Using version ^4.1.1 for faunadb

Updating dependencies
Resolving dependencies... (0.0s)

  AssertionError

  

  at ~/.poetry/lib/poetry/mixology/incompatibility.py:111 in __str__
      107│         )
      108│ 
      109│     def __str__(self):
      110│         if isinstance(self._cause, DependencyCause):
    → 111│             assert len(self._terms) == 2
      112│ 
      113│             depender = self._terms[0]
      114│             dependee = self._terms[1]
      115│             assert depender.is_positive()

pip install faunadb works fine.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.