S
S
Sergey2015-02-26 17:54:11
Django
Sergey, 2015-02-26 17:54:11

How to use external scripts in Django?

At work, out of necessity, I wrote several scripts for myself that perform purely applied tasks, for example, bypass a hundred or two routers and collect serial numbers from them. Now, out of curiosity, I began to master dzhangu and at the moment I'm sawing a site that will display a certain base of network equipment with the current parameters of the pieces of iron. There is little practical sense, but it is interesting for yourself. And now the question arose before me: how to use my existing scripts in this project?
For example, I have a model that contains the following fields: ip-address, equipment type, router serial, uptime, etc. To get the serial number of a piece of iron, I added a self-written method to the model, but this solution seems to me some kind of crutch. In addition, my script bypasses all the pieces of iron in many threads, and here I have to call this method for each object. Such an opportunity is also needed, but this is not enough.
I can’t provide the code, because not at hand, but the essence is this:
an external script:

hosts = [['1111', '10.255.10.11'], ['1112', '10.255.10.12'],, ...] (получаю из csv-таблички)
for host in hosts:
    router_id = host[0]
    router_ip = host[1]
    *магия, много потоков*
    *каждый поток свой результат добавляет к списку в виде ['входной ID', 'серийник']*
    ***
    return [['1111', 'серийник1'], ['1112', 'серийник2'], ...]

janga model:
class Device(models.Model):
    host_id=models.CharField(max_length=8)
    host_ip = models.IPAddressField()
    serial_num=models.CharField(max_length=20)
    ...
    def update_serial(self):
        router_id = self.host_id
        router_ip = self.host_ip
        *магия в один поток *
        *получаю 'серийник' *
        self.serial_num = 'серийник'

Explain to the fool, at least conceptually, how this can be done correctly? I would like to be able to pass a list formed from the data available in the database to the script, and at the output get other data that I can write to the same database, preferably for all objects from this database at once.
And if you also show an approximate code, I will be grateful simply unspeakably :)

Answer the question

In order to leave comments, you need to log in

[[+comments_count]] answer(s)
P
Pavel, 2015-02-26
@vebeer

Perhaps I misunderstood your question, but let's reason.
1. Suppose you have a file (awesome.py) that does a lot of necessary and useful things in one run.
It is necessary to arrange the script as a set of functions (func1, func2, ...) and write a function that initializes the execution (let's say main)

# Образное содержимое файла awesome.py

def func1(...):
    ...

def func2(...):
    ...

<... остальные функции ..>

def main(hosts=None):
    if hosts is None:
        * получаем hosts из csv

    * магия
    param = func1(...)
    * не магия, но что-то же нужно делать
    param2 = func2(...)
    param.extend(param2)... blah blah
    return result

if __name__ == '__main__':
    main()

Now the script will work as before from the command line and can be placed in your django project's application directory and imported as a library, for example in the django project's view.
2. Let's say you have a django project where you want to use the written script. Moreover, the hosts data (for calling main) is collected from the database, and the results obtained are written there as well.
3. Apparently, the launch of the script is not for every user, it is too magical and stressful for the server. This means that there will be some page with limited access (for a dedicated group of users or specific users), by accessing which the script will start to run.
So in views.py, in the function called to show this page, there should be something like:
import awesome

@superuser_required
def compute_hosts(request):
    * выбираем данные из бд для hosts

    result = awesome.main(hosts)

    * записываем в бд полученный результат

What do we get now. Users use data from the database, periodically, manually (or not) the superuser updates the data. It seems to be what you wanted.

U
un1t, 2015-02-26
@un1t

You can put the scripts inside the application in the project and run them through manage.py
https://docs.djangoproject.com/en/1.7/howto/custom...
Or another option, specify where the settings are, call the setup method and then write your own the code.

import os
import django
 
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "project.settings")
django.setup()
 
# write your code here

A
Andrew K, 2015-02-26
@mututunus

for device in Device.objects.all():
    # магия, много потоков
    # каждый поток свой результат сохраняет в device.serial_num
    device.save()

S
SKY-SHY, 2020-07-04
@SKY-SHY

But what if it's not a script, but an exe?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question