Python开发 常见异常和解决办法

时间:2022-07-24
本文章向大家介绍Python开发 常见异常和解决办法,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

1.sqlalchemy创建外键关系报错property of that name exists on mapper

SQLAlchemy是Python编程语言下的一款开源软件,提供了SQL工具包及对象关系映射(ORM)工具,使得在Python中操作MySQL更加简单。在给两个表创建外键关系时可能会报错:

sqlalchemy.exc.ArgumentError: Error creating backref 'xxx' on relationship 'xxx.xxx': property of that name exists on mapper 'mapped class xxx->xxx'

两个数据模型如下:

class Website(Base):
    __tablename__ = 'website'
    id = Column(Integer, primary_key=True, autoincrement=True)
    name = Column(String(10), nullable=False)
    link = Column(String(40), nullable=False)

    orders = relationship('Order', backref='website')

class Order(Base):
    __tablename__ = 'order'
    id = Column(String(50), primary_key=True)
    desc = Column(Text, nullable=False)
    link = Column(String(80), nullable=False)
    contact = Column(String(30))
    category = Column(String(15))
    is_valid = Column(Boolean, nullable=False)
    add_time = Column(DateTime, default=datetime.now)
    website = Column(Integer, ForeignKey('website.id'), nullable=False)
    is_deleted = Column(Boolean, default=False)

其中一个order对于各website,一个website可以对应多个order,在Website模型中定义关系时,backref为website,这与Order中本来的字段website重复而冲突,可以将该字段改名如wid,也可以将backref换名即可。

2.openpyxl保存数据报错openpyxl.utils.exceptions.IllegalCharacterError

在使用openpyxl保存数据时报错如下:

raise IllegalCharacterError
openpyxl.utils.exceptions.IllegalCharacterError

这是因为要保存的数据中存在一些openpyxl认为是非法字符的字符串,需要进行替换,直接使用其提供的ILLEGAL_CHARACTERS_RE进行转换即可,如下:

from openpyxl import Workbook
from openpyxl.cell.cell import ILLEGAL_CHARACTERS_RE

content = ILLEGAL_CHARACTERS_RE.sub(r'', content)
ws.cell(ridx, cidx).value = content

此时即可正常保存数据。