Ticket #32456: django_postgresql_pgpass.diff

File django_postgresql_pgpass.diff, 2.5 KB (added by Dominik George, 4 years ago)
  • django/db/backends/base/client.py

    commit ffee7b0325256ce79a349df2c982607ce5d6d6b1
    Author: Dominik George <nik@naturalnet.de>
    Date:   Thu Feb 18 00:21:24 2021 +0100
    
        Pass PostgreSQL password in a temporary .pgpass file
    
    diff --git a/django/db/backends/base/client.py b/django/db/backends/base/client.py
    index 339f1e863c..a9eb4f2149 100644
    a b class BaseDatabaseClient:  
    2020        )
    2121
    2222    def runshell(self, parameters):
    23         args, env = self.settings_to_cmd_args_env(self.connection.settings_dict, parameters)
    24         if env:
    25             env = {**os.environ, **env}
    26         subprocess.run(args, env=env, check=True)
     23        with self.settings_to_cmd_args_env(self.connection.settings_dict, parameters) as args, env:
     24            if env:
     25                env = {**os.environ, **env}
     26            subprocess.run(args, env=env, check=True)
  • django/db/backends/postgresql/client.py

    diff --git a/django/db/backends/postgresql/client.py b/django/db/backends/postgresql/client.py
    index 2339880967..73a2086017 100644
    a b  
     1import os
    12import signal
     3from contextlib import contextmanager
     4from tempfile import mkstemp
    25
    36from django.db.backends.base.client import BaseDatabaseClient
    47
    from django.db.backends.base.client import BaseDatabaseClient  
    69class DatabaseClient(BaseDatabaseClient):
    710    executable_name = 'psql'
    811
     12    @contextmanager
    913    @classmethod
    1014    def settings_to_cmd_args_env(cls, settings_dict, parameters):
    1115        args = [cls.executable_name]
    class DatabaseClient(BaseDatabaseClient):  
    3236        args.extend(parameters)
    3337
    3438        env = {}
    35         if passwd:
    36             env['PGPASSWORD'] = str(passwd)
    3739        if service:
    3840            env['PGSERVICE'] = str(service)
    3941        if sslmode:
    class DatabaseClient(BaseDatabaseClient):  
    4446            env['PGSSLCERT'] = str(sslcert)
    4547        if sslkey:
    4648            env['PGSSLKEY'] = str(sslkey)
    47         return args, env
     49        if passwd:
     50            pass_fd, pass_path = mkstemp()
     51            os.close(pass_fd)
     52            with open(pass_path, 'w') as pass_file:
     53                pass_file.write(f'*:*:*:*:{passwd}\n')
     54            env['PGPASSFILE'] = pass_path
     55        else:
     56            pass_path = ''
     57
     58        try:
     59            yield args, env
     60        finally:
     61            if pass_path:
     62                os.unlink(pass_path)
    4863
    4964    def runshell(self, parameters):
    5065        sigint_handler = signal.getsignal(signal.SIGINT)
Back to Top