I want to build an API service using Django. A basic workflow goes like this:
First, an http request goes to http://mycompany.com/create?id=001&callback=http://callback.com
. It will create a folder on the server with name 001.
Second, if the folder does not exist, it will be created. You get response immediately in XML format. It will look like:
<?xml version="1.0" encoding="UTF-8"?>
<response>
<status>
<statusCode>0</statusCode>
<message>Success</message>
</status>
<group id="001"/>
</response>
Finally, the server will do its job (i.e. creating the folder). After it is done, the server does a callback to the URL provided.
Currently, I use
return render_to_response('create.xml', {'statusCode': statusCode,
'statusMessage': statusMessage,
'groupId': groupId,
}, mimetype = 'text/xml')
to send the XML response back. I have an XML template which has statusCode
, statusMessage开发者_如何转开发
, groupId
placeholders.
<?xml version="1.0" encoding="UTF-8"?>
<response>
<status>
<statusCode>{{ statusCode }}</statusCode>
<message>{{ statusMessage }}</message>
</status>
{% if not statusCode %}
<group id="{{ groupId }}"/>
{% endif %}
</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.
Can somebody give me some suggestions how to do this? Thanks.
I have a feeling that you might be missing some Django fundamentals here.
Why is create.py
inside of your url?
If you're using Django's url routing and views, the render_to_response should work fine. You might be jumping to an incorrect conclusion regarding why your response isn't getting returned.
I'm not sure I understand the statement:
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.
Step 3 is not after the return statement. It is part of the return statement.
You could always do something like this to split up the process:
# 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
You can use celery for the problem of te queue
精彩评论