Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Long, slow operation in Django view causes timeout. Any way for Python to speak AJAX instead?

I've been programming Python a while, but DJango and web programming in general is new to me.

I have a very long operation performed in a Python view. Since the local() function in my view takes so long to return, there's an HTTP timeout. Fair enough, I understand that part.

What's the best way to give an HTTPresponse back to my users immediately, then dynamically show the results of some python code within the page? I suspect the answer may lie in AJAX but I;m not sure how AJAX on the client can be fed from Python on the server, or even the modules one would commonly use to do such a thing.

like image 422
mikemaccana Avatar asked Oct 17 '09 17:10

mikemaccana


2 Answers

Ajax doesn't require any particular technology on the server side. All you need is to return a response in some form that some Javascript on the client side can understand. JSON is an excellent choice here, as it's easy to create in Python (there's a json library in 2.6, and Django has django.utils.simplejson for other versions).

So all you need to do is to put your data in JSON form then send it just as you would any other response - ie by wrapping it in an HTTPResponse.

like image 166
Daniel Roseman Avatar answered Nov 15 '22 02:11

Daniel Roseman


One way is to submit the task using AJAX/JS or the normal way, start it in background in your view and return immediately. Then use AJAX/JS on client side to periodically check if task is done. If it's done reload the page or provide a link to the client.

CLIENT "Please start a task using this data."-> SERVER

CLIENT <- "Task started!" SERVER

CLIENT "Done?"-> SERVER

CLIENT <- "Nope." SERVER

CLIENT "Done?"-> SERVER

CLIENT <- "Yep, here's a link where you can view results" SERVER

While sending data from server to client without client asking for it is possible, well kind a, (the technology is called Comet) it isn't really necessary in your case.

like image 44
Maiku Mori Avatar answered Nov 15 '22 04:11

Maiku Mori