使用Flask框架创建,
令牌验证:
使用密钥进行简单的令牌验证,确保只有经过授权的请求可以访问该应用。
Flask路由:
- 定义了一个根路由 ('/'),接受GET和POST请求。
在GET请求中,从查询参数获取令牌和文本。- 在POST请求中,从请求体获取令牌和文本。
- 验证令牌的有效性。
- 准备数据,将文本发送到
Gemini
进行处理。 - 对模型生成的文本进行Base64编码。
- 返回经过Base64编码的生成文本。
折腾了半天把
POST
请求改成了GET
,在url里传参数。用了一会儿才想起来长度受限……使用
Base64
编码是因为在IOS
快捷指令获取的时候一直乱码,索性直接先编码、获取再解码。
# 导入Flask、request模块
from flask import Flask, request
import requests
import base64
# 创建Flask应用
app = Flask(__name__)
# 定义生成内容的模型的API地址和请求头信息
url = "https://generativelanguage.googleapis.com/v1/models/gemini-pro:generateContent"
headers = {
"Content-Type": "application/json",
"x-goog-api-key": "YOUR_TOKEN",
}
# 用于验证令牌的密钥(替换为您的密钥)
SECRET_KEY = "YOUR_SECRET_KEY"
# 创建会话对象,用于发送HTTP请求并保持连接池
session = requests.Session()
# 验证令牌的函数
def verify_token(token):
# 在此处实现令牌验证逻辑
return token == SECRET_KEY
# 定义根路由,接受GET和POST请求
@app.route('/', methods=['POST'])
def generate_content():
try:
# 从请求体中获取令牌
token = request.headers.get('Authorization')
# 验证令牌
if not token or not verify_token(token):
return "Unauthorized", 401
# 从请求体中提取文本
text = request.json.get('text', '')
# 准备用于POST请求的数据
data = {
"contents": [
{
"role": "user",
"parts": [
{"text": text}
]
}
]
}
# 使用连接池发送带有数据的POST请求
with session.post(url, headers=headers, json=data) as response:
response.raise_for_status()
result = response.json()
content_text = result.get("candidates", [])[0].get("content", {}).get("parts", [])[0].get("text")
# 对内容进行Base64编码
encoded_content = base64.b64encode(content_text.encode()).decode()
return encoded_content
except Exception as e:
# 记录异常并返回错误响应
app.logger.error(f"Error processing request: {e}")
return "Internal Server Error", 500
# 如果是主程序,则运行Flask应用在指定的主机和端口上
if __name__ == '__main__':
app.run(host='0.0.0.0', port=8000)
附一个 Nginx
配置
server {
listen 80;
server_name YOUR_DOMAIN;
location / {
proxy_pass http://127.0.0.1:8000; # Flask端口
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
location /static {
alias /path/to/your/static/folder; # Replace with the path to your static files
}
location /media {
alias /path/to/your/media/folder; # Replace with the path to your media files
}
location ~ /\.ht {
deny all;
}
}
没有评论