调用Gemini API遇403(API_KEY_HTTP_REFERRER_BLOCKED)错误求助
解决Gemini API调用时的403(API_KEY_HTTP_REFERRER_BLOCKED)错误
问题描述
部署在IP为158.38.176.102的服务器上的Python Flask项目调用Gemini API时,出现以下403错误:
"error": "403 Requests from referer are blocked. [reason:
"API_KEY_HTTP_REFERRER_BLOCKED"
domain:
"googleapis.com"
metadata {
key: "service"
value:
"generativelanguage.googleapis.com"
}
metadata {
key:
"consumer"
value:
"projects/883817471146"
}
]"
项目核心代码如下:
from flask import Flask, jsonify, request from flask_restful import reqparse from dotenv import load_dotenv from PIL import Image import google.generativeai as genai import io genai.configure(api_key="Example") app = Flask(__name__) def get_gemini_response(category, title, description, image): model = genai.GenerativeModel('gemini-1.5-flash') # Combining category, title, and description into a prompt input_text = f"Category: {category}\nTitle: {title}\nDescription: {description}" if input_text: response = model.generate_content([f"User: {input_text}", image]) else: response = model.generate_content(image) return response.text @app.route('/check-category-post', methods=['POST']) def evaluate_image(): try: # Extract form data and file category = request.form.get('category') title = request.form.get('title') description = request.form.get('description') file = request.files.get('image') print("Category:", category) print("Title:", title) print("Description:", description) print("File:", file) if not category or not title or not description or not file: return jsonify({"error": "Category, title, description, and image file are required"}), 400 # Open the image image = Image.open(io.BytesIO(file.read())) # Pass the category, title, description, and image to the Gemini model response_text = get_gemini_response(category, title, description, image) return jsonify({"response": response_text}), 200 except Exception as e: print("Error:", str(e)) # Log the error for debugging return jsonify({"error": str(e)}), 500 @app.route('/check-category-post', methods=['POST']) def check_category_post(): # Log headers and raw data for debugging print("Headers:", request.headers) print("Raw Data:", request.data) # Set up reqparse parser = reqparse.RequestParser() parser.add_argument('cpf', type=str, required=True, location='args') # Expecting args args = parser.parse_args() return jsonify({"message": "Success", "data": args}), 200 if __name__ == '__main__': app.run(host='0.0.0.0', port=5000, debug=True)
Google Cloud控制台API设置截图:
解决方案
这个错误是因为你的Gemini API密钥设置了HTTP referer限制,但服务器端调用API时没有携带符合要求的referer头,或者当前请求的来源不在允许列表中。
方法1:调整API密钥的referer限制设置
- 登录Google Cloud控制台,找到对应项目
projects/883817471146的API密钥。 - 在密钥的"应用限制"部分,针对
generativelanguage.googleapis.com服务:- 如果不需要referer限制,选择"无限制"(不推荐生产环境使用)。
- 如果需要保留限制,添加你的服务器IP或绑定域名到允许列表,比如
https://158.38.176.102/*。
- 保存设置后,等待几分钟让配置生效。
方法2:在请求中手动添加合法的referer头
使用google.generativeai SDK时,可以通过配置客户端选项添加referer头:
import google.generativeai as genai from google.api_core.client_options import ClientOptions # 配置客户端选项,添加合法的referer client_options = ClientOptions(api_endpoint="generativelanguage.googleapis.com") client_options.headers = {"Referer": "https://158.38.176.102/"} genai.configure( api_key="你的实际API密钥", client_options=client_options )
额外注意事项
- 代码中存在两个相同路径
/check-category-post的POST路由,Flask只会加载最后定义的check_category_post函数,导致前面的evaluate_image无法生效,需修改其中一个路由路径避免冲突。 - 不要硬编码API密钥,使用
dotenv加载环境变量保障密钥安全:import os load_dotenv() genai.configure(api_key=os.getenv("GEMINI_API_KEY"))
内容的提问来源于stack exchange,提问作者Shehbaz Khanani
相关产品推荐
相关产品推荐

