python - 用 `try except` 尝试两个表达式

标签 python sqlalchemy try-except

我有两种表达方式。我需要尝试一个表达式,如果它引发异常,请尝试另一个,但如果第二个表达式也引发异常 - 引发异常。

我试过了,但它看起来很丑,我不确定这是解决这个问题的最佳方法:

try:                                                           
    image = self.images.order_by(func.random()).limit(1)       
except:                                                        
    try:                                                       
        image = self.images.order_by(func.rand()).limit(1)     
    except ProgrammingError:                                   
        raise ProgrammingError(                                
            'The database engine must be PostgtreSQL or MySQL')

你是怎么做到的?

最佳答案

制作一个单独的函数非常有帮助。

def get_random_image(self):
    for rand in func.random, func.rand:
        try:                                                           
            return self.images.order_by(rand()).limit(1)
        except ProgrammingError:                                                        
            pass
    raise ProgrammingError('This database engine is not supported')

关于python - 用 `try except` 尝试两个表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11936350/

相关文章:

python - 异常后如何重试?

python - turtle.TurtleGraphicsError没有注册?

python - Django max_upload_size 被忽略

python - 如何保证更少的UDP数据包被丢弃?

python - 使用 Python 打开新的 Thunderbird 电子邮件

python - 使用 SQLAlchemy 预加载一组对象时出现问题

c++ - 什么是 C++ 中的 .pyw 文件?

python - 如何在 SQLAlchemy 连接表继承中从父类创建子类?

sqlalchemy - Flask 迁移 : Problem creating table and using existing Enum in database. `create_type=False` 不工作

python - 简单;如何合并未知数量的中断