Flask:测试需要登录用户的 AJAX 调用

Flask: testing an AJAX call that requires a logged in user

我正在尝试使用(并测试)一个 AJAX 调用。我不是专业人士,希望我能正确使用术语。

我有一个 Flask 应用程序,它从一个只有登录用户才能访问的视图(使用 JQuery)进行 AJAX 调用:

$.ajax({
    type: "POST",
    url: "/_get_data",
    data: JSON.stringify({begin_date: begin_date,
                          end_date: end_date}, null, '\t'),
    contentType: "application/json;charset=UTF-8",
    dataType: "json",
    success: function(response){
         // do something with the results
         }
    });

端点函数需要访问记录的用户数据。使用 Flask-Login,它存储在 current_user 代理中(下面的函数只是为了示例,我知道查询可以以不同的方式完成):

@app.route('/_get_data', methods=['GET', 'POST'])
def get_data():
    param = request.get_json()
    # get data from the DB for the current user
    data = db.session.query(Orders).filter(Orders.customer_id == current_user.id).all()
    # ...
    # Do calculations on data and return the results
    # ...
    return jsonify(results = results)

我有两个问题:

  1. 依赖 Flask-Login current_user 代理是一种安全的方法吗?或者用 AJAX 调用发送 current_user id,并在 get_data() 函数内查询用户的数据库会更好吗?然而,对于第二种方法,这意味着在 ajax 调用中明确用户 ID。
  2. 从视图来看,函数 get_data() 响应正确。但是,如何对 get_data() 函数进行单元测试?我面临的问题是 "pass" current_user 到 get_data() 函数。我正在使用 pytest,并四处搜索我发现 solutions like 以下内容:

.

app = create_app(DevConfig)
data = {"begin_date": "", "end_date": ""}
with app.test_client() as tester:
    with tester.session_transaction() as sess:
        sess['user_id'] = 1
        sess['_fresh'] = True
        response = tester.get('/_get_data',
                    content_type='application/json;charset=UTF-8',
                    headers={'X-Requested-With': 'XMLHttpRequest',
                             'Content-Type': 'application/json'},
                    data=json.dumps(data))

但它对我不起作用:get_data() 函数获取一个 'AnonymousUserMixin' 对象而不是登录用户。

抱歉我的技术含量低。

第二个问题我已经解决了。这只是 with 语句中代码缩进的问题。 正确的版本是,如 中所述(注意 response 的标识):

app = create_app(DevConfig)
data = {"begin_date": "", "end_date": ""}
with app.test_client() as tester:
    with tester.session_transaction() as sess:
        sess['user_id'] = 1
        sess['_fresh'] = True
    response = tester.get('/_get_data',
                content_type='application/json;charset=UTF-8',
                headers={'X-Requested-With': 'XMLHttpRequest',
                         'Content-Type': 'application/json'},
                data=json.dumps(data))

然而,我的第一个问题仍然存在。