Python Flask:TypeError: unsupported operand type(s) for -: ‘str‘ and ‘int‘

背景

项目中常见的分页功能,代码如下:

c 复制代码
# 收藏列表
@blog_base_blueprint.route('/resource_like_list/<int:user_id>', methods=['POST'])
def getResourceLikeList(user_id):

    page_size = request.form.get('page_size', default=2)

    page_num = request.form.get('page_num', default=1)

    offset = (page_num - 1) * page_size

    print(offset)
    print(page_num)
    print(page_size)

    logs = models.ResourceLikeLog.query.filter_by(user_id=user_id).filter_by(delete_flag=0).order_by(models.ResourceLikeLog.id.desc()).offset(
        offset).limit(page_size)

    return jsonify({
        'code': 1,
        'msg': '成功',
        'data': [log.to_format() for log in logs]
    })

项目启动时可以使用,但是我在postman中传了page_num的参数,然后就报异常TypeError: unsupported operand type(s) for -: 'str' and 'int';

根据异常信息,是类型的的问题,需要将str转为int,这里还是很好处理的,在接受参数的时候,处理一下就可以喽。

request.form.get()

点到源码,

c 复制代码
    def get(self, key, default=None, type=None):
        """Return the default value if the requested data doesn't exist.
        If `type` is provided and is a callable it should convert the value,
        return it or raise a :exc:`ValueError` if that is not possible.  In
        this case the function will return the default as if the value was not

        :param key: The key to be looked up.
        :param default: The default value to be returned if the key can't
                        be looked up.  If not further specified `None` is
                        returned.
        :param type: A callable that is used to cast the value in the
                     :class:`MultiDict`.  If a :exc:`ValueError` is raised
                     by this callable the default value is returned.
        """
        try:
            rv = self[key]
        except KeyError:
            return default
        if type is not None:
            try:
                rv = type(rv)
            except ValueError:
                rv = default
        return rv

能看到这个方法的参数:有默认值,还有一个参数类型的参数,用来强制转换参数类型,调整代码为:

c 复制代码
    page_size = request.form.get('page_size', default=2, type=int)

    page_num = request.form.get('page_num', default=1, type=int)
相关推荐
用户8356290780516 小时前
Python 实现 PDF 文件加密与解密方法
后端·python
用户8356290780517 小时前
使用 Python 冻结与拆分 Excel 窗格教程
后端·python
你好潘先生15 小时前
别再记命令了,用 yeero do 说句人话就能跑脚本,而且不烧 token
服务器·python·命令行
Agent_大师15 小时前
WebSocket 行情重连成功,K线缺口不会自动消失
python
荣码15 小时前
LLM结构化输出:让AI返回JSON而不是废话,我踩了4个坑
java·python
copyer_xyf15 小时前
FastAPI 如何连接 MySQL
后端·python
apocelipes1 天前
常用编程语言和库的正则表达式性能对比
c语言·c++·python·性能优化·golang·开发工具和环境
用户8356290780511 天前
使用 Python 在 PDF 中创建与管理书签
后端·python
MeixianAgent1 天前
Python 回测数据入口怎么验?历史 K 线入库前先做 5 个检查
后端·python
咕白m6252 天前
用 Python 实现一键批量查找与替换 Excel 数据
后端·python