Python Quick Start
This document describes how to create a Python application from scratch and deploy it to CloudBase HTTP cloud functions. The project uses Flask as the Web application framework.
Cloud Function and CloudBase Run runtimes can access developer credentials through HTTP headers and environment variables. Handle this sensitive information carefully (including but not limited to the HTTP header x-cloudbase-context and environment variables TENCENTCLOUD_SECRETID/TENCENTCLOUD_SECRETKEY), and avoid directly exposing raw request headers or environment variables to end users. When using services like httpbin that automatically echo request headers back to the caller, be sure to handle this behavior, otherwise significant security risks may arise.
Prerequisites
Before you begin, ensure that you have:
- Installed Python 3.10 or a later version
- Have a Tencent Cloud account and have activated the CloudBase service
- Have a basic knowledge of Python and Flask development
Step 1: Create the project directory
Create a new project directory named helloworld-python and enter the directory:
mkdir helloworld-python
cd helloworld-python
Step 2: Set up the Python virtual environment
Create and activate a virtual environment to manage project dependencies:
# Create a virtual environment
python -m venv env
# Activate the virtual environment
# Linux/macOS
source env/bin/activate
# Windows
# env\Scripts\activate
💡 Tip: Using a virtual environment can avoid dependency conflicts and ensure project isolation.
Step 3: Install Dependencies
Install the Flask framework:
pip install flask
Step 4: Write the Application Code
Create the app.py file as the entry file of the application:
⚠️ Important: CloudBase HTTP cloud functions must use the default port
9000.
import os
from flask import Flask, jsonify, request
app = Flask(__name__)
@app.route('/')
def hello():
"""Root path handler function"""
return 'Hello World from Python Flask!'
@app.route('/health')
def health_check():
"""Health Check Endpoint"""
return jsonify({
'status': 'healthy',
'message': 'Python Flask app is running',
'python_version': os.sys.version
})
@app.route('/api/info')
def get_info():
"""Obtain request information"""
return jsonify({
'method': request.method,
'path': request.path,
'headers': dict(request.headers),
'args': dict(request.args)
})
@app.errorhandler(404)
def not_found(error):
"""404 Error Handling"""
return jsonify({'error': 'Not Found', 'message': 'The requested resource was not found'}), 404
@app.errorhandler(500)
def internal_error(error):
"""500 Error Handling"""
return jsonify({'error': 'Internal Server Error', 'message': 'Something went wrong'}), 500
if __name__ == '__main__':
# Listen on port 9000 for all network interfaces
app.run(host='0.0.0.0', port=9000, debug=False)
This code creates a basic Flask Web application that provides the following features:
- Root path (
/): Returns a welcome message - Health Check (
/health): returns application status information - Info Interface (
/api/info): Returns detailed request information - Error Handling: Unified 404 and 500 error handling
Step 5: Generate dependency file
Generate the requirements.txt file to record project dependencies:
pip freeze > requirements.txt
View the generated dependency file:
cat requirements.txt
Typical requirements.txt contents are as follows:
blinker==1.7.0
click==8.1.7
Flask==3.0.0
itsdangerous==2.1.2
Jinja2==3.1.2
MarkupSafe==2.1.3
Werkzeug==3.0.1
Step 6: Create the Startup Script
💡 Note:
- When creating the
scf_bootstrapfile on windows, it is recommended to use- When creating the
scf_bootstrapfile using vscode on windows, deploying to an HTTP cloud function may result in an error:scf_bootstrapfile does not exist- This error occurs because the script file contains Windows-style carriage returns (^M), causing Linux to fail to recognize the interpreter path correctly. This is a common issue in WSL
Create the scf_bootstrap file (with no file extension), which is the startup script for CloudBase cloud functions:
#!/bin/bash
# Set the Python dependency loading path, which defaults to the third_party directory
export PYTHONPATH="./third_party:$PYTHONPATH"
/var/lang/python310/bin/python3.10 app.py
⚠️ Note:
- The file name must be
scf_bootstrapwith no extension- The Python path needs to match the runtime version (here we use Python 3.10)
- Ensure the file has execute permissions
Grant execute permissions to the startup script:
chmod +x scf_bootstrap
Step 7: Local Testing (Optional)
Before deployment, you can test the application locally:
python app.py
After successful testing, you can verify in the following ways:
- Access
http://localhost:9000/to view the welcome message - Access
http://localhost:9000/healthto view the health status - Access
http://localhost:9000/api/infoto view the request information
Press Ctrl + C to stop the local server.
Step 8: Prepare Deployment Files
Before deployment, install dependencies to the third_party directory:
⚠️ Note:
- HTTP cloud functions do not automatically install Python dependencies, so we need to manually download them into the code package
pip install -r requirements.txt -t third_party
Ensure your project directory contains the following files:
helloworld-python/
├── third_party/ # Python dependencies
├── app.py # Application main file
├── requirements.txt # Dependencies list
└── scf_bootstrap # Startup script
Step 9: Package the project
Package the project files into a ZIP file:
# Ensure you are in the project root directory
zip -r helloworld-python.zip third_party app.py scf_bootstrap
💡 Packaging Tip:
- Include the
third_partydirectory to ensure dependencies are complete- Ensure the
scf_bootstrapfile is included- Avoid including unnecessary files (such as
.git,__pycache__, etc.)
Step 10: Deploy to CloudBase HTTP cloud function
Deploy via the console
- Log in to TCB/cloud function
- Click "New Cloud Function"
- Select "HTTP cloud function"
- Enter the function name (e.g.:
helloworld-python) - Select runtime: Python 3.10
- Select the "Local upload" method
- Upload the
helloworld-python.zipfile you just created - Click "OK" to complete the deployment
Deploy via CLI
For details, see Deploy HTTP function via CLI
Step 11: Access Your Application
After successful deployment, you can refer to Accessing Cloud Functions via HTTP to set up custom domain access to the
You can test in the following ways:
- Access the root path to view the welcome message
- Access the
/healthpath to view the application status - Access the
/api/infopath to view request information
Frequently Asked Questions
Q: Why must port 9000 be used?
A: CloudBase HTTP cloud functions require the application to listen on port 9000, which is the standard configuration of the platform.
Q: What is the purpose of the scf_bootstrap file?
A: scf_bootstrap is the startup script for cloud functions, used to set environment variables and start the application.
Q: How to view function logs?
A: On the Cloud Functions page of the CloudBase console, click the function name to go to the details page, where you can view the runtime logs.
Q: Which Python versions are supported?
A: CloudBase supports multiple Python versions. See Runtime Environment Support for details.
Q: How to handle the issue of excessively large dependency packages?
A: You can use the (Layer) feature to manage large dependency packages, or use pip install --no-deps to only install necessary packages.
Best Practices
- Dependency Management: Use
requirements.txtto pin dependency versions - Error Handling: Implement a unified error handling mechanism
- Logging: Use Python's
loggingmodule to log key information - Environment Variables: Use environment variables to manage configuration information.
- Code Structure: For complex applications, it is recommended to use Blueprint (Blueprint) to organize code.
Next steps
- Learn more about HTTP cloud function configuration options
- Learn how to connect to the database
- View Flask framework advanced usage