Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Approximately:</p> <pre><code>attempts = [ { 'database'='postgres', 'user'='pgsql', ...}, { 'database'='postgres', 'user'='postgres', 'host'='localhost', 'password'=getpass()}, ... ] conn = None for attempt in attempts: try: conn = psycopg2.connect(**attempt) break except psycopg2.OperationalError: pass if conn is None: raise a ruckus CURSOR = conn.cursor() </code></pre> <p>Now, if you don't want to call <code>getpass()</code> unless it is necessary, you'd want to check <code>if 'password' in attempt: attempt['password'] = getpass()</code> or so.</p> <p>Now about that global....</p> <pre><code>class MyCursor: def __init__(self): self.CURSOR = None def __call__(self): if self.CURSOR is None: &lt;insert logic here&gt; return self.CURSOR get_cursor = MyCursor() </code></pre> <p>... though I think there are a couple of other ways to accomplish the same thing.</p> <p>Bringing it all together:</p> <pre><code>class MyCursor: def __init__(self): self.CURSOR = None def __call__(self): if self.CURSOR is None: attempts = [ {'database'='postgres', 'user'='postgres'}, {'database'='postgres', 'user'='pgsql'}, {'database'='postgres', 'user'='postgres', 'host'='localhost', 'password'=True}, {'database'='postgres', 'user'='pgsql', 'host'='localhost', 'password'=True}, ] conn = None for attempt in attempts: if 'password' in attempt: attempt['password'] = getpass() try: conn = psycopg2.connect(**attempt) break # that didn't throw an exception, we're done except psycopg2.OperationalError: pass if conn is None: raise a ruckus # nothin' worked self.CURSOR = conn.cursor() return self.CURSOR get_cursor = MyCursor() </code></pre> <p><sub>Note: completely untested</sub></p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload