Package: fauna
This driver can only be used with FQL v10, and is not compatible with earlier versions
of FQL. To query your databases with earlier API versions, see
thefaunadbpackage.See theFauna Documentationfor additional information how to configure and query your databases.InstallationpipinstallfaunaCompatibilityThe following versions of Python are supported:Python 3.9Python 3.10Python 3.11Basic UsageYou can expect aClientinstance to have reasonable defaults, like the Fauna endpointhttps://db.fauna.comand a global HTTP client, but you will always need to configure a secret.You can configure your secret by passing it directly to the client or by setting an environment variable.Supported Environment Variables:FAUNA_ENDPOINT: The Fauna endpoint to use. For example,http://localhost:8443FAUNA_SECRET: The Fauna secret to use.fromfaunaimportfqlfromfauna.clientimportClientfromfauna.encodingimportQuerySuccessfromfauna.errorsimportFaunaExceptionclient=Client()# The client defaults to using using the value stored FAUNA_SECRET for its secret.# Either set the FAUNA_SECRET env variable or retrieve it from a secret store.# As a best practice, don't store your secret directly in your code.try:# create a collectionq1=fql('Collection.create({ name: "Dogs" })')client.query(q1)# create a documentq2=fql('Dogs.create({ name: "Scout" })')res:QuerySuccess=client.query(q2)doc=res.dataprint(doc)exceptFaunaExceptionase:# handle errorsprint(e)Query CompositionThis driver supports query composition with Python primitives, lists, dicts, and other FQL queries.For FQL templates, denote variables with${}and pass variables as kwargs tofql(). You can escape a variable by prepending an additional$.fromfaunaimportfqlfromfauna.clientimportClientclient=Client()defadd_two(x):returnfql("${x}+ 2",x=x)q=fql("${y}+ 4",y=add_two(2))res=client.query(q)print(res.data)# 8Serialization / DeserializationSerialization and deserialization with user-defined classes is not yet supported.When building queries, adapt your classes into dicts or lists prior to using them in composition. When instantiating classes from the query result data, build them from the expected result.classMyClass:def__init__(self,my_prop):self.my_prop=my_propdefto_dict(self):return{'my_prop':self.my_prop}@static_methoddeffrom_result(obj):returnMyClass(obj['my_prop'])Client ConfigurationMax AttemptsThe maximum number of times a query will be attempted if a retryable exception is thrown (ThrottlingError). Default 3, inclusive of the initial call.  The retry strategy implemented is a simple exponential backoff.To disable retries, pass max_attempts less than or equal to 1.Max BackoffThe maximum backoff in seconds to be observed between each retry. Default 20 seconds.TimeoutsThere are a few different timeout settings that can be configured; each comes with a default setting. We recommend that most applications use the defaults.Query TimeoutThe query timeout is the time, asdatetime.timedelta, that Fauna will spend executing your query before aborting with aQueryTimeoutError.The query timeout can be set using thequery_timeoutoption. The default value if you do not provide one isDefaultClientBufferTimeout(5 seconds).fromdatetimeimporttimedeltafromfauna.clientimportClientclient=Client(query_timeout=timedelta(seconds=20))The query timeout can also be set to a different value for each query using theQueryOptions.query_timeoutoption. Doing so overrides the client configuration when performing this query.fromdatetimeimporttimedeltafromfauna.clientimportClient,QueryOptionsresponse=client.query(myQuery,QueryOptions(query_timeout=timedelta(seconds=20)))Client TimeoutThe client timeout is the time, asdatetime.timedelta, that the client will wait for a network response before canceling the request. If a client timeout occurs, the driver will throw an instance ofNetworkError.The client timeout is always the query timeout plus an additional buffer. This ensures that the client always waits for at least as long Fauna could work on your query and account for network latency.The client timeout buffer is configured by setting theclient_buffer_timeoutoption. The default value for the buffer if you do not provide on isDefaultClientBufferTimeout(5 seconds), therefore the default client timeout is 10 seconds when considering the default query timeout.fromdatetimeimporttimedeltafromfauna.clientimportClientclient=Client(client_buffer_timeout=timedelta(seconds=20))Idle TimeoutThe idle timeout is the time, asdatetime.timedelta, that a session will remain open after there is no more pending communication. Once the session idle time has elapsed the session is considered idle and the session is closed. Subsequent requests will create a new session; the session idle timeout does not result in an error.Configure the idle timeout using thehttp_idle_timeoutoption. The default value if you do not provide one isDefaultIdleConnectionTimeout(5 seconds).fromdatetimeimporttimedeltafromfauna.clientimportClientclient=Client(http_idle_timeout=timedelta(seconds=6))>Note> Your application process may continue executing after all requests are completed for the duration of the session idle timeout. To prevent this, it is recommended to callClient.close()once all requests are complete. It is not recommended to sethttp_idle_timeoutto small values.Connect TimeoutThe connect timeout is the maximum amount of time, asdatetime.timedelta, to wait until a connection to Fauna is established. If the client is unable to connect within this time frame, aConnectTimeoutexception is raised.Configure the connect timeout using thehttp_connect_timeoutoption. The default value if you do not provide one isDefaultHttpConnectTimeout(5 seconds).fromdatetimeimporttimedeltafromfauna.clientimportClientclient=Client(http_connect_timeout=timedelta(seconds=6))Pool TimeoutThe pool timeout specifies the maximum amount of time, asdatetime.timedelta, to wait for acquiring a connection from the connection pool. If the client is unable to acquire a connection within this time frame, aPoolTimeoutexception is raised. This timeout may fire if 20 connections are currently in use and one isn’t released before the timeout is up.Configure the pool timeout using thehttp_pool_timeoutoption. The default value if you do not provide one isDefaultHttpPoolTimeout(5 seconds).fromdatetimeimporttimedeltafromfauna.clientimportClientclient=Client(http_pool_timeout=timedelta(seconds=6))Read TimeoutThe read timeout specifies the maximum amount of time, asdatetime.timedelta, to wait for a chunk of data to be received (for example, a chunk of the response body). If the client is unable to receive data within this time frame, aReadTimeoutexception is raised.Configure the read timeout using thehttp_read_timeoutoption. The default value if you do not provide one isDefaultHttpReadTimeout(None).fromdatetimeimporttimedeltafromfauna.clientimportClientclient=Client(http_read_timeout=timedelta(seconds=6))Write TimeoutThe write timeout specifies the maximum amount of time, asdatetime.timedelta, to wait for a chunk of data to be sent (for example, a chunk of the request body). If the client is unable to send data within this time frame, aWriteTimeoutexception is raised.Configure the write timeout using thehttp_write_timeoutoption. The default value if you do not provide one isDefaultHttpWriteTimeout(5 seconds).fromdatetimeimporttimedeltafromfauna.clientimportClientclient=Client(http_write_timeout=timedelta(seconds=6))Query StatsStats are returned on query responses and ServiceErrors.fromfaunaimportfqlfromfauna.clientimportClientfromfauna.encodingimportQuerySuccess,QueryStatsfromfauna.errorsimportServiceErrorclient=Client()defemit_stats(stats:QueryStats):print(f"Compute Ops:{stats.compute_ops}")print(f"Read Ops:{stats.read_ops}")print(f"Write Ops:{stats.write_ops}")try:q=fql('Collection.create({ name: "Dogs" })')qs:QuerySuccess=client.query(q)emit_stats(qs.stats)exceptServiceErrorase:ife.statsisnotNone:emit_stats(e.stats)# more error handling...Document StreamingNot implementedSetup$virtualenvvenv$sourcevenv/bin/activate$pipinstall..[test].[lint]TestingWe use pytest. You can run tests directly or with docker. If you run integration tests directly, you must have fauna running locally.If you want to run fauna, then run integration tests separately:$makerun-fauna$sourcevenv/bin/activate$makeinstall$makeintegration-testTo run unit tests locally:$sourcevenv/bin/activate$makeinstall$makeunit-testTo stand up a container and run all tests at the same time:$makedocker-testSee theMakefilefor more.Coverage$sourcevenv/bin/activate$makecoverageContributeGitHub pull requests are very welcome.LicenseCopyright 2023Fauna, 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 can obtain a copy of the License athttp://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.