Hey there, fellow Python enthusiast! Ready to dive into the world of Firestore? You're in for a treat. Firestore is Google's flexible, scalable NoSQL cloud database, and today we're going to walk through integrating it into your Python project. Buckle up!
Before we jump in, make sure you've got:
google-cloud-firestore
library (pip install google-cloud-firestore
)Got all that? Great! Let's roll.
First things first, we need to get you authenticated. Head over to your Google Cloud Console, create a service account, and download the JSON key file. Easy peasy.
Now, set an environment variable to point to your key file:
export GOOGLE_APPLICATION_CREDENTIALS="/path/to/your/keyfile.json"
Time to get our hands dirty with some code:
from google.cloud import firestore db = firestore.Client()
Boom! You're connected. How's that for simple?
Let's add some data:
doc_ref = db.collection('users').document('alovelace') doc_ref.set({ 'first': 'Ada', 'last': 'Lovelace', 'born': 1815 })
Reading is just as easy:
doc = doc_ref.get() print(f'Document data: {doc.to_dict()}')
Need to make changes? No sweat:
doc_ref.update({'born': 1816})
And when it's time to say goodbye:
doc_ref.delete()
Let's step it up a notch:
users_ref = db.collection('users') # Get all users born before 1900 docs = users_ref.where('born', '<', 1900).stream() for doc in docs: print(f'{doc.id} => {doc.to_dict()}')
Subcollections? We've got you covered:
doc_ref = db.collection('rooms').document('roomA') message_ref = doc_ref.collection('messages').document('message1') message_ref.set({'text': 'Hello, World!'})
Want to keep things fresh? Try this on for size:
def on_snapshot(doc_snapshot, changes, read_time): for doc in doc_snapshot: print(f'Received document snapshot: {doc.id}') doc_ref = db.collection('cities').document('SF') doc_watch = doc_ref.on_snapshot(on_snapshot)
Remember, always wrap your Firestore calls in try-except blocks. And for the love of all things Pythonic, use batch writes for multiple operations!
batch = db.batch() # ... add your operations to the batch batch.commit()
And there you have it! You're now armed and dangerous with Firestore knowledge. Go forth and build amazing things!
Remember, the official Firestore documentation is your best friend for diving deeper. Happy coding!