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

基于AWS Glue从S3动态生成Botify查询JSON请求

AWS Glue中动态生成Botify BQL请求JSON的实现

核心步骤

  • 从S3读取预存的BQL查询文本
  • 构造符合Botify API要求的JSON请求体,替换占位符myId为真实ID
  • 发送POST请求到Botify API

代码实现

1. 导入依赖库

import boto3
import requests
import json
from botocore.exceptions import ClientError

2. 读取S3中的查询文件

这个函数负责从指定S3桶读取查询文本:

def read_query_from_s3(bucket_name, file_key):
    s3_client = boto3.client('s3')
    try:
        obj = s3_client.get_object(Bucket=bucket_name, Key=file_key)
        # 读取并解码文件内容,去除首尾空白字符
        query_content = obj['Body'].read().decode('utf-8').strip()
        return query_content
    except ClientError as e:
        print(f"读取S3文件失败: {e.response['Error']['Message']}")
        return None

3. 构造请求并调用API

主函数完成参数配置、JSON构造和请求发送:

def main():
    # 配置参数,替换成你的实际信息
    S3_BUCKET = "your-s3-bucket-name"
    QUERY_FILE_PATH = "path/to/your/bql_query.txt"  # S3中文件的键路径
    BOTIFY_API_ENDPOINT = "https://api.botify.com/v1/projects/{project_id}/bql/query"
    REAL_PROJECT_ID = "your-actual-project-id"  # 替换myId的真实ID
    BOTIFY_API_TOKEN = "your-botify-api-token"

    # 获取S3中的查询内容
    bql_query = read_query_from_s3(S3_BUCKET, QUERY_FILE_PATH)
    if not bql_query:
        print("未获取到查询内容,程序退出")
        return

    # 构造请求JSON(根据Botify API要求调整结构)
    request_payload = {
        "project_id": REAL_PROJECT_ID,  # 替换占位符myId
        "query": bql_query,
        "format": "json"  # 按需调整返回格式
    }

    # 发送POST请求
    headers = {
        "Authorization": f"Token {BOTIFY_API_TOKEN}",
        "Content-Type": "application/json"
    }
    try:
        response = requests.post(
            BOTIFY_API_ENDPOINT.format(project_id=REAL_PROJECT_ID),
            headers=headers,
            json=request_payload
        )
        response.raise_for_status()  # 触发HTTP错误异常
        print("请求成功,响应结果:")
        print(json.dumps(response.json(), indent=2))
    except requests.exceptions.RequestException as e:
        print(f"请求失败: {str(e)}")
        if response:
            print(f"API状态码: {response.status_code}")
            print(f"API响应内容: {response.text}")

if __name__ == "__main__":
    main()

关键注意事项

  • IAM权限:确保Glue作业的IAM角色拥有AmazonS3ReadOnlyAccess(或更精细的s3:GetObject权限),能访问目标S3桶
  • Botify配置:确认API令牌拥有BQL查询权限,API端点和请求结构与Botify官方文档一致
  • 异常处理:代码中加入了基础的错误捕获,可根据需求扩展日志记录或重试逻辑

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 03:10:09