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)
相关推荐
DeepVisionary几秒前
8 月 20 款大模型同台:OpenAI 拆出三档家族,IBM 押注 512K 密集推理,Meta 回头开源 30B
python·自动化
未若君雅裁1 分钟前
自定义中间件:Node-style 与 Wrap-style 钩子全解析
python·中间件·langchain
奈斯先生Vector3 分钟前
本地图片识别怎么接入多模态 AI?用 Python API 理解 GPT-4o Vision 的真实工作流
开发语言·人工智能·windows·python·网络协议·http·aigc
OPEN-F7 分钟前
C++17新特性精讲:结构化绑定、if constexpr与实用类型
开发语言·c++
测试老哥9 分钟前
Pytest 之assert断言的使用
自动化测试·软件测试·python·测试工具·测试用例·pytest·接口测试
OPEN-F10 分钟前
C++并发编程:线程与互斥锁
开发语言·c++
俊昭喜喜里12 分钟前
C#中的decimal
开发语言·c#
2601_9563198822 分钟前
先把交易想法说清,再让 Python 承接
人工智能·python
catchadmin23 分钟前
免费可商用 PHP 管理后台 CatchAdmin V5.4.0 发布,新增短信服务能力
开发语言·php
小白学大数据33 分钟前
API 调用错误处理实战:分层定位、有纪律地重试与可观测性设计
开发语言·网络·人工智能