Search code examples
pythondjangoapscheduler

Job "WrappedAPIView raised an exception. TypeError: view() missing 1 required positional argument: 'request'


I used apscheduler to run a job that calls the function UserViewSet() every 5 seconds.

views.py

    @api_view(['GET'])
    def UserViewSet(self):
       usersData=UserSerializer(UserDetail.objects.all().order_by('name'), many=True)
       return Response(usersData.data)

alerts_scheduler.py

from apscheduler.schedulers.background import BackgroundScheduler
from .. import views
from rest_framework.request import Request

def start():
    scheduler=BackgroundScheduler()
    scheduler.add_job(views.UserViewSet, 'interval', seconds=5)
    scheduler.start()

But I keep getting "Job "WrappedAPIView raised an exception.TypeError: view() missing 1 required positional argument: 'request'" everytime I run my application. enter image description here

I am starting the scheduled job in apps.py as follows:

from django.apps import AppConfig


class AppbackendConfig(AppConfig):
    default_auto_field = 'django.db.models.BigAutoField'
    name = 'AppBackend'

    def ready(self):
        from .app_scheduler import alerts_schedule
        alerts_schedule.start()

The project structure is something like this:

AppBackend

   app_scheduler
      __init__.py
      alerts_scheduler.py

   views.py

Solution

  • Django view takes a request and returns the response. The request can't be passed to APScheduler. So try scheduling a request to the view from APScheduler or write a separate function which makes a request to the view and schedule that to be run.

    For example, if you want to perform any query or update any changes, dont make a call to the view, instead write a separate function as below.

    def test():
         usersData=UserDetail.objects.all().order_by('name')
         #do anything with the queryset
    
    def start():
        scheduler=BackgroundScheduler()
        scheduler.add_job(test, 'interval', seconds=5)
        scheduler.start()
    

    also

    @api_view(['GET'])
    def UserViewSet(self):
    

    should be :

    @api_view(['GET'])
    def UserViewSet(request):