Search code examples
pythongoogle-cloud-run

Python session on Google Cloud Run automatically logs out


I am running a website on Google Cloud Run that I have written in Python. The site runs in a Docker image that uses python:latest. The code works, however after some time the user is logged out and I dont know why the session does not lasts.

main.py:

"""
Main
File: main.py
Updated: 23.10.2022 Ditlefsen
"""
import os

import flask
from flask import request, session

# Flask
app = flask.Flask(__name__)
app.secret_key = os.urandom(12)


# - Index ------------------------------------------------------------------------------
@app.route('/', methods=['GET', 'POST'])
def __index():

    # Login user
    if not session.get('logged_in'):
        request_form_global = request.form

        inp_username = request_form_global['inp_username']
        inp_password = request_form_global['inp_password']
        
        if inp_username == "hello" and inp_password == "world":
            session['logged_in'] = True
            

    if session.get('logged_in'):
        return "Welcome to the website", 200
    else:
        return "Access denied!", 304


# - Main ----------------------------------------------------------------------
def main(function_request: flask.wrappers.Request = None):
    app.run(debug=False, host="0.0.0.0", port=8080)

if __name__ == '__main__':
    main()

Dockerfile:

# Specify Python
FROM python:latest

ENV PYTHONDONTWRITEBYTECODE 1
ENV PYTHONUNBUFFERED 1

# Open port
EXPOSE 8080

# Add Python script
RUN mkdir /app
WORKDIR /app
COPY . .


# Install dependencies
RUN pip install -r requirements.txt

# Set Pythons path
ENV PYTHONPATH /app

# Run script
CMD [ "python", "./main.py" ]

requirements.txt:

cloud-sql-python-connector
flask
flask-cors
google-cloud-secret-manager
google
google-api-python-client
PyYAML
psycopg2-binary
pg8000
sqlalchemy==1.4.46
requests



flask-login
passlib
Werkzeug

What can I do to keep the user logged in?


Solution

    • Does your user remain logged in if you test your code locally?
    • What is the delay before being logged out? My guess is that your Google Cloud Run service is shut off after a while, depending on your subscription and/or parameters (see quotas here)