Exemple #1
0
    def on_create(self, snapshot: DocumentSnapshot, transaction):
        """ Invoked when a new instance of UserSublocation is created
                in firestore.

        TODO: check concurrency issues when running async functions
            in parallel; see if context var can be overriden when
            awaiting another task

        :param snapshot:
        :param transaction:
        :return:
        """

        doc_ref = snapshot.reference
        # Do a redundant get to register document to transaction
        _ = transaction.get(doc_ref)

        # user_id = doc_ref.parent.parent.parent.parent.id
        doc_id = doc_ref.id
        user_location_id = doc_ref.parent.parent.id
        form = UserSublocationForm.new(user_location_id=user_location_id,
                                       doc_id=doc_id)
        form.update_vals(with_raw=snapshot.to_dict())
        self.notify(obj=form)
        snapshot.reference.delete()
Exemple #2
0
def test_document_from_snapshot():
    client = object()
    reference = Mock(id=DOC_ID)
    snapshot = DocumentSnapshot(reference, mock_data(), True, None, None, None)
    doc = Document1._from_firestore_snapshot(snapshot, firestore_client=client)
    assert doc.__firestore__.client == client
    assert doc.dict() == mock_data(with_id=True)
def DocumentWrapper(snapshot: DocumentSnapshot) -> AttrDict:
    """
    A wrapper around a Firestore DocumentSnapshot,
    to bring a Django-Model-esque API to a Snapshot
    and make it compatible with custom Serializer Fields.
    """
    wrapper = AttrDict()
    wrapper["_snapshot"] = snapshot
    wrapper["reference"] = snapshot.reference
    wrapper["id"] = snapshot.id
    wrapper["pk"] = snapshot.id

    snapshot_data = snapshot.to_dict()
    if not snapshot_data:
        return wrapper

    def _wrap(data: dict, ad: AttrDict) -> AttrDict:
        """ Recursively wrap objects (dicts) as AttrDicts. """
        for k, v in data.items():
            if isinstance(v, dict):
                ad[k] = _wrap(v, AttrDict())
            else:
                ad[k] = v
        return ad

    for key, value in snapshot_data.items():
        if isinstance(value, dict):
            wrapper[key] = _wrap(value, AttrDict())
        else:
            wrapper[key] = value

    return wrapper
Exemple #4
0
 def on_create(snapshot: DocumentSnapshot, mediator):
     doc_ref = snapshot.reference
     user_id = doc_ref.parent.parent.id
     doc_id = doc_ref.id
     form = UserLocationForm.new(user_id=user_id, doc_id=doc_id)
     form.update_vals(with_raw=snapshot.to_dict())
     mediator.notify(obj=form)
     snapshot.reference.delete()
Exemple #5
0
def test_document_get():
    with patch("pyrodantic.document.DocumentReference") as MockDocRef:
        reference = Mock(id="doc-id")
        data = {"str_attr": "foo", "int_attr": 1}
        mock_doc = Mock()
        mock_doc.get.return_value = DocumentSnapshot(reference, data, True,
                                                     None, None, None)
        MockDocRef.return_value = mock_doc
        doc = Document1.get("doc-id", firestore_client=None)
        data["doc_id"] = "doc-id"
        assert doc.dict() == data
Exemple #6
0
 def make_mock_snap(cmd: Command) -> DocumentSnapshot:
     ref = AsyncDocumentReference(*cmd.document_path.split("/"))
     # noinspection PyTypeChecker
     snap = DocumentSnapshot(
         reference=ref,
         data=cmd.to_snap(),
         exists=True,
         read_time=None,
         create_time=None,
         update_time=None,
     )
     return snap
Exemple #7
0
    def _from_firestore_document(
        cls: Type[_DocumentSubclassTypeVar],
        firestore_document: firestore_v1.DocumentSnapshot
    ) -> _DocumentSubclassTypeVar:
        """Convert a document as returned by the Firestore client to the corresponding fireclass.Document instance.
        """
        decoded_dict = {}
        for field_name, value in firestore_document.to_dict().items():
            field_description = cls._find_field(field_name)
            decoded_dict[field_name] = convert_value_from_firestore(
                value, field_description)

        document = cls(**decoded_dict)  # type: ignore
        document._id = firestore_document.id
        return document
Exemple #8
0
def parse_cursor(cursor, client):
    from google.cloud.firestore_v1 import DocumentReference
    from google.cloud.firestore_v1 import DocumentSnapshot

    if "doc_snapshot" in cursor:
        path = parse_path(cursor.doc_snapshot.path)
        doc_ref = DocumentReference(*path, client=client)

        return DocumentSnapshot(
            reference=doc_ref,
            data=json.loads(cursor.doc_snapshot.json_data),
            exists=True,
            read_time=None,
            create_time=None,
            update_time=None,
        )

    values = [json.loads(value) for value in cursor.json_values]
    return convert_data(values)
Exemple #9
0
def mock_snapshot(exists=True):
    reference = Mock(id=DOC_ID)
    return DocumentSnapshot(reference, mock_data(), exists, None, None, None)
Exemple #10
0
 def _from_firestore_snapshot(
     cls, snapshot: DocumentSnapshot, *, firestore_client: FirestoreClient
 ) -> _DocumentSubclassTypeVar:
     data = snapshot.to_dict()
     data[cls.__firestore__.id_attr] = snapshot.id
     return cls(firestore_client, **data)
Exemple #11
0
def get_events(doc: DocumentSnapshot) -> list:
    try:
        return doc.to_dict()["events"]
    except (KeyError, TypeError) as e:
        print(e)
        return []