Handling sessions with Firestore

Many apps need session handling for authentication and user preferences. The Flask framework comes with a memory-based implementation to perform this function. However, this implementation is unsuitable for an app that can be served from multiple instances, because the session that is recorded in one instance might differ from other instances. This tutorial shows how to handle sessions on App Engine.

Objectives

  • Write the app.
  • Run the app locally.
  • Deploy the app on App Engine.

Costs

This tutorial uses the following billable components of Google Cloud:

To generate a cost estimate based on your projected usage, use the pricing calculator. New Google Cloud users might be eligible for a free trial.

When you finish this tutorial, you can avoid continued billing by deleting the resources you created. For more information, see Cleaning up.

Before you begin

  1. Sign in to your Google Account.

    If you don't already have one, sign up for a new account.

  2. In the Google Cloud Console, on the project selector page, select or create a Google Cloud project.

    Go to the project selector page

  3. Make sure that billing is enabled for your Cloud project. Learn how to confirm that billing is enabled for your project.

  4. Enable the Firestore API.

    Enable the API

  5. Install and initialize the Cloud SDK.
  6. Install Python, pip, and virtualenv on your system. For instructions, see Setting up a Python development environment for Google Cloud.

Setting up the project

  1. In your terminal window, start in a directory of your choosing and create a new directory named sessions. All of the code for this tutorial is inside the sessions directory.

  2. Change into the sessions directory:

    cd sessions
    
  3. Create the requirements.txt with the following contents:

    google-cloud-firestore==2.0.1
    flask==1.1.2
    
  4. Install the dependencies:

    pip install  -r requirements.txt
    

At the end of this tutorial, the final file structure is similar to the following:

sessions
├── app.yaml
├── main.py
└── requirements.txt

Writing the web app

This app displays greetings in different languages for every user. Returning users are always greeted in the same language.

Multiple app windows displaying a greeting in different languages.

Before your app can store preferences for a user, you need a way to store information about the current user in a session. This sample app uses Firestore to store session data.

  • In your terminal window, create a file called main.py with the following content:

    import random
    from uuid import uuid4
    
    from flask import Flask, make_response, request
    from google.cloud import firestore
    
    
    app = Flask(__name__)
    db = firestore.Client()
    sessions = db.collection('sessions')
    greetings = [
        'Hello World',
        'Hallo Welt',
        'Ciao Mondo',
        'Salut le Monde',
        'Hola Mundo',
    ]
    
    
    @firestore.transactional
    def get_session_data(transaction, session_id):
        """ Looks up (or creates) the session with the given session_id.
            Creates a random session_id if none is provided. Increments
            the number of views in this session. Updates are done in a
            transaction to make sure no saved increments are overwritten.
        """
        if session_id is None:
            session_id = str(uuid4())   # Random, unique identifier
    
        doc_ref = sessions.document(document_id=session_id)
        doc = doc_ref.get(transaction=transaction)
        if doc.exists:
            session = doc.to_dict()
        else:
            session = {
                'greeting': random.choice(greetings),
                'views': 0
            }
    
        session['views'] += 1   # This counts as a view
        transaction.set(doc_ref, session)
    
        session['session_id'] = session_id
        return session
    
    
    @app.route('/', methods=['GET'])
    def home():
        template = '<body>{} views for "{}"</body>'
    
        transaction = db.transaction()
        session = get_session_data(transaction, request.cookies.get('session_id'))
    
        resp = make_response(template.format(
            session['views'],
            session['greeting']
            )
        )
        resp.set_cookie('session_id', session['session_id'], httponly=True)
        return resp
    
    
    if __name__ == '__main__':
        app.run(host='127.0.0.1', port=8080)
  • The following diagram illustrates how Firestore handles sessions for the App Engine app.

    Diagram of architecture: user, App Engine, Firestore.

After you've set app.use(session), every request has a req.session property that you can use to identify recurring users. The session data is stored in Firestore.

Deleting sessions

You can delete session data or implement an automated deletion strategy. If you use storage solutions for sessions such as Memcache or Redis, expired sessions are automatically deleted.

Running locally

  1. In your terminal window, install the Gunicorn HTTP server:

    pip install gunicorn
    
  2. Run the Gunicorn HTTP server:

    gunicorn -b :8080 main:app
    
  3. View the app in your web browser:

    Cloud Shell

    In the Cloud Shell toolbar, click Web preview Web preview and select Preview on port 8080.

    Local machine

    In your browser, go to http://localhost:8080

    You see one of five greetings: "Hello World", "Hallo Welt", "Hola mundo", "Salut le Monde", or "Ciao Mondo." The language changes if you open the page in a different browser or in incognito mode. You can see and edit the session data in the Google Cloud Console.

    Firestore sessions in Cloud Console.

  4. To stop the HTTP server, in your terminal window, press Control+C.

Deploying and running on App Engine

You can use the App Engine standard environment to build and deploy an app that runs reliably under heavy load and with large amounts of data.

This tutorial uses the App Engine standard environment to deploy the server.

  1. In your terminal window, create an app.yaml file and copy the following:

    runtime: python37
  2. Deploy the app on App Engine:

    gcloud app deploy
    
  3. View the live app at https://your-project-id.appspot.com:

    gcloud app browse
    

    Where your-project-id is your Google Cloud project ID.

The greeting is now delivered by a web server running on an App Engine instance.

Debugging the app

If you cannot connect to your App Engine app, check the following:

  1. Check that the gcloud deploy commands successfully completed and didn't output any errors. If there were errors (for example, message=Build failed), fix them, and try deploying the App Engine app again.
  2. In the Cloud Console, go to the Logs Viewer page.

    Go to Logs Viewer page

    1. In the Recently selected resources drop-down list, click App Engine Application, and then click All module_id. You see a list of requests from when you visited your app. If you don't see a list of requests, confirm you selected All module_id from the drop-down list. If you see error messages printed to the Cloud Console, check that your app's code matches the code in the section about writing the web app.

    2. Make sure that the Firestore API is enabled.

Cleaning up

Delete the project

  1. In the Cloud Console, go to the Manage resources page.

    Go to Manage resources

  2. In the project list, select the project that you want to delete, and then click Delete.
  3. In the dialog, type the project ID, and then click Shut down to delete the project.

Delete the App Engine instance

  1. In the Cloud Console, go to the Versions page for App Engine.

    Go to the Versions page

  2. Select the checkbox for the non-default app version you want to delete.
  3. Click Delete to delete the app version.

What's next