def test_collections_w_import(): from google.cloud import firestore client = firestore.Client() collections = list(client.collections()) assert isinstance(collections, list)
def handler(request): '''Returns data from a firestore query.''' arguments = dict(request.args) arguments.pop('key', None) path = request.view_args['path'] collection = path.split('/')[1] db = firestore_v1.Client() q = db.collection(collection) max = int(os.getenv('MAX', 3000)) page_size = int(arguments.pop('page_size', max)) if page_size > max: page_size = max q = q.limit(page_size) if arguments.get('next_cursor'): id = arguments.pop('next_cursor') snapshot = db.collection(collection).document(id).get() logging.info(f'Starting query at cursor: {id}') if snapshot: q = q.start_after(snapshot) # Return filtered documents with IN query multi = request.args.to_dict(flat=False) for field, values in multi.items(): if len(values) > 1: logging.info(f'Filtering {field} in {values}') q = q.where(field, 'in', values) arguments.pop(field, None) # Return filtered documents for field, value in arguments.items(): logging.info(f'Filtering {field} == {value}') q = q.where(field, '==', value) docs = q.stream() results = [] for doc in docs: results.append(doc.to_dict()) next = '' size = len(results) if results and (page_size == size): next = f'/{collection}?next_cursor={doc.id}&page_size={page_size}' for field, value in arguments.items(): next = next + f'&{field}={value}' logging.info(f'Returning {size} record(s)!') response = { 'status': 'success', 'page_size': size, 'max': max, 'next': next, 'results': results } return make_response(jsonify(response), 200, {'cache-control': 'private, max-age=3600, s-maxage=3600'})
def test_collections_w_import(): from google.cloud import firestore credentials, project = _get_credentials_and_project() client = firestore.Client(project=project, credentials=credentials) collections = list(client.collections()) assert isinstance(collections, list)
def get_user(mail): db = firestore.Client() docs = db.collection(USERS).where(u'Mail', u'==', mail).stream() for doc in docs: # returns the first object return doc.to_dict() return None
def client(): if FIRESTORE_EMULATOR: credentials = EmulatorCreds() project = FIRESTORE_PROJECT else: credentials = service_account.Credentials.from_service_account_file( FIRESTORE_CREDS) project = FIRESTORE_PROJECT or credentials.project_id yield firestore.Client(project=project, credentials=credentials)
def test_cannot_use_foreign_key(client, cleanup): document_id = "cannot" + UNIQUE_RESOURCE_ID document = client.document("foreign-key", document_id) # Add to clean-up before API request (in case ``create()`` fails). cleanup(document.delete) other_client = firestore.Client(project="other-prahj", credentials=client._credentials, database="dee-bee") assert other_client._database_string != client._database_string fake_doc = other_client.document("foo", "bar") with pytest.raises(InvalidArgument): document.create({"ref": fake_doc})
def create_user(mail, pwd, institution, phone, name, surname): doc = get_user(mail) if doc is not None: # todo throw exception here print('User already exist') else: db = firestore.Client() db.collection(USERS).add({ u'Mail': mail, u'Password': encrypt_password(pwd), u'Phone': phone, u'Name': name, u'Surname': surname, u'Institution': institution, })
def local_api(url): """Returns data from a firestore query.""" parsed_url = urlparse(url) query = {key: value[0] for key, value in parse_qs(parsed_url.query).items()} path = parsed_url.path collection = path.split("/")[1] db = firestore_v1.Client() q = db.collection(collection) max = int(os.getenv("MAX", 3000)) page_size = int(query.pop("page_size", max)) if page_size > max: page_size = max q = q.limit(page_size) if query.get("next_cursor"): id = query.pop("next_cursor") snapshot = db.collection(collection).document(id).get() logging.info(f"Starting query at cursor: {id}") if snapshot: q = q.start_after(snapshot) # Return filtered documents for field, value in query.items(): logging.info(f"Filtering {field} == {value}") q = q.where(field, "==", value) docs = q.stream() results = [] for doc in docs: results.append(doc.to_dict()) next = "" size = len(results) if results and (page_size == size): next = f"/{collection}?next_cursor={doc.id}&page_size={page_size}" for field, value in query.items(): next = next + f"&{field}={value}" logging.info(f"Returning {size} record(s)!") return results
def client(): credentials = service_account.Credentials.from_service_account_file( FIRESTORE_CREDS) project = FIRESTORE_PROJECT or credentials.project_id yield firestore.Client(project=project, credentials=credentials)
from datetime import datetime, timezone from google.cloud import firestore_v1 as firestore from ib_insync import Contract, util import logging from os import environ # get environment variables K_REVISION = environ.get('K_REVISION', default='localhost') # instantiate Firestore Client db = firestore.Client() def main(ib_gw, trading_mode): # query config config = db.collection('config').document(trading_mode).get().to_dict() # activity log for Firestore activity_log = { 'agent': K_REVISION, 'config': config, 'exception': None, 'tradingMode': trading_mode } main_e = None try: # log open orders/trades activity_log['openOrders'] = [{ 'contract': t.contract.nonDefaults(),
def client(): credentials, project = _get_credentials_and_project() yield firestore.Client(project=project, credentials=credentials)
import datetime import json import logging import sys from google.cloud import firestore_v1 from isodate import parse_duration logging.getLogger().setLevel(logging.INFO) catalog = json.load(open(sys.argv[1], "r")) firestore_client = firestore_v1.Client() def get_temporal_in_days(temporal): """ Transform a temporal to days :param temporal: Temporal in ISO 8601 format :type temporal: str :return: Temporal in days :rtype: int """ if temporal and temporal.startswith("P"): duration = parse_duration(temporal) return duration.days return None
# You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-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. import threading import time import os from google.cloud import firestore_v1 db = firestore_v1.Client() # Create an Event for notifying main thread. callback_done = threading.Event() # Create a callback on_snapshot function to capture changes def on_snapshot(doc_snapshot, changes, read_time): os.system('clear') for doc in doc_snapshot: print(f'Product id: {doc.id} {doc.to_dict()}') callback_done.set() doc_ref = db.collection(u'app')
from time import sleep from google.cloud import firestore_v1 import firebase_admin from firebase_admin import credentials import sys import os # -------------------------------------------------------------------- cred = credentials.Certificate( "D:/Google/organic-palace-306416-firebase-adminsdk-23tbh-ded810a1c3.json") firebase_admin.initialize_app(cred) # First attempt # Add a new document: GOOGLE_APPLICATION_CREDENTIALS=D:\Google\My First Project-cadc535bd037.json db = firestore_v1.Client(project='organic-palace-306416') doc_ref = db.collection(u'users').document(u'alovelace') doc_ref.set({ u'first': u'Ada', u'last': u'Lovelace', u'born': 1815, u'age': 15, u'favorites': { u'food': u'Steak', u'color': u'Blue', u'subject': u'Recess' }, u'department': u'FIN' })