在Django中构建API服务
我想用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>
但是这样的话,我必须把第三步放在第二步之前,因为如果第三步在 return
语句之后,就不会被执行了。
有没有人能给我一些建议该怎么做?谢谢。
2 个回答
2
你可以使用celery来解决队列的问题。
4
我觉得你可能对Django的一些基本知识还不太了解。
为什么你的create.py
会放在网址里面呢?
如果你在用Django的路由和视图,使用render_to_response应该是没问题的。你可能对为什么没有返回响应这个问题得出了错误的结论。
我不太明白你说的这句话:
但这样的话,我必须把第3步放在第2步之前,因为如果第3步在return语句之后,就不会被执行了。
其实第3步并不是在return语句之后,它是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