Integrating Third-Party Services in Python Web Applications

Integrating Third-Party Platforms

In web application development, certain tasks often require external assistance. For instance, implementing user or business identity verification necessitates a reliable method to confirm the authenticity of provided information, a capability typically beyond a project's internal scope. In such cases, leveraging third-party platforms becomes essential. Similarly, offering online payment functionality usually relies on established payment gateways like WeChat Pay, Alipay, or UnionPay, rather than building a custom solution from scratch.

Integrating third-party platforms generally involves two primary approaches: API integration and SDK integration.

  1. API Integration: This method involves making network requests to URLs provided by the third-party service to perform actions or retrieve data. Many platforms offer a wide range of APIs, such as those for lifestyle services, fintech, geolocation, and recharging. A Python program can initiate these requests to fetch data, similar to how a project might interact with its own internal APIs. However, while some APIs are open, most providing commercially valuable data require payment.
  2. SDK Integration: This approach involves installing a third-party library and utilizing its encapsulated classes and functions. For example, integrating Alipay requires installing its SDK and using its provided classes and methods to invoke payment services.

Let's explore these integration methods through practical examples.

Integrating an SMS Gateway

SMS services are widely used in web projects, such as for mobile verification code logins, important notifications, and marketing messages. To implement SMS sending, integrating an SMS gateway is a common solution. Popular SMS gateways in China include Yunpian, NetEase Cloud Message, Luosimao, and SendCloud, many of which offer free trials. We'll use Luosimao as an example to demonstrate how to integrate an SMS gateway into a project; the process for other platforms is generally similar.

  1. Register an account, which often includes a free trial.
  2. Log in to the management console and navigate to the SMS section.
  3. Click "Trigger Send" to find your unique API Key (identity identifier).
  4. Click "Signature Management" to add an SMS signature. All SMS messages must include a signature. For free trials, the signature "【Iron Shell Test】" must be added; otherwise, messages will not be sent.
  5. Click "IP Whitelist" and add the public IP address of the server running you're Django project (for local development, you can find your public IP via a service like whatismyipaddress.com). Without this, messages will fail to send.
  6. If you run out of SMS credits, you can recharge by selecting "SMS Service" on the "Recharge" page.

Next, we can implement sending an SMS verification code by calling the Luosimao SMS gateway. The code is as follows:

import requests

def dispatch_sms_verification(phone_number, verification_code):
    """Send an SMS verification code."""
    response = requests.post(
        url='http://sms-api.luosimao.com/v1/send.json',
        auth=('api', 'key-Your_API_Key_Here'),
        data={
            'mobile': phone_number,
            'message': f'Your verification code is {verification_code}. Do not share it with anyone. 【Python Essentials】'
        },
        verify=False
    )
    return response.json()

Running this code requires the requests library, which simplifies HTTP network requests. The dispatch_sms_verification function takes a phone number and a verification code. The fifth line requires your API Key from step 2. The Luosimao gateway returns data in JSON format. A response like {'err': 0, 'msg': 'ok'} indicates success. If the err field has a non-zero value, it signifies a failure. The official Luosimao documentation explains the meaning of different error codes, e.g., -20 for insufficient balance, -32 for missing signature.

You can call this function within a view to send verification codes, which we'll later integrate with user registration.

Functions to generate a random code and validate a phone number:

import random
import re

PHONE_PATTERN = re.compile(r'1[3-9]\d{9}')

def validate_phone_number(phone):
    """Validate a Chinese mobile phone number."""
    return PHONE_PATTERN.fullmatch(phone) is not None

def generate_random_code(length=6):
    """Generate a random numeric verification code."""
    return ''.join(random.choices('0123456789', k=length))

View function for requesting an SMS verification code:

from django.http import JsonResponse
from django.core.cache import cache

def request_sms_verification(request, phone):
    """Request an SMS verification code."""
    if validate_phone_number(phone):
        # Check for throttling using Redis
        throttle_key = f'sms:throttle:{phone}'
        if cache.get(throttle_key):
            return JsonResponse({'status': 'error', 'message': 'Please do not request a code more than once within 60 seconds.'})
        else:
            code = generate_random_code()
            dispatch_sms_verification(phone, code)
            # Set a 60-second throttle
            cache.set(throttle_key, '1', timeout=60)
            # Store the verification code for 10 minutes (600 seconds)
            cache.set(f'sms:code:{phone}', code, timeout=600)
            return JsonResponse({'status': 'success', 'message': 'SMS verification code sent. Please check your phone.'})
    else:
        return JsonResponse({'status': 'error', 'message': 'Please enter a valid phone number.'})

Note: The above code uses Redis to prevent users from requesting a verification code more than once within 60 seconds and to store the code for 10 minutes, ensuring its validity period.

Integrating Cloud Storage Services

When we refer to cloud storage, we typically mean storing data on virtual servers provided by a third party. In simpler terms, it involves hosting data or resources on a third-party platform. Companies offering cloud storage services operate large data centers, and users or organizations purchase or lease storage space from them. In web application development, static resources, especially those uploaded by users, can be directly placed on cloud storage. Cloud storage providers offer corresponding URLs for accessing these static resources. Renowned cloud storage services like Amazon S3 or Alibaba Cloud OSS are cost-effective. Compared to setting up your own static resource server, cloud storage is often more economical, and many platforms provide CDN services to accelerate access to these resources. Therefore, using cloud storage to menage web application data and static resources is an excellent choice, unless the resources involve personal or commercial privacy.

Let's use integrating AWS S3 as an example to demonstrate how to save user-uploaded files to cloud storage. AWS S3 is a well-known cloud computing and data service provider. S3 offers solutions for massive file storage, CDN, video on demand, interactive live streaming, and large-scale heterogeneous data analysis. Non-paying users can also access its services for free. The integration process is as follows:

  1. Register an account and log in to the AWS Management Console.
  2. Navigate to the S3 service.
  3. Create a new bucket (e.g., my-web-app-assets). If the name is taken, choose another. After creating the bucket, you'll be prompted to configure it, including setting up a custom domain (optional for this example).
  4. In the console, go to "My Security Credentials" to find your Access Key ID and Secret Access Key, which are needed for authentication.
  5. Visit the AWS documentation, navigate to the "SDKs and Tools" section, find the "AWS SDK for Python (Boto3)" documentation.

Once you have your credentials, you can integrate with S3. First, install the AWS SDK for Python:

pip install boto3

Then, you can use the boto3 library to upload files. The following functions demonstrate uploading a file from a local path and uploading binary data from memory:

import boto3
import uuid

# Initialize the S3 client
s3_client = boto3.client(
    's3',
    aws_access_key_id='Your_Access_Key_ID',
    aws_secret_access_key='Your_Secret_Access_Key'
)

BUCKET_NAME = 'my-web-app-assets'

def store_file_on_s3(file_key, local_file_path):
    """Upload a file from a local path to S3."""
    try:
        s3_client.upload_file(local_file_path, BUCKET_NAME, file_key)
        return True
    except Exception as e:
        print(f"Error uploading file: {e}")
        return False

def store_stream_on_s3(file_key, file_stream, file_size):
    """Upload binary data stream to S3."""
    try:
        s3_client.put_object(Bucket=BUCKET_NAME, Key=file_key, Body=file_stream)
        return True
    except Exception as e:
        print(f"Error uploading stream: {e}")
        return False

Here's a simple HTML form for file upload:

<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Upload File</title>
</head>
<body>
    <form action="/upload/" method="post" enctype="multipart/form-data">
        <div>
            <input type="file" name="document">
            <input type="submit" value="Upload">
        </div>
    </form>
</body>
</html>

Note: For file uploads via HTML forms, the method attribute must be post, and the enctype attribute must be multipart/form-data. The input tag with type="file" is the file selector.

The view function to handle the upload could look like this:

import os
from django.http import HttpResponse, HttpResponseRedirect
from django.views.decorators.csrf import csrf_exempt

@csrf_exempt
def handle_file_upload(request):
    """Handle file upload and store it on S3."""
    if request.method == 'POST':
        uploaded_file = request.FILES.get('document')
        if uploaded_file:
            # Generate a unique filename using UUID and original extension
            file_extension = os.path.splitext(uploaded_file.name)[1]
            unique_filename = f"{uuid.uuid4().hex}{file_extension}"

            # For files, we can use the stream upload function
            if store_stream_on_s3(unique_filename, uploaded_file, uploaded_file.size):
                return HttpResponseRedirect('/static/html/upload.html')
            else:
                return HttpResponse("Failed to upload file to S3.", status=500)
        else:
            return HttpResponse("No file uploaded.", status=400)
    return HttpResponse("Invalid request method.", status=405)

Note: The view function uses the csrf_exempt decorator to bypass CSRF protection for simplicity. The 11th line uses the uuid module's uuid4 function to generate a globally unique identifier for the filename.

After running the project and testing the file upload, you can verify the uploaded file in the S3 console under your bucket's "Objects" list. You can then access the file using the URL provided by S3.

Tags: python API sdk SMS Gateway Cloud Storage

Posted on Mon, 06 Jul 2026 17:33:38 +0000 by schris403