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

22 篇文章 0 订阅
19 篇文章 3 订阅

背景

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

# 收藏列表
@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()

点到源码,


    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

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

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

    page_num = request.form.get('page_num', default=1, type=int)
java.lang.IllegalStateException: Failed to execute CommandLineRunner at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:798) [spring-boot-2.3.4.RELEASE.jar:2.3.4.RELEASE] at org.springframework.boot.SpringApplication.callRunners(SpringApplication.java:779) [spring-boot-2.3.4.RELEASE.jar:2.3.4.RELEASE] at org.springframework.boot.SpringApplication.run(SpringApplication.java:322) [spring-boot-2.3.4.RELEASE.jar:2.3.4.RELEASE] at org.springframework.boot.SpringApplication.run(SpringApplication.java:1237) [spring-boot-2.3.4.RELEASE.jar:2.3.4.RELEASE] at org.springframework.boot.SpringApplication.run(SpringApplication.java:1226) [spring-boot-2.3.4.RELEASE.jar:2.3.4.RELEASE] at com.unkown.data.hw.ipran.straight.collect.UnkownDataHwIpranStraightCollectApplication.main(UnkownDataHwIpranStraightCollectApplication.java:39) [classes/:na] Caused by: feign.FeignException$InternalServerError: [500 INTERNAL SERVER ERROR] during [POST] to [http://ants-flask/api/collect/endpoint] [RemoteIpranScanService#endpoint(String)]: [<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <title>TypeError: unsupported operand type(s) for +: 'int' and 'str' // Wer... (20567 bytes)] at feign.FeignException.serverErrorStatus(FeignException.java:231) ~[feign-core-10.10.1.jar:na] at feign.FeignException.errorStatus(FeignException.java:180) ~[feign-core-10.10.1.jar:na] at feign.FeignException.errorStatus(FeignException.java:169) ~[feign-core-10.10.1.jar:na] at feign.codec.ErrorDecoder$Default.decode(ErrorDecoder.java:92) ~[feign-core-10.10.1.jar:na] at feign.AsyncResponseHandler.handleResponse(AsyncResponseHandler.java:96) ~[feign-core-10.10.1.jar:na] at feign.SynchronousMethodHandler.executeAndDecode(SynchronousMethodHandler.java:138) ~[feign-core-10.10.1.jar:na] at feign.SynchronousMethodHandler.invoke(SynchronousMethodHandler.java:89) ~[feign-core-10.10.1.jar:na] at com.alibaba.cloud.sentinel.feign.SentinelInvocationHandler.invoke(SentinelInvocationHandler.java:107) ~[spring-cloud-starter-alibaba-sentinel-2.2.3.RELEASE.jar:2.2.3.RELEASE] at com.sun.proxy.$Proxy131.endpoint(Unknown Source) ~[na:na] at com.unkown.data.hw.ipran.straight.collect.controller.RTrsHwIpranCircuitController.IpranSend(RTrsHwIpranCircuitController.java:94) ~[classes/:na] at com.unkown.data.hw.ipran.straight.collect.MyRunner.run(MyRunner.java:22) ~[classes/:na] at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:795) [spring-boot-2.3.4.RELEASE.jar:2.3.4.RELEASE] ... 5 common frames omitted
06-06
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值