UnboundLocalError:无法访问未与值关联的局部变量“request”

问题描述 投票:0回答:1

我正在使用 Python 3.12 和 Flask,
这是带有 mongo db 的 Flask 应用程序。

我在 Flask 应用程序中遇到

UnboundLocalError
。当我尝试在视图函数之一中访问
request
对象时,会发生错误。这是完整的回溯:

该错误表明

request
对象在
get_user_contribution_requests
函数中不可用。不过,我已经从
request
导入了
flask
,我相信它应该是可以访问的。


   File "/Users/divakaryadav/road-guardian/backend/env/lib/python3.12/site-packages/flask/app.py", line 880, in full_dispatch_request
    rv = self.dispatch_request()
         ^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/divakaryadav/road-guardian/backend/env/lib/python3.12/site-packages/flask/app.py", line 865, in dispatch_request
    return self.ensure_sync(self.view_functions[rule.endpoint])(**view_args)  # type: ignore[no-any-return]
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/divakaryadav/road-guardian/backend/env/lib/python3.12/site-packages/flask_jwt_extended/view_decorators.py", line 170, in decorator
    return current_app.ensure_sync(fn)(*args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/divakaryadav/Documents/GitHub/Sync1.0/backend/app.py", line 163, in get_user_contribution_requests
    page_str = request.args.get('page', 1)
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^
UnboundLocalError: cannot access local variable 'request' where it is not associated with a value

这是我的代码的相关部分:

@app.route('/user-contribution-requests', methods=['GET'])
@jwt_required()
def get_user_contribution_requests():
    contribution_requests = db.contribution_requests
    user_id = get_jwt_identity()
    page_str = request.args.get('page', 1)
    page = int(page_str)
    rows_per_page = int(request.args.get('rowsPerPage', 5))
    
    total_count = contribution_requests.count_documents({'user_id': user_id})
    requests = list(contribution_requests.find({'user_id': user_id})
                    .skip((page - 1) * rows_per_page)
                    .limit(rows_per_page))
    
    for request in requests:
        request['_id'] = str(request['_id'])
        
        if 'project_id' in request:
            request['project_id'] = str(request['project_id'])
        
        # Convert date strings to datetime objects
        for date_field in ['request_creation_date', 'created_at', 'updated_at']:
            if date_field in request and isinstance(request[date_field], str):
                try:
                    request[date_field] = datetime.fromisoformat(request[date_field])
                except ValueError:
                    request[date_field] = None
        
        # Format dates as ISO strings
        request['request_creation_date'] = request['request_creation_date'].isoformat() if request['request_creation_date'] else None
        request['created_at'] = request['created_at'].isoformat() if request['created_at'] else None
        request['updated_at'] = request['updated_at'].isoformat() if request['updated_at'] else None

    return jsonify({'contribution_requests': requests, 'totalCount': total_count}), 200
python-3.x flask
1个回答
0
投票

导致此错误的最可能原因是名称冲突。在您的函数中,您使用 request 作为循环中的变量名称。

for request in requests:
request['_id'] = str(request['_id'])

将请求重命名为 req,它应该按预期工作

for req in requests:
    req['_id'] = str(req['_id'])
© www.soinside.com 2019 - 2024. All rights reserved.