The request still runs for django_migrations

I am developing a django web application and I notice something strange. The next query will remain executed in DB

SELECT "django_migrations". "app", "django_migrations". "name" FROM "django_migrations"

here is an example from: select query_start, state_change, wait, state, query from pg_stat_activity;

test6=> select query_start,state_change,waiting,state,query from pg_stat_activity;
          query_start          |         state_change          | waiting | state  |                                                                  query
-------------------------------+-------------------------------+---------+--------+--------------------------------------------------------------------------------------------------
 2017-06-21 16:02:21.926337+02 | 2017-06-21 16:02:21.926402+02 | f       | idle   | SELECT "django_migrations"."app", "django_migrations"."name" FROM "django_migrations"

      

to stop "server-to-server"

Current settings:

  • Django 1.11.2
  • PostgreSQL 9.2.17
  • Using Django ORM only
  • All migrations have been applied
  • CONN_MAX_AGE set in settings.py

Why doesn't Django close the connection after making a request?

+3


source to share


1 answer


The documentation Django uses persistent connections:

[...] each thread maintains its own connection

The command runserver

itself is a thread, but SELECT "django_migrations"."app", "django_migrations"."name" FROM "django_migrations"

simply represents the last request made on the connection, after the results have been returned, the state remains dormant.

If you try to execute a query after checking the migration, for example in wsgi, this query will replace the one you see.



Hence, by default, the creator creates a thread for every incoming request, so the connection (in the main thread) to test the migration is never closed using the doc:

At the beginning of each request, Django closes the connection if it has reached its maximum age. If your database ends up with a connection idle after a while, you should set CONN_MAX_AGE to a lower value so that Django doesn't try to use a connection that was stopped by the database server. (This issue can only affect very low traffic locations.)

As you can read, the closure is done by either Postgres or Django on the next request. So, either you are configuring postgres to kill idle connections, or you can use --nothreading

the server to reuse the connection created by the main thread (warning: it has a big performance impact).

+3


source







All Articles