Skip to main content

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.

Prerequisites

Before you begin, make sure you have:

  • Have Python 3.10 or later versions installed
  • Have a Tencent Cloud account with CloudBase service activated
  • Have basic knowledge of Python and Flask development

Step 1: Create a Project Directory

Create a new project directory named helloworld-python and go to the directory:

mkdir helloworld-python
cd helloworld-python

Step 2: Set Up a 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 helps avoid dependency conflicts and ensures project isolation.

Step 3: Install Dependencies

Install the Flask framework:

pip install flask

Step 4: Write Application Code

Create the app.py file as the application entry file:

⚠️ Important Notice: The default port for CloudBase HTTP cloud function must be 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 API"""
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 on 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
  • Information API (/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 list 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 a Startup Script

Create the scf_bootstrap file (without an extension), which is the startup script for CloudBase cloud functions:

#!/bin/bash
export PYTHONPATH="./env/lib/python3.10/site-packages:$PYTHONPATH"
/var/lang/python310/bin/python3.10 app.py

⚠️ Caution:

  • The file name must be scf_bootstrap without extension
  • Python path must match the runtime version (using Python 3.10 here)
  • Ensure the file has execute permission

Grant execute permission to the startup script:

chmod +x scf_bootstrap

Step 7: Test Locally (Optional)

Test the application locally before deployment:

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/health to view the health status
  • Access http://localhost:9000/api/info to view the request information

Press Ctrl + C to stop the local server.

Step 8: Prepare Deployment Files

Ensure your project directory contains the following files:

helloworld-python/
├── env/ # Virtual Environment Directory
│ └── lib/
│ └── python3.10/
│ └── site-packages/
├── app.py # Main application file
├── requirements.txt # Dependency 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 -q helloworld-python.zip ./*

💡 Packaging Tip:

  • Include the env directory to ensure dependency integrity
  • Ensure the scf_bootstrap file is included
  • Avoid including unnecessary files (such as .git, __pycache__, etc.)

Step 10: Deploy to CloudBase HTTP cloud function

Deploy via the Console

  1. Log in to the CloudBase Console
  2. Select your environment and go to the [Cloud Function] page
  3. Click [New Cloud Function]
  4. Select [HTTP cloud function]
  5. Fill in the function name (for example: helloworld-python)
  6. Select runtime: Python 3.10
  7. Select the [Local upload] method
  8. Upload the helloworld-python.zip file created earlier
  9. Click [OK] to complete the deployment

Deploy via CLI (Coming Soon)

Step 11: Access Your Application

After successful deployment, you can refer to Web Client Invocation to configure custom domain access for

You can test in the following ways:

  • Access the root path to view the welcome message
  • Access the /health path to view application status
  • Access the /api/info path to view request information

Frequently Asked Questions

Q: Why must I use port 9000?

A: The CloudBase HTTP cloud function requires 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 up the application.

Q: How do I view function logs?

A: On the CloudBase console's cloud function page, click the function name to go to the details page and view the running logs.

Q: Which Python versions are supported?

A: CloudBase supports Python versions such as 3.6, 3.7, 3.9, 3.10, etc. It is recommended to use Python 3.10.

Q: How to address the issue of excessively large dependency packages?

A: You can use the layer (Layer) feature to manage large dependency packages, or use pip install --no-deps to install only the necessary packages.

Best Practices

  1. Dependency Management: Use requirements.txt to precisely specify dependency versions
  2. Error Handling: Implement a unified error handling mechanism
  3. Logging: Use Python's logging module to log key information
  4. Environment Variables: Use environment variables to manage configuration information.
  5. Code Structure: For complex applications, it is recommended to use blueprint (Blueprint) to organize code.

Next Steps