0

我正在将 google.cloud.firestore 与 Async Client 一起使用,并且我想添加超时设置以添加文档,但我无法以某种方式...

版本

  • 蟒蛇:3.9.7
  • google-cloud-firestore: ">=2.1.0"
  • API 框架:fastapi: "^0.70.0"
  • pytest:“^6.2.5”
  • pytest-asyncio:“^0.16.0”

问题

当我运行此代码时without setting firebase server turning on

from firebase_admin import firestore
db_client = firestore.AsyncClient()

async def some_function():
  await asyncio.wait_for(
    db.collection('states')
      .add({'some':'values'})
    ,timeout=10
  )

这应该会导致错误only after when 10 secs已经过去,但实际上这会导致错误提示immidiately

503 failed to connect to all addresses

我该如何解决db.collection('states').add(...)以适当地等待?

谢谢!

4

1 回答 1

1

First, you should check if there are any networking settings blocking connections. 503 means the library is unable to make a connection with the backend API. Now coming to Firestore timeout values, there is no way to adjust that. The timeout requests defaults to a system specified value as per this.

Write operations never time out, and they never fail due to loss of network. You should not think of Firestore reads and writes as typical input and output operations. Data written to Firestore is eventually synchronized, which will happen whenever it's possible to do so.

Unlike in Firebase Realtime database where to enable offline persistence, you have to do the following :

FirebaseDatabase.getInstance().setPersistenceEnabled(true);

In Cloud Firestore, offline persistence is enabled by default. So, there is no need to use: setPersistenceEnabled(true). When you are offline the result will be from the cached copy of the Cloud Firestore data that your app is actively using. To check if the data is from cache or from Firestore servers, you can use the following line of code:

String source = querySnapshot.getMetadata().isFromCache() ? "Local Cache" : "Firebase Servers”

Documents written in Firestore are saved locally immediately if not executed, until they are able to be synchronized with the server, which could be any time in the future.

// Add a new document with a generated id.

Map<String, Object> data = new HashMap<>(); 
data.put("name", "Tokyo"); 
data.put("country", "Japan"); 
db.collection("cities") .add(data) .addOnSuccessListener(
new OnSuccessListener<DocumentReference>() { 
@Override public void onSuccess(DocumentReference documentReference) 
{ Log.d(TAG, "DocumentSnapshot written with ID: " + documentReference.getId()); 
} })
 .addOnFailureListener(new OnFailureListener() { 
@Override public void onFailure(@NonNull Exception e) 
{ Log.w(TAG, "Error adding document", e); 
} });

Note : The onSuccess or onFailure will only be called if there is a connection to the server. The only exception to this is transaction operations, which require a network to complete.

However there is a request in the Python client library for Firestore asking for this improvement. Also have a look at this for reference.

于 2021-11-16T06:12:15.197 回答