Skip to main content
 首页 » 编程设计

python之在 Django 中构建 API 服务

2025年05月04日38xing901022

我想使用 Django 构建 API 服务。一个基本的工作流程是这样的:

首先,http 请求转到 http://mycompany.com/create?id=001&callback=http://callback.com。它将在服务器上创建一个名为 001 的文件夹。

其次,如果文件夹不存在,则会创建。您会立即获得 XML 格式的响应。它看起来像:

<?xml version="1.0" encoding="UTF-8"?> 
<response> 
    <status> 
        <statusCode>0</statusCode> 
        <message>Success</message> 
    </status> 
    <group id="001"/> 
</response> 

最后,服务器将完成它的工作(即创建文件夹)。完成后,服务器会对提供的 URL 进行回调。

目前,我使用

return render_to_response('create.xml', {'statusCode': statusCode, 
                                                   'statusMessage': statusMessage, 
                                                   'groupId': groupId, 
                                                   }, mimetype = 'text/xml') 

发送回 XML 响应。我有一个 XML 模板,其中包含 statusCode、statusMessage、groupId 占位符。

<?xml version="1.0" encoding="UTF-8"?>  
<response> 
    <status> 
        <statusCode>{{ statusCode }}</statusCode> 
        <message>{{ statusMessage }}</message> 
    </status> 
    {% if not statusCode %} 
        <group id="{{ groupId }}"/> 
    {% endif %}  
</response> 

但是这样我必须把步骤 3 放在步骤 2 之前,否则如果在 return 语句之后,步骤 3 将不会被执行。

有人可以给我一些建议吗?谢谢。

请您参考如下方法:

我觉得您可能在这里遗漏了一些 Django 基础知识。

为什么 create.py 在你的 url 中?

如果您使用 Django 的 url 路由和 View ,render_to_response 应该可以正常工作。关于为什么没有返回您的回复,您可能会草草得出错误的结论。

我不确定我是否理解该声明:

But in this way I have to put step 3 before step 2, because otherwise step 3 will not be executed if it is after return statement.

第 3 步不在 return 语句之后。它是返回语句的一部分。

你总是可以做这样的事情来拆分这个过程:

# Code that creates folder, statusCode, statusMessage, groupId 
response = render_to_response('create.xml', {'statusCode': statusCode, 
                                                   'statusMessage': statusMessage, 
                                                   'groupId': groupId, 
                                                   }, mimetype = 'text/xml') 
# Some other code, maybe an import pdb; pdb.set_trace()  
# So that you can inspect the response inside of a python shell. 
return response