个人 BUG 汇总记录

27 minute

TOC

fastjson 反序列化对象修饰符问题

1Caused by: java.lang.IllegalAccessException: class com.alibaba.fastjson.parser.deserializer.JavaBeanDeserializer cannot access a member of class com.jzh.test.json.SubmitTime with modifiers "public"

fastjson 通过有参构造函数反序列化可能会出现此问题,原因是 SubmitTime 这个类没有被 public 修饰,而其构造函数使用 public 修饰,所以导致反序列化失败。而如果通过无参构造加 setter 进行反序列化则无此问题。

本地多线程测试天坑: 测试方法开的线程没跑完

如果测试方法中包含异步操作,那么直接运行测试方法,异步方法未执行完成时,主线程已经退出,导致异步方法无法正常执行完!!

解决方法是在 @Test 测试方法中打个断点,不要让 @Test 的方法直接完成退出!

IDEA maven reload : out of memory error

Maven | Importing | VM options for importer: -Xmx6144m

sqlite-jdbc No native library is found

1Caused by: java.lang.Exception: No native library is found for os.name=Mac and os.arch=aarch64. path=/org/sqlite/native/Mac/aarch64

If you are using Apple M1 chip

One of the release notes they have mentioned by jetpack (Version 2.4.0-alpha03 )

Fixed an issue with Room’s SQLite native library to support Apple’s M1 chips. Change Version to 2.4.0-alpha03 or above

For those who are facing this problem, you can simply add this line before the room-compiler as a workaround now:

kapt “org.xerial:sqlite-jdbc:3.34.0”

hibernate + sqlite 问题

 1Description:
 2
 3An attempt was made to call a method that does not exist. The attempt was made from the following location:
 4
 5    org.sqlite.hibernate.dialect.SQLiteDialect.<init>(SQLiteDialect.java:57)
 6
 7The following method did not exist:
 8
 9    'void org.sqlite.hibernate.dialect.SQLiteDialect.registerColumnType(int, java.lang.String)'
10
11The calling method's class, org.sqlite.hibernate.dialect.SQLiteDialect, was loaded from the following location:
12
13    jar:file:/Users/zh/.m2/repository/com/github/gwenn/sqlite-dialect/0.1.2/sqlite-dialect-0.1.2.jar!/org/sqlite/hibernate/dialect/SQLiteDialect.class
14
15The called method's class, org.sqlite.hibernate.dialect.SQLiteDialect, is available from the following locations:
16
17    jar:file:/Users/zh/.m2/repository/com/github/gwenn/sqlite-dialect/0.1.2/sqlite-dialect-0.1.2.jar!/org/sqlite/hibernate/dialect/SQLiteDialect.class
18
19The called method's class hierarchy was loaded from the following locations:
20
21    org.sqlite.hibernate.dialect.SQLiteDialect: file:/Users/zh/.m2/repository/com/github/gwenn/sqlite-dialect/0.1.2/sqlite-dialect-0.1.2.jar
22    org.hibernate.dialect.Dialect: file:/Users/zh/.m2/repository/org/hibernate/orm/hibernate-core/6.4.1.Final/hibernate-core-6.4.1.Final.jar
23
24
25Action:
26
27Correct the classpath of your application so that it contains a single, compatible version of org.sqlite.hibernate.dialect.SQLiteDialect

fix:

From Hibernate 6, SQLite dialect is supported. We have to import in our pom.xml:

1<dependency>
2    <groupId>org.hibernate.orm</groupId>
3    <artifactId>hibernate-community-dialects</artifactId>
4</dependency>

Copy And in our application properties:

1spring.jpa.database-platform=org.hibernate.community.dialect.SQLiteDialect
 1        <!--jpa-->
 2        <dependency>
 3            <groupId>org.springframework.boot</groupId>
 4            <artifactId>spring-boot-starter-data-jpa</artifactId>
 5        </dependency>
 6        <!-- sqlite -->
 7        <dependency>
 8            <groupId>org.xerial</groupId>
 9            <artifactId>sqlite-jdbc</artifactId>
10            <version>3.34.0</version>
11        </dependency>
12<!--        <dependency>-->
13<!--            <groupId>com.github.gwenn</groupId>-->
14<!--            <artifactId>sqlite-dialect</artifactId>-->
15<!--            <version>0.1.4</version>-->
16<!--        </dependency>-->
17        <dependency>
18            <groupId>org.hibernate.orm</groupId>
19            <artifactId>hibernate-community-dialects</artifactId>
20        </dependency>

具体就是要删去 sqlite-dialect 并引入 hibernate-community-dialects,然后添加 jpa 配置。

JAR 包项目文件上传问题

获取类路径:

如果单纯运行一个 java 项目:${project}/target/classes

如果是运行 jar 包,且是在 Linux 系统上:${jar包名}!/BOOT-INF/classes!

所以如果是 jar 包启动并上传文件,则无法正确放到类路径下,需指定新的上传路径。

可以在 jar 包同一路径下新建并编辑 application.yaml 文件如下:

1spring:
2    resources:
3        static-locations:
4            - classpath:static/
5            - file:/app/static/

然后在文件上传是指定上传路径即可。

类文件具有错误的版本 55.0, 应为 52.0

上面报错中的 55.0 是 JDK11 使用的类文件格式 (class file format) 的版本号,提示的意思是当面项目使用的类文件格式版本比某个依赖包使用的类文件格式版本低。

实际就是指当前项目使用的 JDK 版本比某个依赖包使用的 JDK 版本低。

Mockito 5.8 使用了 JDK 11,而项目使用 JDK 8,那么会报错。

The server selected protocol version TLS10 is not accepted by client preferences [TLS13, TLS12]

Remove “TLSv1, TLSv1.1” from “jdk.tls.disabledAlgorithms” property in file ${soapui_home}/jre/conf/securityjava.security.

RocketMQ: It may be caused by one of the following reasons: the broker’s disk is full

1cd conf/2m-2s-sync
2
3vim broker-a.properties
4diskMaxUsedSpaceRatio=99

SpringBoot 3.X 使用 SpringBoot 2.X 的 Starter 无法完成自动装配

SpringBoot 3.X 自动装配类通过 META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports 配置,而 2.X 通过 META-INF/spring.factories 完成,所以无法完成自动装配。解决方式是自己通过 @Bean@Configuration 装配 Bean。

list.remove() 正确的使用重载

调用 set.remove(i) 选择重载 remove(E) 方法,其中 E 是 set (Integer) 的元素类型,将 基本类型 i 由 int 自动装箱为 Integer 中。这是你所期望的行为,因此程序最终会从集合中删除指定大小的值。

调用 list.remove(i) 的调用选择重载 remove(int i) 方法,它将删除列表中指定位置的元素。若要删除指定大小的元素,对于 List<E> 接口对方法有的两个重载: remove(E) 和 remove(int),需要强制转换的参数为类型,迫使其选择正确的重载。

后端返回的 json 数据格式出错

首先注意,json 采用驼峰命名法。

一般对于前后端分离的项目,后端都是返回 json 格式数据,比如使用 @RestController 进行自动的转换。

对于一个采用驼峰命名法命名的变量,比如 userId,转换后返回前端的 json 属性名是 userId,没有问题。

但是当变量名为 uId时,转换后则变为 uid,这就产生了问题。我还测试了其它一些变量,如下:

1# userId
2{"code":200,"msg":"ok","obj":{"userId":"hello"}}
3# uId
4{"code":200,"msg":"ok","obj":{"uid":"hello"}}
5# Id
6{"code":200,"msg":"ok","obj":{"id":"hello"}}
7# uuId
8{"code":200,"msg":"ok","obj":{"uuId":"hello"}}

可见当为 uId 和 Id 时,都会出现问题。

一般可以考虑在后端变量命名时,不让第二个字符大写,或者采用 @JsonProperty("uId") 进行解决。

IDEA 中在 maven 配置文件中配置 JVM 启动参数

有些是 .maven/maven.config,有些是 .mvn/jvm.config,必须在设置 > maven 中查看。

BigDecimal 构造函数的结果可能不可预测

1BigDecimal amount1 = new BigDecimal(0.02);
2BigDecimal amount2 = new BigDecimal(0.03);
3System.out.println(amount2.subtract(amount1));
4// 0.0099999999999999984734433411404097569175064563751220703125

正确方法:

1BigDecimal amount1 = BigDecimal.valueOf(0.02);
2BigDecimal amount2 = BigDecimal.valueOf(0.03);

反序列化 boolean 字段失败的问题

直接以一个例子说明这个问题:

 1public class FastJsonTest {
 2    @Test
 3    public void test1() {
 4        Vote vote = new Vote();
 5        vote.setTitle("test");
 6        vote.setIsOverdue(true);
 7        vote.setDeleted(false);
 8        vote.setImportant(true);
 9        String voteJson = JSON.toJSONString(vote);
10        System.out.println(voteJson);
11        // {"deleted":false,"important":true,"isOverdue":true,"title":"test"}
12
13        // ok
14        Vote voteFromJson = JSON.parseObject(voteJson, Vote.class);
15        System.out.println(voteFromJson);
16
17        // {"deleted":false,"isImportant":true,"isOverdue":true,"title":"test"}
18        String anotherVoteJson = "{\"deleted\":false,\"isImportant\":true,\"isOverdue\":true,\"title\":\"test\"}";
19        Vote anotherVote = JSON.parseObject(anotherVoteJson, Vote.class);
20        System.out.println(anotherVote);
21        // 反序列化失败:
22        // Vote(isOverdue=true, deleted=false, isImportant=false, title=test)
23    }
24}
25
26@NoArgsConstructor
27@Data
28class Vote {
29    // ok
30    private Boolean isOverdue;
31    // ok
32    private Boolean deleted;
33    // fail
34    private boolean isImportant;
35
36    private String title;
37}

使用 fastjson 反序列化时,由于 Vote 对象存在空参构造, 所以将根据 set 方法反序列化,如果字段是 Boolean 类型,那么反序列化成功,如果是 boolean 类型,且字段命名以 is 开头,那么反序列化失败。

所以,建议布尔类型都不要加 is 作为前缀,否则部分框架解析可能会有问题。(来自阿里巴巴 Java 开发手册)

maven 的 http 问题

Maven 升级到 3.8.1 之后,执行 mvn clean package 命令后会报错如下:

1maven-default-http-blocker (http://0.0.0.0/): Blocked mirror for repositories

maven 在 3.8.1 的默认配置文件中增加了一组标签,如果仓库镜像是 http 而不是 https 就会被拦截禁止访问

新增节点:

1<mirror>
2    <id>maven-default-http-blocker</id>
3    <mirrorOf>dummy</mirrorOf>
4    <name>Dummy mirror to override default blocking mirror that blocks http</name>
5    <url>http://0.0.0.0/</url>
6</mirror>

或回退版本

Failed to determine a suitable driver class

 12023-05-31T16:52:18.233+08:00  WARN 28432 --- [           main] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in class path resource [org/springframework/boot/autoconfigure/jdbc/DataSourceConfiguration$Hikari.class]: Failed to instantiate [com.zaxxer.hikari.HikariDataSource]: Factory method 'dataSource' threw exception with message: Failed to determine a suitable driver class
 22023-05-31T16:52:18.235+08:00  INFO 28432 --- [           main] o.apache.catalina.core.StandardService   : Stopping service [Tomcat]
 32023-05-31T16:52:18.250+08:00  INFO 28432 --- [           main] .s.b.a.l.ConditionEvaluationReportLogger : 
 4
 5......
 6
 7Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured.
 8
 9Reason: Failed to determine a suitable driver class
10
11
12Action:
13
14Consider the following:
15  If you want an embedded database (H2, HSQL or Derby), please put it on the classpath.
16  If you have database settings to be loaded from a particular profile you may need to activate it (no profiles are currently active).

关键在于:

1Error creating bean with name 'dataSource' defined in class path resource [org/springframework/boot/autoconfigure/jdbc/DataSourceConfiguration$Hikari.class]: Failed to instantiate [com.zaxxer.hikari.HikariDataSource]: Factory method 'dataSource' threw exception with message: Failed to determine a suitable driver class

可以发现是 springboot 自动配置的锅,找不到一个合适的 driver 进行数据源的连接。

解决方法:

1@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})

隐藏的依赖版本冲突问题

当我从 SpringBoot 2.7 迁移到 SpringBoot 3.0 时,发现项目启动报错,原来的项目能正常启动,证明可能是依赖错误的问题了。

而 pom.xml 中有着很多依赖,由于是和 SpringBoot 有关,所以估计是一些第三方的 starter 有问题,最终发现是 MybatisPlus 的 3.4.3.4 版本不能正常在 SpringBoot 3.0 中使用,升级到 3.5.3.1 就没这个问题了。

BufferedWriter 无法正确写出问题

这是一段客户端代码,向服务器端发送消息,然后接收服务器端的回复:

 1try (
 2        BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
 3        BufferedWriter out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()))
 4) {
 5    String message;
 6    while((message = stdIn.readLine()) != null) {
 7        out.write(message);
 8        out.flush();
 9        System.out.println("Receive from server: " + in.readLine());
10    }
11} catch (Exception e) {
12    System.out.println(e.getMessage());
13}

这是服务端代码的一部分,接收客户端消息,并向客户端回复:

 1try (
 2        BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
 3        BufferedWriter out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()))
 4) {
 5    String message;
 6    while((message = in.readLine()) != null) {
 7        System.out.println(Thread.currentThread().getName() + ": receive from port " + socket.getPort() + ": " + message);
 8        out.write(message);
 9        out.flush();
10    }
11} catch (Exception e) {
12    System.out.println(e.getMessage());
13}

这里两端都使用了 BufferedReaderBufferedWriter 作为消息的传输工具。

经过测试发现,消息传输是失败的。

问题出现在 out.write(message);message = in.readLine() 这两个地方,因为 in.readLine() 读取的是一行数据,即数据必须要存在换行符,如果不存在的话将无法读完,一直处于阻塞状态。

所以,解决方法就是将写出的数据通过 newLine 操作加上换行符:

1out.write(message); // 如果使用BufferedWriter,则需要添加换行符
2out.newLine();

另一种更好的方法是使用 PrintWriter,使用它的写出操作 println 进行消息的输出。

pnpm build error: Rollup

构建失败的原因是 Rollup 在处理代码时遇到了一个错误:Cannot read properties of null (reading ‘render’)。这种错误通常与代码中的某些语法或依赖问题有关。

某些第三方库可能与 Rollup 不兼容,尤其是使用了动态导入或复杂语法的库。检查 node_modules 中是否有库的版本更新或损坏。

1# 清理缓存
2pnpm store prune
3# 删除 node_modules 和 lock 文件
4rm -rf node_modules pnpm-lock.yaml
5# 重新安装依赖
6pnpm install

Spark: Cannot safely cast

Spark-sql 执行 sql 语句报:Cannot safely cast xxx string to int.

原因是 spark-sql 执行 sql 有三中模式:ANSI, LEGACY, STRICT。

  • ANSI 模式是标准 sql,不允许不合理的类型转换,与 PostgreSQL 相同;
  • LEGACY 模式允许类型强制转换,只要它是有效的 Cast,这也是 Spark 2.x 中的唯一行为,它与 Hive 兼容;
  • STRICT 模式下 Spark 不允许任何可能的精度损失或数据截断。

解决方法是添加如下配置即可:

1spark.sql.storeAssignmentPolicy=LEGACY

Node: Error message “error:0308010C:digital envelope routines::unsupported”

1export NODE_OPTIONS=--openssl-legacy-provider

Apple Watch 无法更新,一直显示已暂停

在 Apple Watch 中的储存空间下删除之前的更新文件即可。

Apple Map icloud 关闭同步后指南丢失

卸载重装 Apple Map 即可

go build stuck

1go build -v -o bepusdt ./main
2github.com/goccy/go-json/internal/encoder/vm
3
4# stuck here

Try cleaning the build cache to ensure that no corrupted files are causing the problem.

1go clean -cache -modcache -i -r

iterm2 scp 下载每次都要询问 key

1ssh-add -K ~/.ssh/id_rsa

latex 中文编码问题

1\usepackage{CJKutf8}
2
3\begin{document}
4\begin{CJK}{UTF8}{gbsn}
5...
6\end{CJK}
7\end{document}

certbot renew 报错 urlib3 依赖问题

try:

1pip install --upgrade --force-reinstall 'requests==2.6.0' urllib3

I’ve had the same problem https://niuhp.com/other/https-certbot.html

mybatis 判断和语法错误

1<if test="employeeIds != null and employeeIds.size > 0">
2    AND A.EmployeeId in
3    <foreach collection="employeeIds" index="index" item="item" open="(" separator="," close=")">
4        #{item}
5    </foreach>
6</if>
7
8ORDER BY A.FeedId DESC

and employeeIds.size > 0 不可少否则报错:

1org.springframework.jdbc.BadSqlGrammarException

curl 请求路径正确但报 404 或参数反序列化异常

去掉 content-length 限制 -H 'Content-Length: 19'

sqlserver TLSv1 was negotiated. Please update server and client to use TLSv1.2 at minimum.

由于公司的 sqlserver 只支持 tls1 所以需要安装旧版本 driver 并配置 VM option:

1"-Djdk.tls.disabledAlgorithms=SSLv3, TLSv1.1, RC4, DES, MD5withRSA, DH keySize < 1024, EC keySize < 224, 3DES_EDE_CBC, anon, NULL"

driver 使用 8 及以下版本即可。

Unittest test discovery error for workspace

12024-02-05 15:27:34.532 [error]     from typing_extensions import Literal, NotRequired, TypedDict
2  File "/Users/zh/.vscode/extensions/ms-python.python-2024.0.0/pythonFiles/lib/python/typing_extensions.py", line 916
3    def TypedDict(typename, fields=_marker, /, *, total=True, **kwargs):
4                                            ^
5SyntaxError: invalid syntax
6
72024-02-05 15:27:34.544 [error] Subprocess exited unsuccessfully with exit code 1 and signal null on workspace /Users/zh/Codes/jvav. Creating and sending error discovery payload 
8
92024-02-05 15:27:34.544 [error] Unittest test discovery error for workspace:  /Users/zh/Codes/jvav 

Fixed by #21757:

Thank you for your issue report. We are looking into this now! In the meantime, you are likely on the new testing rewrite and this is why you saw a change in behavior. You can opt out of the rewrite as I get this fix in by setting this in your user settings: “python.experiments.optOutFrom”: [“pythonTestAdapter”],. If this doesn’t work let me know as this will mean it is a different issue. Thank you and I will send updates in this thread as I get a fix in.

1// settings.json
2"python.experiments.optOutFrom": ["pythonTestAdapter"]

Gitignore 失效

1git rm -rf --cached .
2git add .

Nginx 相对地址资源引用不走反向代理

1location /pay/usdt/ {
2  sub_filter 'src="/img/'  'src="/pay/usdt/img/';
3  sub_filter 'src="/js/' 'src="/pay/usdt/js/' ;
4  sub_filter 'src="/css/' 'src="/pay/usdt/css/' ;
5  sub_filter_once off;
6  
7  proxy_pass http://127.0.0.1:8080/;
8}

Nginx 无法加载 css

1http {
2    include /etc/nginx/mime.types;
3}

dujiaoka 重启后前台需要重新安装

1# enter dujiaoka container
2echo "ok" > /dujiaoka/install.lock

manpath: can’t set the locale; make sure $LC_* and $LANG are correct

Add these lines to /etc/environment:

1LANG=en_US.utf-8
2LC_ALL=en_US.utf-8

RSSHub commit 不通过

报错提示说缺少某个依赖(pinyin-pro),是文档相关的。

如果修改了文档,那么需要到 website 下运行 pnpm i 安装相关依赖,以便于 commit 检查。

InfluxDb 引号问题

插入数据时,tag 不带引号,field 字符串类型带双引号

查询数据时,字符串类型带单引号

docker-compose 容器内无法连接服务的问题

这是一个 docker-compose 配置文件:

 1version: "3"
 2
 3services:
 4  cache:
 5    image: redis
 6    command: bash -c "mkdir -p ${PATH_REDIS} && touch ${PATH_REDIS}/redis.conf && redis-server ${PATH_REDIS}/redis.conf"
 7    ports:
 8      - "6379:6379"
 9    volumes:
10      - ${HOST_PATH_ROOT}/redis:${PATH_REDIS}
11      - ${HOST_PATH_ROOT}/redis/data:/data
12  web:
13    build: .
14    volumes:
15      - ${HOST_PATH_ROOT}:${PATH_ROOT}
16    depends_on:
17      - cache
18    # network_mode: "host"

我组织了两个容器服务,redis 和 web,在 web 中需要连接到 redis,如果指定的 redis 地址为 127.0.0.1 则无法连接到,报错如下:

1ERROR: 无法连接到 redis 服务: 127.0.0.1:6379 : Error 111 connecting to 127.0.0.1:6379. Connection refused.

这是因为通过 docker-compose 组织的容器,主机名被设置为 cache 和 web,将 127.0.0.1 改为 cache 即可。

XX 不允许发送按键

执行发送按键的 applescript 时可能会失败:

1execution error: “System Events”遇到一个错误:“osascript”不允许发送按键。 (1002)

在隐私与安全性 -> 辅助功能 -> + -> 添加 /usr/bin/osascript 即可

.gitignore 反选的正确用法

排除 /.xxx 下除了 jvm.cfg 的所有文件:

1/.xxx/*
2!/.xxx/jvm.cfg

如果 /.xxx/* 写为 /.xxx/ 或 /.xxx 都将失效,因为这样忽略的是 ./xxx 这个文件夹,而不是整个文件夹下的文件,导致反选无效。

brew 安装报错 curl: (56) Failure when receiving data from the peer

1git config --global http.sslVerify "false"
2git config --global https.sslVerify "false"

oh-my-zsh agnoster 主题乱码问题

从这个链接下载字体文件: https://github.com/lxbrtsch/Menlo-for-Powerline

1mv "Menlo for Powerline.ttf" ~/Library/Fonts

VSCode -> Terminal Font Family 设置字体为 Menlo for Powerline

Terminal -> 设置 -> 字体 -> 更改

docker-compose volume 指定对象为文件时产生的问题

如果指定为文件(命名为 a),且事先没有创建该文件,那么当启动后,docker 将会自动创建一个名为 a 的目录。

这样就读取不到该文件了。

所以,如果指定的对象为文件,建议先创建。

Sqlite3 执行 sql 出错

1sqlite> select * from t_record where comment != "";
2Parse error: no such column:
3  select * from t_record where comment != "";
4                            error here ---^

应该将双引号改为单引号。

根据 SQL 标准,通常在标识符(例如表名或列名)周围使用双引号,而在字符串字面量周围使用单引号。

在 3.41 版本往后 cli 默认禁用了双引号表示字符串,使用单引号就不报错了:https://www.sqlite.org/quirks.html#double_quoted_string_literals_are_accepted

iterm2 无法使用 scp

1# server side
2vim .zprofile
3export iterm2_hostname=your_server_global_ip
4# then relogin

Python 版本冲突问题

certbot 依赖系统 python3 的 requests 包,但它和某个项目依赖的 requests 包版本不一样,如果项目不使用 venv,将会导致 certbot 不可用。

建议在资源允许的情况下所有项目都使用 venv 来隔离 python 环境。

Python requests_cache 在多线程环境下发生错误 “database is locked”

代码包含了使用了 requests_cache 的引用包,而引用包中存在的 requests_cache.install_cache 将影响所有范围的 requests,代码中有着多线程操作,其中某个线程长时间占用 sqlite,锁长时间无法释放,从而导致其它线程无法访问数据库(sqlite3 本身是线程安全的)、CPU 占用率飙升。引用包建议单独使用 requests_cache.CachedSession 完成操作。

FYI, a better option for using requests-cache is using CachedSession directly, instead of patching with install_cache(). It makes it more explicit what you are and aren’t caching, and doesn’t affect downstream requests calls. It’s mostly thread-safe, except for cache_disabled(), as you noted; instead, when you want to make a non-cached request, you can just use a regular requests.Session.

[Errno 24] Too many open files

1ulimit -n 50000

Django 手动删除 migrations 目录后 migrate 无效

1python3 manage.py migrate --fake <app-name> zero
2python3 manage.py makemigrations <app-name>
3python3 manage.py migrate

mac m1 python3.7.9 ModuleNotFoundError: No module named ‘_ctypes’

Use python3.7.12 instead.

Windows 下安装 lxml 报错

1Error while installing lxml through pip: Microsoft Visual C++ 14.0 is required
  1. Run pip install wheel
  2. Download lxml from http://www.lfd.uci.edu/~gohlke/pythonlibs/#lxml, if your python version is 3.5, download lxml-3.6.4-cp35-cp35m-win32.whl (补充一句: 经测试 3.12 版本的安装无法 3.11 版本的)
  3. Run pip install lxml-3.6.4-cp35-cp35m-win32.whl

UnicodeDecodeError: ‘utf-8’ codec can’t decode byte 0xff in position 0: invalid start byte

byte 0xff in position 0 could also mean the file is encoded in UTF-16, then you can do with open(path, encoding=‘utf-16’) as f: instead

包冲突

1ModuleNotFoundError: No module named 'utils.util_bus'; 'utils' is not a package

项目下的 utils 文件夹 <-> pip 某个依赖包中的 utils.py 文件名 “utils” 冲突!

默认先扫描当前目录下包,但是识别不到 utils 包,因为 utils 文件夹下缺失了 __init__.py 文件!

SSLError(SSLCertVerificationError)

使用 requests 库时出现 bug:

1(Caused by SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:997)')))

解决方法:python-requests-throwing-sslerror

From requests documentation on SSL verification:

Requests can verify SSL certificates for HTTPS requests, just like a web browser. To check a host’s SSL certificate, you can use the verify argument:

1requests.get('https://kennethreitz.com', verify=True)

pipenv 无法正常 install

1PS C:\Users\akyna\Codes\test\test_py> pipenv install
2Usage: pipenv install [OPTIONS] [PACKAGES]...
3
4ERROR:: --system is intended to be used for pre-existing Pipfile installation, not installation of specific packages. Aborting.

解决方法:

因为pipenv检测到之前在该目录下创建过了环境,需要先删除之前的环境才可以:

1PS C:\Users\akyna\Codes\test\test_py> pipenv --rm
2Removing virtualenv (C:\Users\akyna\.virtualenvs\test_py-_qApXuy4)...

Python requests 库 headers 字段编码错误

1UnicodeEncodeError: 'latin-1' codec can't encode characters in position 30-34: ordinal not in range(256)

解决方法:

加上.encode(‘utf-8’):

1return {
2    'User-Agent':
3    'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.101 Safari/537.36',
4    'Host': HOST,
5    'Connection': 'close',
6    'X-Requested-With': 'XMLHttpRequest',
7    'Referer': url.encode('utf-8'), ## fix bug
8}

python + crontab 环境变量

crontab运行python时,如果python中使用了环境变量,将无法正常获取。

解决方法:

在crontab中配置好 python 中用到的环境变量:

1## backup
20 1 * * * env code=/root/Codes /bin/bash /root/Codes/scripts/unix/bbak
3## tg send
40 8 * * * env code=/root/Codes /bin/python3 ~/Codes/scripts/py/submit_tg_send.py

Python 关于爬虫所设置的 Headers 中的 UserAgent

这是一个很难以发现的点,但不能说是bug吧。

Headers 中的 UserAgent 可以配置不同的设备端,如果设置了类似于 Android 这样的手机端,那从 requests.get() 返回得到的页面是手机端的界面!如果这个网站手机端的界面和电脑端的界面不是一样的,那么这个问题是很值得注意的。