【问题标题】:Getting only first value of json file仅获取 json 文件的第一个值
【发布时间】:2022-07-27 23:13:54
【问题描述】:

提前致谢。

我有一个 json 文件存储在 s3 存储桶中。我指的是任何重定向。下面是一个示例 json 文件。

{
  "redirects" :[
  {
    "url" : "/xxx/index.html", 
    "redirect_url": "/yyy/index.html", 
    "statusCode": 302 
  },
  {
    "url" : "/aaaa/index.html",
    "redirect_url": "/bbb/index.html", 
    "statusCode": 301      
  },
  {
    "url" : "/ccc/ddd/index.html", 
    "redirect_url": "/eeee/index.html", 
    "statusCode": 301 
  }
]
}

但是,lambda 只获取重定向的第一个条目,其余部分被忽略。下面是我用于重定向的 python 脚本。我前面有云端。

import boto3
import json
s3 = boto3.resource('s3')
base_url= "testsite_com" ###Cannot post any site address on stackoverflow

def lambda_handler (event, context):
    request = event['Records'][0]['cf']['request']
    print(event)
    content_object = s3.Object('cbtest.cb-infra.com', 'config/redirects.json')
    file_content = content_object.get()['Body'].read().decode('utf-8')
    json_content = json.loads(file_content)

    for entries in json_content["redirects"]:
        old_url = entries["url"]
        redirect_uri = entries["redirect_url"]
        status_code = entries["statusCode"]
        new_url= base_url + redirect_uri
        print(old_url)
        if request["uri"] == old_url :
            response = {
                    'status': status_code,
                    'statusDescription': 'Found',
                    'headers': {
                        'location': [{
                            'key': 'Location',
                            'value': new_url
                        }]
                    }
                }
            print(response)
            print("uri matched: ", request["uri"], redirect_uri)
            return response    
        else : 
            print("uri : ", request["uri"])
            return request      

重定向仅适用于第一个 url,即 /xxx/index.html 有效。其余部分没有被重定向。

【问题讨论】:

    标签: python python-3.x lambda amazon-cloudfront aws-lambda-edge


    【解决方案1】:

    for 循环中的第一次迭代之后,您将返回,来自ifelse 语句,在Python 中,函数在返回后退出。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-05-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-28
      • 2022-01-03
      • 1970-01-01
      相关资源
      最近更新 更多