如何在Python版Google Ads API中规避SQL注入?
Google Ads API 中的注入防护与类似 cursor.execute 的机制
有没有类似 cursor.execute 的机制?
Google Ads API 并非直接操作 SQL 数据库的工具,它是对接 Google Ads 平台的 gRPC/REST 接口,使用Google Ads Query Language (GAQL) 完成数据查询,因此没有和数据库cursor.execute完全对应的机制。但官方 Python 客户端提供了参数化查询的能力,作用和cursor.execute的参数绑定一致——自动处理参数转义,避免注入风险。
如何实现类似的防注入方式?
1. 查询操作(GAQL):用参数绑定替代字符串拼接
不要手动把变量拼进 GAQL 字符串,而是用:作为占位符,再通过param_bindings传递参数值,客户端会自动处理转义,防止恶意输入被解析为 GAQL 语句的一部分。
示例代码:
from google.ads.googleads.client import GoogleAdsClient # 初始化客户端(需提前配置好认证信息) client = GoogleAdsClient.load_from_storage() google_ads_service = client.get_service("GoogleAdsService") # 模拟可能带注入风险的输入 unsafe_campaign_id = "12345' OR 1=1" # 带参数占位符的GAQL查询 query = """ SELECT ad_group.id, ad_group.name FROM ad_group WHERE campaign.id = :campaign_id """ # 创建参数绑定对象,关联占位符和实际值 string_param = client.get_type("StringParameter") string_param.name = "campaign_id" string_param.value = unsafe_campaign_id # 执行查询,传入参数绑定列表 response = google_ads_service.search( customer_id="YOUR_CUSTOMER_ID", query=query, param_bindings=[string_param] ) # 遍历结果 for row in response: print(f"Ad Group ID: {row.ad_group.id}, Name: {row.ad_group.name}")
2. 增删改操作:用结构化对象传递数据
Google Ads API 的修改、创建操作不需要写类似 SQL 的语句,而是通过构建官方提供的资源对象(比如Campaign、AdGroup)来传递数据。这种方式本身就规避了注入风险,因为你是通过 API 的结构化字段赋值,而非拼接字符串。
示例(更新广告系列名称):
from google.ads.googleads.client import GoogleAdsClient client = GoogleAdsClient.load_from_storage() campaign_service = client.get_service("CampaignService") # 模拟带注入风险的名称 unsafe_campaign_name = "Test Campaign' -- DROP TABLE ..." target_campaign_id = 12345 # 创建更新操作对象 campaign_operation = client.get_type("CampaignOperation") campaign = campaign_operation.update campaign.id = target_campaign_id campaign.name = unsafe_campaign_name # 指定要更新的字段(字段掩码) update_mask = client.get_type("FieldMask") update_mask.paths.append("name") # 执行更新 response = campaign_service.mutate_campaigns( customer_id="YOUR_CUSTOMER_ID", operations=[campaign_operation] ) print(f"Updated campaign: {response.results[0].resource_name}")
内容的提问来源于stack exchange,提问作者Louis
相关产品推荐
相关产品推荐

