Flask实现根据Hive表database_table的field_id动态查询子表并在UI展示结果的完整代码需求
Flask实现根据Hive表database_table的field_id动态查询子表并在UI展示结果的完整代码需求
我来帮你完善这个实现,让它完全满足你的动态查询需求。首先先明确你的场景:你是Flask新手,有一个Hive表database_table,结构和数据如下:
| id | field_id | table_name | schema_name |
|---|---|---|---|
| 1 | 1 | employee_table | employee |
| 2 | 2 | department_table | employeee |
| 3 | 3 | statistics_table | employeee |
你的需求是:在UI中选择某个field_id后,程序自动从database_table找到对应的子表名,查询该子表的内容并展示在页面上。比如选field_id=1时,就查询employee_table并返回结果。
你现有的代码已经有了Hive连接的基础封装,但还缺少动态参数接收、子表查询逻辑和前端UI部分,下面是完整的可运行解决方案:
一、完整后端代码(app.py)
这段代码完善了Hive连接封装,添加了动态接收field_id的路由,实现了两步查询逻辑:先找目标表名,再查子表数据:
from pyhive import hive from flask import Flask, current_app, jsonify, render_template, request from flask import Blueprint try: from flask import _app_ctx_stack as stack except ImportError: from flask import _request_ctx_stack as stack class Hive(object): def __init__(self, app=None): self.app = app if app is not None: self.init_app(app) def init_app(self, app): # 自动管理连接的销毁,适配不同Flask版本的上下文 if hasattr(app, 'teardown_appcontext'): app.teardown_appcontext(self.teardown) else: app.teardown_request(self.teardown) def connect(self): # 替换成你实际的Hive服务器地址,比如'your-hive-host:10000' return hive.connect(current_app.config['HIVE_DATABASE_URI'], database="orc") def teardown(self, exception): ctx = stack.top if hasattr(ctx, 'hive_db'): ctx.hive_db.close() @property def connection(self): ctx = stack.top if ctx is not None: if not hasattr(ctx, 'hive_db'): ctx.hive_db = self.connect() return ctx.hive_db # 创建蓝图管理Hive相关路由 hive_bp = Blueprint('hive', __name__) @hive_bp.route('/hive/query', methods=['GET']) def query_table_by_field_id(): # 从请求参数获取field_id和可选的显示条数 field_id = request.args.get('field_id', type=int) limit = request.args.get('limit', default=10, type=int) if not field_id: return jsonify(error="请选择有效的Field ID"), 400 try: # 第一步:查询database_table,拿到目标表的名称和schema cur = Hive.connection.cursor() get_table_sql = f"SELECT table_name, schema_name FROM database_table WHERE field_id = {field_id}" cur.execute(get_table_sql) table_info = cur.fetchone() if not table_info: return jsonify(error=f"未找到Field ID={field_id}对应的表"), 404 target_table, target_schema = table_info # 第二步:查询目标子表的数据 query_sql = f"SELECT * FROM {target_schema}.{target_table} LIMIT {limit}" cur.execute(query_sql) # 获取列名,方便前端展示表头 columns = [col[0] for col in cur.description] table_data = cur.fetchall() return jsonify(columns=columns, data=table_data) except Exception as e: return jsonify(error=f"查询失败:{str(e)}"), 500 # 初始化Flask应用 app = Flask(__name__) # 配置Hive连接地址,根据你的实际环境修改 app.config['HIVE_DATABASE_URI'] = 'localhost:10000' # 注册蓝图 app.register_blueprint(hive_bp) # 主页面路由,展示选择Field ID的UI @app.route('/') def index(): # 先加载所有可用的Field ID和对应表名,用于下拉选择 try: cur = Hive.connection.cursor() cur.execute("SELECT field_id, table_name FROM database_table") field_options = cur.fetchall() return render_template('index.html', field_options=field_options) except Exception as e: return f"加载选项失败:{str(e)}", 500 if __name__ == '__main__': app.run(debug=True)
二、前端UI模板(templates/index.html)
在项目根目录下创建templates文件夹,新建index.html文件,实现交互式的查询界面:
<!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <title>Hive动态表查询</title> <style> .container {max-width: 1000px; margin: 20px auto;} .select-area {margin-bottom: 20px;} select, button, input {padding: 8px 12px; margin-right: 10px; border: 1px solid #ddd; border-radius: 4px;} button {background-color: #007bff; color: white; cursor: pointer;} button:hover {background-color: #0056b3;} table {width: 100%; border-collapse: collapse; margin-top: 20px;} th, td {border: 1px solid #ddd; padding: 10px; text-align: left;} th {background-color: #f8f9fa; font-weight: bold;} .error {color: #dc3545; margin-top: 10px;} </style> </head> <body> <div class="container"> <h1>Hive动态表查询工具</h1> <div class="select-area"> <select id="fieldSelect"> {% for field_id, table_name in field_options %} <option value="{{ field_id }}">Field ID {{ field_id }} - {{ table_name }}</option> {% endfor %} </select> <input type="number" id="limitInput" placeholder="显示条数(默认10)" min="1" value="10"> <button onclick="queryData()">查询数据</button> </div> <div id="resultArea"></div> </div> <script> function queryData() { const fieldId = document.getElementById('fieldSelect').value; const limit = document.getElementById('limitInput').value; // 发送AJAX请求到后端 fetch(`/hive/query?field_id=${fieldId}&limit=${limit}`) .then(response => response.json()) .then(result => { const resultArea = document.getElementById('resultArea'); if (result.error) { resultArea.innerHTML = `<p class="error">${result.error}</p>`; return; } // 生成表格HTML let tableHtml = '<table><thead><tr>'; result.columns.forEach(col => { tableHtml += `<th>${col}</th>`; }); tableHtml += '</tr></thead><tbody>'; result.data.forEach(row => { tableHtml += '<tr>'; row.forEach(cell => { tableHtml += `<td>${cell}</td>`; }); tableHtml += '</tr>'; }); tableHtml += '</tbody></table>'; resultArea.innerHTML = tableHtml; }) .catch(error => { document.getElementById('resultArea').innerHTML = `<p class="error">请求失败:${error.message}</p>`; }); } </script> </body> </html>
三、使用说明
- 环境准备:确保已安装依赖包:
pip install flask pyhive - 配置修改:将
app.py中的HIVE_DATABASE_URI替换成你实际的Hive服务器地址(比如your-hive-server-ip:10000) - 运行程序:执行
python app.py,然后访问http://localhost:5000即可使用 - 功能说明:页面会加载所有可用的Field ID选项,选择后输入显示条数,点击查询就能看到对应子表的数据了
备注:内容来源于stack exchange,提问作者Chanukya
相关产品推荐
相关产品推荐

