Skip to main content
 首页 » 编程设计

php之AWS Flask session 不会从 PHP 请求中持久化

2025年12月25日54unruledboy

我将 Flask 应用程序部署到 AWS lambda

@bp_google_routes.route('/is_authorized', methods=('POST', )) 
def google_is_authorized(): 
    data = json.loads(request.data) 
 
    flask.session['user_email'] = data['email'] 
    authorized = aws_handler.already_authorized(data['email']) 
    return jsonify({'authorized': authorized}) 
 
 
@bp_google_routes.route('/authorize', methods=('GET', )) 
def google_authorize(): 
    if 'user_email' not in flask.session: 
        abort(404) 
 
    return 'All good' 

我正在通过 PHP 后端访问应用程序以首先检查授权 is_authorized这是一个 POST请求并将存储 email在 session 中。

然后在我第二次调用 authorize 之后由于 session 中显然没有电子邮件,因此总是中止。但是应该从第一个请求开始:
<?php 
    $data = array("email" => "test@test.com");                                                                   
    $data_string = json_encode($data);  
    $aws_endpoint = "https://.../is_authorized"; 
    $aws_endpoint_auth = "https://.../authorize"; 
 
    $ch = curl_init(); 
    curl_setopt($ch, CURLOPT_URL, $aws_endpoint); 
    curl_setopt($ch, CURLOPT_POST, 1); 
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string); 
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
    curl_setopt($ch, CURLOPT_HTTPHEADER, array( 
        'Content-Type: application/json') 
    ); 
 
    $response = curl_exec($ch); 
    $err = curl_error($ch); 
 
    curl_close ($ch); 
 
    if ($err) { 
        echo "There was an error accessing the requested information!"; 
    } else { 
        $result = json_decode($response); 
        if (!$result->authorized) { 
            $ch = curl_init(); 
            curl_setopt($ch, CURLOPT_URL, $aws_endpoint_auth); 
            curl_setopt($ch, CURLOPT_HEADER, true); 
            curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); 
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
            $result = curl_exec($ch); 
 
            echo $result; 
            print_r('False'); 
        } else { 
            print_r('True'); 
        } 
    } 
?> 

为什么 session 在两个调用之间不持久?

请您参考如下方法:

你需要告诉curl使用 cookiejar 保存 cookie .

将下面的行添加到文件的顶部:

$cookieFileName = tempnam('/tmp','cookies.txt'); 
 

然后添加 curl_setopt在下面调用您的每个电话:

curl_setopt($ch, CURLOPT_COOKIEJAR, $cookieFileName);  
curl_setopt($ch, CURLOPT_COOKIEFILE, $cookieFileName); 

这样,curl 将在请求之间存储和重用 cookie。