Šimon Marko
Šimon Marko

Reputation: 69

Using Django ORM in plain python script / infinite task

I have application in plain python with some basic libraries. I'm looking to use Django as main framework for this application and maintain frontend.

My question is, can I still use my already written application and switch to Django ORM and maybe controlling the application via some callbacks. This application is running infinitely with asincio library.

Or is there any way how to run background tasks in Django? I found celery but I'm not sure about starting this process. Maybe use of some Django commands and supervisor.

TLDR: I need some way of running background task (command, controller, python script) infinitely long without user interaction.

Upvotes: 0

Views: 139

Answers (1)

gradyhorn
gradyhorn

Reputation: 65

You can do that with Django Background Tasks.

Define your background-task as a function with the decorator @background.
Since you want your task to run infinitely, call it in your main urls.py and just set
repeat_until = None, then it will repeat infinitely.

Copied Example from the linked tutorial:

from django.shortcuts import render,HttpResponse
from background_task import background
# Create your views here.
@background(schedule=5)
def hello():
    print "Hello World!"

def background_view(request):
    hello(repeat=10)
  return HttpResponse("Hello world !")

And this is your call in the urls.py:

from django.conf.urls import url
from django.contrib import admin
from django.conf.urls import include
from background_app.views import hello
urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url( r'^', include('background_app.urls',namespace='background')),

]

hello(repeat=10,repeat_until=None) # This is how you call it

Doc:
https://django-background-tasks.readthedocs.io/en/latest/


Tutorial with small example:
https://medium.com/@robinttt333/running-background-tasks-in-django-f4c1d3f6f06e

Upvotes: 2

Related Questions