gpt4 book ai didi

'Try until no exception is raised' 的 Python 习语

转载 作者:太空狗 更新时间:2023-10-29 21:27:39 26 4
gpt4 key购买 nike

我希望我的代码自动尝试多种方式来创建数据库连接。一旦一个工作,代码就需要继续(即它不应该再尝试其他方式)。如果它们都失败了,那么脚本就会爆炸。

所以在 - 我认为是,但很可能不是 - 我尝试了这个天才之举:

import psycopg2
from getpass import getpass

# ouch, global variable, ooh well, it's just a simple script eh
CURSOR = None

def get_cursor():
"""Create database connection and return standard cursor."""

global CURSOR

if not CURSOR:
# try to connect and get a cursor
try:
# first try the bog standard way: db postgres, user postgres and local socket
conn = psycopg2.connect(database='postgres', user='postgres')
except psycopg2.OperationalError:
# maybe user pgsql?
conn = psycopg2.connect(database='postgres', user='pgsql')
except psycopg2.OperationalError:
# maybe it was postgres, but on localhost? prolly need password then
conn = psycopg2.connect(database='postgres', user='postgres', host='localhost', password=getpass())
except psycopg2.OperationalError:
# or maybe it was pgsql and on localhost
conn = psycopg2.connect(database='postgres', user='pgsql', host='localhost', password=getpass())

# allright, nothing blew up, so we have a connection
# now make a cursor
CURSOR = conn.cursor()

# return existing or new cursor
return CURSOR

但似乎第二个和后续的 except 语句不再捕获 OperationalErrors。可能是因为 Python 在 try...except 语句中只捕获一次异常?

是这样吗?如果不是:还有什么我做错了吗?如果是这样:那么你如何做这样的事情呢?有没有标准的成语?

(我知道有办法解决这个问题,比如让用户在命令行上指定连接参数,但这不是我的问题好吧:))

编辑:

我接受了 Retracile 的出色回答,并采纳了 gnibbler 关于使用 for..else 结构的评论。最终代码变成了(抱歉,我并没有真正遵循 pep8 中的每行最大字符数限制):

编辑 2: 从 Cursor 类的评论中可以看出:我真的不知道如何调用这种类。它不是真正的单例(我可以有多个不同的 Cursor 实例)但是在调用 get_cursor 时我每次都得到相同的光标对象。所以它就像一个单例工厂? :)

import psycopg2
from getpass import getpass
import sys

class UnableToConnectError(Exception):
pass

class Cursor:
"""Cursor singleton factory?"""

def __init__(self):
self.CURSOR = None

def __call__(self):
if self.CURSOR is None:
# try to connect and get a cursor
attempts = [
{'database': 'postgres', 'user': 'postgres'},
{'database': 'postgres', 'user': 'pgsql'},
{'database': 'postgres', 'user': 'postgres', 'host': 'localhost', 'password': None},
{'database': 'postgres', 'user': 'pgsql', 'host': 'localhost', 'password': None},
]

for attempt in attempts:
if 'password' in attempt:
attempt['password'] = getpass(stream=sys.stderr) # tty and stderr are default in 2.6, but 2.5 uses sys.stdout, which I don't want
try:
conn = psycopg2.connect(**attempt)

attempt.pop('password', None)
sys.stderr.write("Succesfully connected using: %s\n\n" % attempt)

break # no exception raised, we have a connection, break out of for loop
except psycopg2.OperationalError:
pass
else:
raise UnableToConnectError("Unable to connect: exhausted standard permutations of connection dsn.")

# allright, nothing blew up, so we have a connection
# now make a cursor
self.CURSOR = conn.cursor()

# return existing or new cursor
return self.CURSOR
get_cursor = Cursor()

最佳答案

大约:

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()

现在,如果您不想调用 getpass() 除非有必要,您需要检查 if 'password' in attempt: attempt['password'] = getpass() 左右。

现在关于那个全局....

class MyCursor:
def __init__(self):
self.CURSOR = None
def __call__(self):
if self.CURSOR is None:
<insert logic here>
return self.CURSOR

get_cursor = MyCursor()

...虽然我认为还有其他几种方法可以完成同样的事情。

综合考虑:

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()

注意:完全未经测试

关于 'Try until no exception is raised' 的 Python 习语,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1603578/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com