How can I force django to restart a database connection from the shell?

后端 未结 2 1790
遇见更好的自我
遇见更好的自我 2021-02-02 15:46

I have a django project on a Digital Ocean server. From my local machine, I connect to the database through ssh:

ssh -L 63333:localhost:5432 me@my.server
         


        
相关标签:
2条回答
  • 2021-02-02 16:34
    from django.db import connections, connection
    for conn in connections.all():
        conn.close_if_unusable_or_obsolete()
    

    then call connection.cursor will get a fresh connection, django source code:

    def _cursor(self, name=None):
        self.ensure_connection()
        with self.wrap_database_errors:
            return self._prepare_cursor(self.create_cursor(name))
    
    0 讨论(0)
  • 2021-02-02 16:35

    You can use something like below

    from django.db import connections
    conn = connections['default']
    conn.connect()
    

    or

    from django.db import connection
    connection.connect()
    
    0 讨论(0)
提交回复
热议问题