You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flask更新接口报错:'NoneType' object has no attribute 'username'

Flask PUT接口更新行程时出现AttributeError问题排查与解决

问题详情

我在Flask中编写了用于更新特定行程的PUT接口(路径为/trips/<int:trip_id>),代码如下:

# Update Route for a particular trip
@app.route('/trips/<int:trip_id>', methods=['PUT'])
def update_trip(trip_id):
    trip = trips.get(trip_id) #query from the database
    data = request.get_json()
    
    trip.username = data['username']
    trip.start_at = datetime.strptime(data['start_at'], '%Y-%m-%d %H:%M:%S')
    trip.from_gps = data['from_gps']
    trip.end_at = datetime.strptime(data['end_at'], '%Y-%m-%d %H:%M:%S')
    trip.distance = data['distance']

    return jsonify({'message': 'Trip updated successfully!'})

使用Postman发送Raw JSON格式的PUT请求时,控制台出现报错:

File "E:\Wlink\Location_Tra\backend\main.py", line 608, in update_trip
trip.username = data['username']
AttributeError: 'NoneType' object has no attribute 'username'

Postman请求截图:
Postman中的PUT请求

解决步骤

  • 确认行程ID存在性:报错核心原因是trips.get(trip_id)返回了None,也就是数据库里找不到对应trip_id的行程记录。先核对请求URL中的trip_id是否确实存在于数据库中,比如你请求的是/trips/5,就去数据库查有没有id为5的行程数据。
  • 添加空值校验逻辑:在操作trip对象前先判断是否为None,提前返回错误提示避免程序崩溃,同时可以增加请求参数的必填字段校验:
    # Update Route for a particular trip
    @app.route('/trips/<int:trip_id>', methods=['PUT'])
    def update_trip(trip_id):
        trip = trips.get(trip_id) #query from the database
        if not trip:
            return jsonify({'error': f'ID为{trip_id}的行程不存在'}), 404
        
        data = request.get_json()
        # 校验必填字段是否齐全
        required_fields = ['username', 'start_at', 'from_gps', 'end_at', 'distance']
        for field in required_fields:
            if field not in data:
                return jsonify({'error': f'缺少必填字段:{field}'}), 400
        
        try:
            trip.username = data['username']
            trip.start_at = datetime.strptime(data['start_at'], '%Y-%m-%d %H:%M:%S')
            trip.from_gps = data['from_gps']
            trip.end_at = datetime.strptime(data['end_at'], '%Y-%m-%d %H:%M:%S')
            trip.distance = data['distance']
            # 注意:添加数据库提交操作,比如用SQLAlchemy的话要加db.session.commit()
            return jsonify({'message': 'Trip updated successfully!'})
        except ValueError as e:
            return jsonify({'error': f'日期时间格式错误:{str(e)}'}), 400
    
  • 补充数据库提交操作:原代码没有提交修改到数据库的步骤,就算修改了trip对象,数据也不会持久化到数据库里,要根据你使用的数据库工具添加提交,比如SQLAlchemy需要调用db.session.commit()。
  • 核对Postman请求URL:确认请求URL中的trip_id输入正确,和数据库中存在的ID一致,避免因为ID输错导致找不到记录。

内容的提问来源于stack exchange,提问作者bibashmanjusubedi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.21 14:31:10