To connect to Cloud Datastore from your Flask app deployed to Cloud Run...
- Ensure you've got both services enabled in a project with an active billing account.
- Ensure you've got at least both Flask & Datastore packages in your
requirements.txt
file (w/any desired versioning):
flask
google-cloud-datastore
- Integrate Datastore usage into your app... here's some sample usage in my demo
main.py
(Flask code dropped for simplicity):
from google.cloud import datastore
ds_client = datastore.Client()
KEY_TYPE = 'Record'
def insert(**data):
entity = datastore.Entity(key=ds_client.key(KEY_TYPE))
entity.update(**data) ## where data = dict/JSON of key-value pairs
ds_client.put(entity)
def query(limit):
return ds_client.query(kind=KEY_TYPE).fetch(limit=limit)
- You can have a
Dockerfile
(minimal one below), but better yet, skip it and let Google (Cloud Buildpacks) build your container for you so you don't have extra stuff like this to worry about.
FROM python:3-slim
WORKDIR /app
COPY . .
RUN pip install -r requirements.txt
CMD ["python", "main.py"]
- Come up with an app/service name
SVC_NAME
then build & deploy your prototype container with gcloud beta run deploy SVC_NAME --source . --platform managed --allow-unauthenticated
. (Think docker build
followed by docker push
and then docker run
, all from 1 command!) If you have a Dockerfile
, Buildpacks will use it, but if not, it'll introspect your code and dependencies to build the most efficient container it can.
That's it. Some of you will get distracted by service accounts and making a public/private key-pair, both of which are fine. However to keep things simple, especially during prototyping, just use the default service account you get for free on Cloud Run. The snippet above works without any service account or IAM code present.
BTW, the above is for a prototype to get you going. If you were deploying to production, you wouldn't use the Flask dev server. You'd probably add gunicorn
to your requirements.txt
and Dockerfile
, and you'd probably create a unique service account key w/specific IAM permissions, perhaps adding other requirements like IAP, VPC, and/or a load-balancer.