[Python] How does Django support asynchronous operations

Discussão em 'Python' iniciado por Stack, Agosto 1, 2025.

  1. Stack

    Stack Membro Participativo

    Environment

    • django = "==3.2.15"
    • python3
    • Mysql
    • Uwsgi + Nginx
    Demo Code

    • The request is returned immediately, and the database operation is executed by the background thread (I don't need to pay attention to the thread execution result, as long as it can be executed correctly).

    // views function
    @classmethod
    def _op_function_view(cls, request):
    task_params = get_request_value(request)
    task_params['user'] = request.user
    thread = threading.Thread(target=Task.function,
    args=(task_params,))
    thread.start()
    return "Task run success"


    // modle calss
    class Tast:
    //some mysql filed
    create_username = models.CharField(max_length=50, default='system')
    update_username = models.CharField(max_length=50, default='system')
    ....

    // task function
    def function(cls,params):
    //
    ORM logical
    ......

    Problem


    • It happens when I execute the code: (2006, 'MySQL server has gone away')


    • What should I do to maintain the current logic (keep the task function running in the background and return requests immediately), and ensure that the background threads do not lose sql
    I try


    def function(cls,params):
    //
    django.db.connection.ensure_connection()
    ORM logical
    ......
    django.db.connection.close()


    • But it will still happen:(2006, 'MySQL server has gone away')

    Continue reading...

Compartilhe esta Página