如何在多个GitHub项目中共享可统一维护的变量?
解决方案:基于Flask搭建共享变量管理服务
核心思路
用Flask做后端,搭配轻量的SQLite数据库(无需额外安装服务),同时提供API接口供代码读取变量,以及网页界面实现手动编辑变量,完全覆盖你的两个需求,且实现成本极低。
具体实现步骤
1. 项目结构
variable-manager/ ├── app.py # Flask主程序 ├── templates/ │ └── index.html # 手动编辑的网页界面 └── variables.db # SQLite数据库(自动生成)
2. Flask后端代码(app.py)
from flask import Flask, render_template, request, jsonify import sqlite3 app = Flask(__name__) # 初始化数据库(首次启动自动创建表和示例变量) def init_db(): conn = sqlite3.connect('variables.db') c = conn.cursor() c.execute('''CREATE TABLE IF NOT EXISTS variables (key TEXT PRIMARY KEY, value TEXT)''') # 插入示例XPath变量,可根据需求修改 c.execute("INSERT OR IGNORE INTO variables VALUES (?, ?)", ("login_xpath", "//input[@id='username']")) conn.commit() conn.close() # 供代码调用的变量读取API @app.route('/api/get/<key>', methods=['GET']) def get_variable(key): conn = sqlite3.connect('variables.db') c = conn.cursor() c.execute("SELECT value FROM variables WHERE key=?", (key,)) result = c.fetchone() conn.close() if result: return jsonify({"key": key, "value": result[0]}), 200 return jsonify({"error": "Variable not found"}), 404 # 手动编辑变量的网页界面 @app.route('/', methods=['GET', 'POST']) def edit_variables(): if request.method == 'POST': key = request.form['key'] value = request.form['value'] conn = sqlite3.connect('variables.db') c = conn.cursor() # 存在则更新,不存在则新增 c.execute("REPLACE INTO variables VALUES (?, ?)", (key, value)) conn.commit() conn.close() # 查询所有变量并渲染到页面 conn = sqlite3.connect('variables.db') c = conn.cursor() c.execute("SELECT * FROM variables") variables = c.fetchall() conn.close() return render_template('index.html', variables=variables) if __name__ == '__main__': init_db() # 0.0.0.0允许局域网内设备访问,端口可自定义 app.run(host='0.0.0.0', port=5000, debug=True)
3. 网页编辑界面(templates/index.html)
<!DOCTYPE html> <html> <head> <title>共享变量管理</title> <style> body { font-family: Arial, sans-serif; max-width: 800px; margin: 20px auto; padding: 0 20px; } .variable-item { margin: 15px 0; padding: 10px; border: 1px solid #ddd; border-radius: 4px; } input { padding: 8px; margin-right: 10px; width: 220px; } button { padding: 8px 15px; background: #007bff; color: white; border: none; border-radius: 4px; cursor: pointer; } </style> </head> <body> <h1>共享变量管理</h1> <form method="POST"> <input type="text" name="key" placeholder="变量名(如login_xpath)" required> <input type="text" name="value" placeholder="变量值(如XPath字符串)" required> <button type="submit">保存/更新变量</button> </form> <h2>已存在的变量</h2> {% for var in variables %} <div class="variable-item"> <strong>{{ var[0] }}:</strong> {{ var[1] }} </div> {% endfor %} </body> </html>
4. 在Selenium代码中读取变量
import requests from selenium.webdriver.common.by import By def get_shared_variable(key): try: # 替换为你的Flask服务地址 response = requests.get(f"http://你的服务器IP:5000/api/get/{key}") if response.status_code == 200: return response.json()['value'] # 服务返回错误时,使用本地默认值兜底 return "//input[@id='username']" except requests.exceptions.RequestException: # 服务不可用时的降级处理 return "//input[@id='username']" # 使用示例 login_xpath = get_shared_variable("login_xpath") driver.find_element(By.XPATH, login_xpath).send_keys("test_user")
部署与优化建议
- 开发阶段直接运行
python app.py启动,生产环境可改用Gunicorn+Nginx部署,提升稳定性。 - 如果需要权限控制,可添加简单的HTTP Basic认证或Flask-Login实现登录验证,内部测试场景也可直接通过IP白名单限制访问。
- 若变量数量多、查询频繁,可添加Redis缓存减少数据库访问压力。
关于RapidAPI的说明
RapidAPI是第三方API聚合平台,适合调用公开API或对外发布API,对于内部共享变量的场景,直接用Flask搭建私有服务更灵活,完全能满足你的需求,无需依赖第三方平台。
内容的提问来源于stack exchange,提问作者tonitone120
相关产品推荐
相关产品推荐

