I have an Firebase Cloud Functions codebase that uses Firestore database. Everything below works when I use it in local emulator using firebase emulators:start
but when I need to deploy it to Firebase I got below error:
Error: User code failed to load. Cannot determine backend specification
main.py
import json
from firebase_functions import https_fn
from firebase_admin import initialize_app, firestore
import flask
from enum import Enum
from flask import g
from endpoints.moon_phase import moon_phase_bp
# Initialize Firebase app and Firestore
initialize_app()
db = firestore.client()
app = flask.Flask(__name__)
# Set up a before_request function to make db available in blueprints
@app.before_request
def before_request():
# g.db = db
print("before_request")
app.register_blueprint(moon_phase_bp) //Doesn't even use db, but in the future it will.
# Firebase Function to handle requests
@https_fn.on_request()
def astro(req: https_fn.Request) -> https_fn.Response:
with app.request_context(req.environ):
return app.full_dispatch_request()
If I update the db initialisation to db = firestore.client
it deploys, but obviously, it's a function reference, so I cannot use Firestore db in my endpoints. This also means it's not related to my Firebase credentials or project setup.
What might be the issue here?
Figured out the below answer in the Firebase repo fixes the issue:
I've discovered if I move the db = firestore.client() into my cloud function, I'm able to deploy.
https://github.com/firebase/firebase-functions-python/issues/126#issuecomment-1682542027
It's really weird that Google does not update the docs or fixes the issue, but for now, this answer unblocks me, hope it helps others too.