Some task is started in a separate process, where in an infinite loop you need to perform some actions and write the result to the database. During the first run of the loop, it runs and then throws an exception:

DatabaseError: the server is closed.

How to implement a record in the database in another process in Django?

_process = Process(target=start_process, args=(message,id)) _process.start() def start_process(message,id): while True: ... cursor = connection.cursor() cursor.execute("""UPDATE tasks SET exemplar=%s WHERE id_tsk=%s;""", [exemplar, id]) cursor.close() ... sleep(100) 
  • Django was designed strictly for consistent execution. Use Celery for background tasks. - Sergey Gornostaev
  • @SergeyGornostaev Does Celery work with ActiveMQ? - magrif
  • Interestingly, the code works when creating a process in the ready () method that starts when the server is initialized, and the connection to the database does not fall. Maybe you can come up with a crutch for such a small task? - magrif
  • Check the postgres' logs, maybe it crashes due to a syntax error, for example, or something else - FeroxTL

1 answer 1

If django is used to display data, then just put a python file next to it that will do all the work of writing data to the database. This file can be multi-threaded (as far as the interpreter allows).

If you need some django specific actions, you only need to import the necessary ones.