Machi
Machi

Reputation: 131

Best way to update my django model coming from an external api source?

I am getting my data through requesting an api source, then I put it in my django model. However, data update daily.. so how can I update these data without rendering it everytime?

def index (request):
    session = requests.Session()
    df = session.get('https://api.coincap.io/v2/assets')
    response= df.json()
    coin = response['data']
    final_result = coin.to_dict('records')
    for coin in final_result:
        obj, created = Coincap.objects.update_or_create(
            symbol = coin['symbol'],
            name = coin['name'],
            defaults = {
                'price': coin['priceUsd']
                })
    return render(request, '/home.html/')

Right now, I have to go to /home.html , if I want my data update. However, my goal is to later serialize it and make it REST api data, so I wouldn't touch django template anymore. Anyway for it to update internally once a day after i do manage.py runserver?

Upvotes: 1

Views: 2487

Answers (2)

Machi
Machi

Reputation: 131

For those that are looking for an example:

from django.core.management.base import BaseCommand
class Command(BaseCommand):
    def handle(self,*args,**kwargs):
        //Your request api here
        for coin in final_result:
            obj, created = Coincap.objects.update_or_create(
                symbol = coin['symbol'],
                name = coin['name'],
                defaults = {
                    'price': coin['priceUsd']})

Then you run in with cron just as Nikita suggested.

Upvotes: 5

Nikita
Nikita

Reputation: 6341

One simple and common solution is to create a custom Django admin command and use Cron to run it at specified intervals. You can write a command's code to your liking and it can have access to all of the models, settings and other parts of your Django project.

You would put your code making a request and writing data to the DB, using your Django models, in your new Command class's handle() method (obviously request parameter is no longer needed). And then, if for example you have named your command update_some_data, you can run it as python manage.py update_some_data.

Assuming Cron exists and is running on the machine. Then you could setup Cron to run this command for you at specified intervals, for example create a file /etc/cron.d/your_app_name and put

0 4 * * * www-data /usr/local/bin/python /path/to/your/manage.py update_some_data >> /var/log/update_some_data.log  2>&1

This would make your update be done everyday at 04:00. If your command would provide any output, it will be written to /var/log/update_some_data.log file. Of course this is just an example, so your server user running your app (www-data here) and path to the Python executable on the server (/usr/local/bin/python here) should be adjusted for particular use.

See links for further guidance.

Upvotes: 2

Related Questions