user3277112
user3277112

Reputation: 157

Print output to webpage Django

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.

Upvotes: 7

Views: 5712

Answers (2)

Hayden
Hayden

Reputation: 2808

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!

Upvotes: 2

DGDD
DGDD

Reputation: 1390

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') 

Upvotes: 3

Related Questions