Adam Thompson
Adam Thompson

Reputation: 3506

Create New Model Instance with API Call in Django

I'm unsure how to approach this problem in general in my Django app:

I need to make a call to an API every n days. I can make this call and fetch the data required via Python, but where exactly should I put the code?

Do I put the code in a specific view and then map the view to a URL and have that URL called whenever I want to create new model instances based on the API call?

Or am I approaching this the wrong way?

Upvotes: 2

Views: 413

Answers (3)

bruno desthuilliers
bruno desthuilliers

Reputation: 77902

Do I put the code in a specific view

a django view is a callable that must accept an HTTP request and return an HTTP response, so unless you need to be able to call your code thru HTTP there's no point in using a view at all, and even if you want to have a view exposing this code it doesn't mean the code doing the API call etc has to live in the view.

Remember that a "django app" is basically a Python package, so beside the django-specific stuff (views, models etc) you can put any module you want and have your views, custom commands etc call on these modules. So just write a module for your API client etc with a function doing the fetch / create model instance / whatever job, and then call this function from where it makes sense (view, custom command called by a cron job, celery task, whatever).

Upvotes: 1

MauroMSL
MauroMSL

Reputation: 342

The way I usually do this is with a combination of custom Django-admin commands, and then run them wit a scheduled Cron job

You can run your custom commands in the same way as you would run the default ones:

python manage.py <your_command_name> <your_command_arguments>

Upvotes: 2

keno
keno

Reputation: 2966

Sounds like you are trying to have a schedule-able job. Celery works well for this sort of situation.

You would create a task that runs every N days. In that task, you would put your code that calls the API and processing the response as necessary.

Reference: Celery Periodic Tasks

Upvotes: 1

Related Questions