Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: start a process in a background thread?

Tags:

I'm trying to work out how to run a process in a background thread in Django. I'm new to both Django and threads, so please bear with me if I'm using the terminology wrong.

Here's the code I have. Basically I'd like start_processing to begin as soon as the success function is triggered. However start_processing is the kind of function that could easily take a few minutes or fail (it's dependent on an external service over which I have no control), and I don't want the user to have to wait for it to complete successfully before the view is rendered. ('Success' as far as they are concerned isn't dependent on the result of start_processing; I'm the only person who needs to worry if it fails.)

def success(request, filepath):     start_processing(filepath)     return render_to_response('success.html', context_instance = RequestContext(request)) 

From the Googling I've done, most people suggest that background threads aren't used in Django, and instead a cron job is more suitable. But I would quite like start_processing to begin as soon as the user gets to the success function, rather than waiting until the cron job runs. Is there a way to do this?

like image 638
AP257 Avatar asked Mar 04 '10 17:03

AP257


People also ask

How do I run a background task in Django?

In Django Background Task, all tasks are implemented as functions (or any other callable). There are two parts to using background tasks: creating the task functions and registering them with the scheduler. setup a cron task (or long running process) to execute the tasks.

Does Django support multithreading?

Node. js has a single threaded, non-blocking I/O mode of execution, while Django being a framework of Python, has a multi-threaded mode of execution.

Is Django Runserver single threaded?

Django itself does not determine whether it runs in one or more threads. This is the job of the server running Django. The development server used to be single-threaded, but in recent versions it has been made multithreaded.


1 Answers

If you really need a quick hack, simply start a process using subprocess.

But I would not recommend spawning a process (or even a thread), especially if your web site is public: in case of high load (which could be "natural" or the result of a trivial DoS attack), you would be spawning many processes or threads, which would end up using up all your system resources and killing your server.

I would instead recommend using a job server: I use Celery (with Redis as the backend), it's very simple and works just great. You can check out many other job servers, such as RabbitMQ or Gearman. In your case, a job server might be overkill: you could simply run Redis and use it as a light-weight message server. Here is an example of how to do this.

Cheers

like image 138
MiniQuark Avatar answered Oct 24 '22 16:10

MiniQuark