To deploy a simple Python function on Firebase, you can use Firebase Cloud Functions. Firebase Cloud Functions allow you to run backend code in response to events triggered by Firebase features or HTTPS requests. Here's a step-by-step guide to deploying a Python function on Firebase:
Prerequisites
- Node.js installed on your machine.
-
Firebase CLI installed (
npm install -g firebase-tools
). - A Firebase project created in the Firebase Console.
- Python 3.7+ installed.
- Docker installed (required for running Python in Firebase Cloud Functions).
Steps to Deploy a Python Function on Firebase
1. Install Firebase CLI and Log In
If you haven't already, install the Firebase CLI and log in to your Firebase account:
npm install -g firebase-tools
firebase login
2. Initialize a Firebase Project
Create a new directory for your project and initialize Firebase:
mkdir my-python-firebase-function
cd my-python-firebase-function
firebase init functions
- Select Cloud Functions when prompted.
- Choose your Firebase project.
- Select JavaScript as the language (we'll modify this later).
3. Set Up Python Runtime
Firebase Cloud Functions natively support JavaScript, but you can use Python by leveraging the Docker runtime. Update the functions/package.json
file to include the following:
{
"name": "functions",
"engines": {
"node": "16"
},
"main": "index.js",
"dependencies": {
"firebase-functions": "^4.0.0",
"firebase-admin": "^11.0.0"
}
}
4. Create a Dockerfile
In the functions
directory, create a Dockerfile
to define the Python runtime:
# Use the official Python image
FROM python:3.9-slim
# Set the working directory
WORKDIR /usr/src/app
# Copy the Python script
COPY . .
# Install dependencies
RUN pip install --no-cache-dir -r requirements.txt
# Expose the port
EXPOSE 8080
# Run the Python script
CMD ["python", "main.py"]
5. Write Your Python Function
Create a main.py
file in the functions
directory with your Python code:
from flask import Flask, request
app = Flask(__name__)
@app.route('/')
def hello_world():
return 'Hello, Firebase with Python!'
if __name__ == '__main__':
app.run(host='0.0.0.0', port=8080)
6. Create a requirements.txt
File
Add the required Python dependencies to functions/requirements.txt
:
Flask==2.0.1
7. Deploy the Function
Deploy your function to Firebase:
firebase deploy --only functions
8. Test the Function
Once deployed, Firebase will provide a URL for your function. Open it in your browser or use curl
to test:
curl https://<your-region>-<your-project-id>.cloudfunctions.net/<function-name>
Notes
- Firebase Cloud Functions with Python require Docker and are more complex than JavaScript-based functions.
- Ensure your Dockerfile and Python code are correctly configured.
- Firebase Cloud Functions have a free tier, but usage beyond that may incur costs.
For more details, refer to the Firebase Cloud Functions Documentation.
Top comments (0)