You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django中返回JsonResponse后如何继续执行后续代码?

问题原因

在Python函数中,return语句的作用是立即终止函数执行并返回结果。你在视图函数里先执行了return JsonResponse(payload),这会直接结束整个paytes函数,所以后面的支付请求代码根本不会被运行。

解决方案

根据你的需求,有两种可行的处理方式:

方式1:调整代码顺序(同步执行,不推荐用于耗时操作)

如果可以接受用户等待支付请求完成后再收到响应,把return JsonResponse(payload)移到所有代码的最后:

import json
import random
import base64
import requests
from django.http import JsonResponse, HttpResponse

def paytes(request): 
    payload ={
            "USERID": code_id,
            "MSISDN": serviceCode,
            "MSGTYPE": type_msg,
            "USERDATA": text,
            "SESSIONID": session_id,
            "MSG": response,
        }
    print('MSG: ',response)
    
    # 先执行支付请求逻辑
    url = 'https://prod.theteller.net/v1.1/transaction/process'
    transaction_id = random.randint(100000000000, 999999999999)
    amounte = "000000000080"
    amount = str(amounte)
    data = {
        "amount" :amount,
        "processing_code" : "000200",
        "transaction_id" : transaction_id,
        "desc" : "Mobile Money Payment Test",
        "merchant_id" : "TTM-00000727",
        "subscriber_number" : "233244491909",
        "r-switch" : "MTN",
        }
    encoded = base64.b64encode(b'rad5d4a81d6a3453:MTQwODBiMjU3Yzg1ODhhYmIwM2Q5ZmFmYWVlNjJkOWQ=')
    headers =  {
        'Content-Type': 'application/json',
        'Authorization': f'Basic {encoded.decode("utf-8")}',
        'Cache-Control': 'no-cache'
    }
    res = requests.post(url, data=json.dumps(data), headers=headers)
    print(res.text)
    response_data = res.json()
    status = response_data["status"]
    print(response_data)
    print(status)
    
    # 最后返回响应
    return JsonResponse(payload)

⚠️ 注意:这种方式会让用户等待支付请求完成,若支付接口响应慢,可能导致Django请求超时,影响用户体验。

方式2:异步执行后续逻辑(推荐)

如果需要立刻给用户返回响应,同时后台继续处理支付请求,建议使用异步任务框架(比如Celery),把支付逻辑放到异步任务中:

步骤1:定义异步任务

# tasks.py
import json
import random
import base64
import requests
from celery import shared_task

@shared_task
def process_payment():
    url = 'https://prod.theteller.net/v1.1/transaction/process'
    transaction_id = random.randint(100000000000, 999999999999)
    amounte = "000000000080"
    amount = str(amounte)
    data = {
        "amount" :amount,
        "processing_code" : "000200",
        "transaction_id" : transaction_id,
        "desc" : "Mobile Money Payment Test",
        "merchant_id" : "TTM-00000727",
        "subscriber_number" : "233244491909",
        "r-switch" : "MTN",
        }
    encoded = base64.b64encode(b'rad5d4a81d6a3453:MTQwODBiMjU3Yzg1ODhhYmIwM2Q5ZmFmYWVlNjJkOWQ=')
    headers =  {
        'Content-Type': 'application/json',
        'Authorization': f'Basic {encoded.decode("utf-8")}',
        'Cache-Control': 'no-cache'
    }
    res = requests.post(url, data=json.dumps(data), headers=headers)
    print(res.text)
    response_data = res.json()
    status = response_data["status"]
    print(response_data)
    print(status)

步骤2:在视图中调用异步任务

from django.http import JsonResponse
from .tasks import process_payment

def paytes(request): 
    payload ={
            "USERID": code_id,
            "MSISDN": serviceCode,
            "MSGTYPE": type_msg,
            "USERDATA": text,
            "SESSIONID": session_id,
            "MSG": response,
        }
    print('MSG: ',response)
    
    # 启动异步任务,后台执行支付逻辑
    process_payment.delay()
    
    # 立刻返回响应给用户
    return JsonResponse(payload)

这种方式下,用户会立即收到JsonResponse,支付逻辑在后台异步执行,不会阻塞请求。

内容的提问来源于stack exchange,提问作者spiritman

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 04:20:30