Cloud Functions
Create serverless backend logic with full database access, request handling, and real-time capabilities using Python cloud functions.What Are Cloud Functions?
Cloud functions are serverless Python functions that run in the cloud. They provide:- Full Database Access - Query and modify your data using the powerful Database API
- HTTP Request Handling - Process GET/POST requests with query parameters and JSON payloads
- HTML Rendering - Return dynamic HTML pages with Jinja2 templates
- Email Integration - Send emails directly from your functions
- Environment Context - Access user authentication, project info, and more
When to Use Cloud Functions
- Custom API Endpoints - Build custom backend logic without deploying servers
- Data Processing - Transform, aggregate, or validate data before storing
- Dynamic Web Pages - Render server-side HTML with real-time data
- Webhooks - Handle webhook events from external services
- Scheduled Tasks - Run background jobs and cron tasks
- Email Notifications - Send automated emails based on events
Getting Started
Basic Function Structure
Every cloud function has amain() function that serves as the entry point:
Execution URL
Each cloud function gets a unique execution URL:Database API Access
Thedb object provides full access to your database. It’s automatically available in all cloud functions.
Query Documents
Query with Filters
Get Single Document
Create Documents
Update Documents
Delete Documents
Request and Response Handling
The Request Object
Access incoming request data with therequest object (also available as req):
Response Types
JSON Response (Default)Error Handling
Environment Variables
Access environment and project information:Execution Context
User Authentication
Access authenticated user data:HTTP Methods
Route based on HTTP method:Database Queries in Cloud Functions
Comparison Operators
Use operator suffixes to filter data:| Operator | Suffix | Example | Description |
|---|---|---|---|
| Equal | (none) or _eq | status="published" | Exact match |
| Not Equal | _ne | status_ne="draft" | Not equal |
| Greater Than | _gt | price_gt="100" | Greater than |
| Greater or Equal | _gte | age_gte="18" | Greater than or equal |
| Less Than | _lt | price_lt="1000" | Less than |
| Less or Equal | _lte | stock_lte="10" | Less than or equal |
| Contains | _contains | title_contains="python" | String contains |
| Starts With | _startswith | name_startswith="john" | String starts with |
| Ends With | _endswith | email_endswith="@gmail.com" | String ends with |
| In Array | _in | status_in="published,draft" | Value in list |
| Not In Array | _notin | category_notin="spam,nsfw" | Value not in list |
| Is Null | _isnull | deleted_at_isnull="true" | Check if null |
Boolean Logic - OR Queries
Simple OR:Relationships and Population
Auto-Relationship Detection: Relationships are automatically detected based on field naming:{field}id- Single reference{field}_ids- Multiple references
User Queries
Query users with the same powerful features:User Relationships
Manage relationships between users:Operators and Filtering
Text Search
Range Queries
List Filtering
Null Checks
Sorting and Pagination
Real-World Examples
E-Commerce: Product Search
Social Media: User Feed
CMS: Blog Search
User Dashboard
Dynamic Web Page
Best Practices
1. Always Use Limits
2. Use Indexes for Performance
3. Selective Population
4. Clear Field Naming
5. Handle Pagination
6. Error Handling
7. Validate Input
Intellisense Setup
Monaco Editor Integration
Enable IntelliSense for cloud functions in your code editor: Install Dependencies:Available Endpoints
Your backend provides IntelliSense data:GET /intellisense/python-stubs- Type definitions forrequest,db,renderobjectsGET /intellisense/python-examples- Code examples and patternsGET /intellisense/operators- Query operator documentation
Features Provided
- Autocomplete - Type
request.,db., orrender.to see available methods - Code Snippets - Quick templates for common patterns
- Hover Documentation - Hover over globals to see documentation
- Examples Toolbar - One-click insertion of complete code patterns
Available Python Modules
Cloud functions have access to these Python standard library modules without import statements:| Module | Description | Common Uses |
|---|---|---|
json | JSON encoding/decoding | Parse API responses, serialize data |
datetime | Date and time class | Current time, timestamps |
timedelta | Time duration class | Add/subtract time, expiration |
time | Time utilities | Delays, timestamps, timing |
math | Mathematical functions | Calculations, rounding |
re | Regular expressions | Pattern matching, validation |
secrets | Cryptographically secure random | OTP generation, tokens, passwords |
uuid | UUID generation | Unique identifiers |
hashlib | Hash functions | MD5, SHA256, data integrity |
base64 | Base64 encoding | Encode/decode binary data |
string | String constants | ASCII letters, digits, punctuation |
collections | Data structures | Counter, defaultdict, deque |
Examples
OTP Generation (Secure):Next Steps
- Querying - Master advanced query techniques
- Real-time - Add live data synchronization
- Best Practices - Security and optimization tips
- Troubleshooting - Common issues and solutions
