I currently have a long running script which produces various output. What I want to do is have this script run when a button on my webapp is pressed, and for the output to be displayed in real time in a text area on the webpage. I was wondering the simplest way to achieve this using Django.
-
2Take a look: http://stackoverflow.com/questions/4787530/does-django-have-a-way-to-open-a-http-long-poll-connection – alecxe Mar 03 '14 at 17:24
-
There is no extremely simple way to do this, so you'll probably get several totally different answers that are all solutions to different, more specific problems. More info about your requirements (how close to real time do you need it? Do you expect constant streaming output or just occasional output that you want displayed immediately? etc) would help – Andrew Gorcester Mar 03 '14 at 21:35
2 Answers
If you are talking about real time output then you need to use AJAX.
To set off the script, in the webpage you can have a button that sends an AJAX request.
function ajax_call_model(data_JSON_Request, object_id){
$(function jQuery_AJAX_model(){
$.ajax({
type: 'GET',
url: '/ajax_request/',
data: something,
datatype: "json",
success: function(data) {
$("#output_id").html(data);
},//success
error: function() {alert("failed...");}
});//.ajax
});//jQuery_AJAX
};//ajax_call
In views you will have something like this:
def ajax_request(request):
something = request.GET.get('something', '')# Receives from AJAX
output = #Does something with the request
jsonDump = json.dumps(str(output))
return HttpResponse(jsonDump, content_type='application/json')

- 1,370
- 7
- 19
- 36
What you need is a WebSocket! Not supported directly by django, but I would recommend taking a look at Websockets for Django applications using Redis. I have used this before and it is really easy to set up and use.
For example create a django template (e.g. output.html
):
<html>
...
<body>
<textarea id="output" row=3 cols=25></textarea>
<script>
var ws = new WebSocket('{{ ws_url }}');
ws.onmessage = function(e) {
$('#output').append(e.data);
};
</script>
</body>
</html>
Then create a method which your script calls whenever it wants to output a message to the text area:
def output_message(session_key, user, message):
conn = redis.StrictRedis()
ws_url = '{0}:{1}'.format(session_key, user)
conn.publish(ws_url, message)
And finally you need to specify in your views.py
a method which renders your output.html
template:
def output_console(request):
template_values = {'ws_url':'ws://{SERVER_NAME}:{SERVER_PORT}/ws/{0}?subscribe-session'.format(request.user.id, **request.META)}
return render(request, 'output.html', template_values)
Take a look at the chat server on the projects git repo for a more in-depth code example.
Hope that helps, and best of luck!

- 2,818
- 2
- 22
- 30