Search code examples
pythongoogle-app-enginegoogle-cloud-platformgoogle-cloud-datastore

Google App Engine on startup autofill initial data in google data store


I have a Google App Engine Python application. I am using google datastore as a database to server dynamic contents. I want to autofill some data in google datastore while starting the google app engine application.

To start the application I am using

dev_appserver.py app.yaml

I have a python script to autofill initial data but did not know how to configure that script to run once while starting the application.

Moreover, I have built the website using webapp2 with jinja2 templating.


Solution

  • To make this work in the dev environment, the simplest thing to do is to run code in your appengine_config.py file (if you don't have such a file, create it in the top level of your application, in the same folder as app.yaml).

    # Make this the last item in app.yaml - set up vendoring etc first.
    
    from models import FooModel
    
    # Delete existing records
    keys = FooModel.query().fetch(keys_only=True)
    ndb.delete_multi(keys)
    
    data = get_data_from_somewhere()
    
    # Assumes data is an iterable of dicts
    entities = [FooModel(**item) for item in data]
    ndb.put_multi(entities)
    

    Understand that this approach will not work reliably in the cloud. This is because in the cloud there may be multiples instances of your application starting and stopping all the time. It's best to design your app so that the datastore does not need to be reinitialised on instance startup (or even after each deployment).