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

此时即可正常保存数据。

3.使用sqlalchemy保存字符串到MySQL中时报错Incorrect string value: ‘\xF0…’ for column ‘desc’ at row 1

在使用sqlalchemy保存字符串数据到MySQL中会报错:

raise errors.get_exception(packet)
mysql.connector.errors.DatabaseError: 1366 (HY000): Incorrect string value: '\xF0\x9F\x91\x89\xCF\x84...' for column 'desc' at row 1

这是因为特殊字符\xF0\x9F\x91\x89\xCF\x84...导致的,实际上这是表情字符,即Emoji对应的字符,但是因为MySQL一般的字符集是utf8,因此Emoji表情或者某些特殊字符是4个字节,而Mysql的utf8编码最多3个字节,所以数据插不进去。

解决方法有两种:

  • 修改数据库的默认字符集编码
    修改为MySQL支持Emoji的字符集utf8mb4,具体如下:
    (1)在MySQL的安装目录中找到配置文件my.ini,修改如下:

    [client] 
    default-character-set = utf8mb4 
    [mysql] 
    default-character-set = utf8mb4 
    [mysqld] 
    character-set-client-handshake = FALSE 
    character-set-server = utf8mb4 
    collation-server = utf8mb4_unicode_ci 
    init_connect='SET NAMES utf8mb4'
    

    (2)并通过命令修改当前数据库和表的编码:

    ALTER DATABASE database_name CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci;
    
    alter table table_name convert to character set utf8mb4 collate utf8mb4_bin; 
    

    (3)配置完成后重新启动MYSQL服务即可

  • 替换Emoji字符串
    通过正则表达式匹配字符串中的Emoji字符并替换,即可不用修改数据库的字符集也能正常插入。

    具体如下:

    import re
    
    # Emoji字符正则表达式
    try:
        # Wide UCS-4 build
        emoji_regex = re.compile(u'['
            u'\U0001F300-\U0001F64F'
            u'\U0001F680-\U0001F6FF'
            u'\u2600-\u2B55]+',
            re.UNICODE)
    except re.error:
        # Narrow UCS-2 build
        emoji_regex = re.compile(u'('
            u'\ud83c[\udf00-\udfff]|'
            u'\ud83d[\udc00-\ude4f\ude80-\udeff]|'
            u'[\u2600-\u2B55])+',
            re.UNICODE)
    
    desc = emoji_regex.sub('[Emoji]', desc_str) # desc为可能包含表情的字符串
    
    

这两种方法中,个人建议使用第二种方法,只是对字符串进行处理,无需修改数据库的相关配置。

4.使用sqlalchemy将字符串保存到MySQL报错AttributeError: ‘MySQLConverter’ object has no attribute ‘__elementunicoderesult_to_mysql’

在使用requests库爬取到网页并使用lxml.etree包进行解析网页后,通过xpath获取到指定的元素和文本,并通过sqlalchemy将文本保存到数据库中时报错:

raise errors.ProgrammingError(
sqlalchemy.exc.ProgrammingError: (raised as a result of Query-invoked autoflush; consider using a session.no_autoflush block if this flush is occurring prematurely)
(mysql.connector.errors.ProgrammingError) Failed processing pyformat-parameters; Python '_elementunicoderesult' cannot be converted to a MySQL type

这是因为通过lxml.etree获取到的字符串可能是_elementunicoderesult,这是Python中字符串的一种,danssqlalchemy并未蹄冻将该类型变量转化为SQL对象的方法,因此需要强制转换为str类型,再进行数据保存,如下:

link = str(order.xpath('./div[1]/div[2]/a/@href')[0])
#...
order = OrderModel(id=yid, desc=desc, link=link, contact=contact, category='', pub_time=None, is_valid=is_valid, is_delete=False if is_valid else True)
order.website = website
session.add(order)
session.commit()

5.Windows 11安装Python库报错Microsoft Visual C++ 14.0 or greater is required,安装包丢失或损坏

Python的强大功能依赖于大量的第三方库,一般可以通过pip命令进行安装。但是一些库在安装时可能会报错Microsoft Visual C++ 14.0 or greater is required.,例如mysqlclient等库,以安装mxnet-cu101为例,报错如下:

error: Microsoft Visual C++ 14.0 or greater is required. Get it with "Microsoft C++ Build Tools": https://visualstudio.microsoft.com/visual-cpp-build-tools/
  ----------------------------------------
  ERROR: Failed building wheel for numpy
  Running setup.py clean for numpy
  ERROR: Command errored out with exit status 1:
   command: 'E:\Miniconda3\envs\nlpbase\python.exe' -u -c 'import io, os, sys, setuptools, tokenize; sys.argv[0] = '"'"'XXX\\Temp\\pip-install-e8urqjmj\\numpy_60732a99f04c4bc280c8ad695fdba369\\setup.py'"'"'; __file__='"'"'XXX\\Temp\\pip-install-e8urqjmj\\numpy_60732a99f04c4bc280c8ad695fdba369\\setup.py'"'"';f = getattr(tokenize, '"'"'open'"'"', open)(__file__) if os.path.exists(__file__) else io.StringIO('"'"'from setuptools import setup; setup()'"'"');code = f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' clean --all
       cwd: C:\Users\LENOVO\AppData\Local\Temp\pip-install-e8urqjmj\numpy_60732a99f04c4bc280c8ad695fdba369
  Complete output (10 lines):
  Running from numpy source directory.

一般可以通过下载第三方库的whl文件来安装,但是这样每次安装需要C++的库时,都需要手动下载whl文件,很麻烦。
另外一种解决方案是安装C++环境,常见的做法是安装Visual Studio,但是问题是软件太大,选择C++桌面开发环境之后,大概要安装10多G的文件,会占用很大的C盘空间。
另一种做法是下载visual cpp build tools full.exe,安装 Microsoft Visual C++ 14.0。但是在Windows 11中安装时,会出现以下问题:
安装包丢失或损坏
安装包丢失或损坏
此时需要安装自带安装包的visual cpp build tools full.exe,即可自动安装,如下:
正常安装
安装完成,如下:
安装完成
如需单独的visual cpp build tools full.exe自带安装包的visual cpp build tools full.exe,可点击https://download.csdn.net/download/CUFEECR/84945668下载,并按照使用说明进行安装。

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

东哥说AI

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值