jeudi 11 novembre 2021

Django-Store to DB with Crontab by means of a for loop and API calls

My problem is that my crontab script does not enter into the first loop and therefore does not store the values that I am trying to store.

In my settings file I have the following:

INSTALLED_APPS = [
'django_crontab',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'my_app',]

and a little further down:

CRONJOBS = [
('*/30 * * * * ', 'ms_app.cron.node_count_and_store'),]

In my cron file I make use of an API that is working correctly, I will not add this here but it basically collects 'nodes' and stores them in a list in this format:

node_list = [[owner, location, serial_number, state]]

This node list (about 6000 in length) is used in the following code:

node = models.Node.objects
    node_list_len = len(node_list)
    for k in range(node_list_len):
        print(k)
        if node.filter(node_serial=node_list[k][2]).exists() == True:
            node_ref = node.filter(node_serial=node_list[k][2])
            node_ref.connection_state = node_list[k][3]
            node.save()
            print("Found the node: %s"%node_list[k][2])
        elif node.filter(node_serial=node_list[k][2]).exists() == False:
            node.create(
                owener_id=node_list[k][0],
                location_id=node_list[k][1],
                node_serial=node_list[k][2],
                connection_state=node_list[k][3]
            )
            node.save()
            print("Created the node: %s"%node_list[k][2])
        else:
            print("Do nothing")
    return

The above snippet is in the function def node_count_and_store()

What I don't understand is that when I use the Django shell and import my models and apply the exact same code I can loop through my list and store the node information. It just does not loop through when it is run via cron.

Please could I get any advice or get information if there is anything wrong here. I am using Django 3.2.5 with python3 This all sits in a venv.

Please let me know if any other information is required.

Aucun commentaire:

Enregistrer un commentaire