gpt4 book ai didi

mysql - 从数据库表名称构建下拉列表

转载 作者:行者123 更新时间:2023-11-29 23:56:56 24 4
gpt4 key购买 nike

我有这个应用程序,我想将一些 Web 界面部署到系统日志服务器。

所以 syslogserver 确实将其内容写入 mysql 数据库。我已经构建了应用程序的某些部分除了我想构建一个下拉选择表单以选择数据库内的主机表的特定部分之外。

实际上我正在使用flask、flask-sqlalchemy 和wtforms。因此,我尝试通过“QuerySelectField”来实现此功能,但不知何故,我只得到一个没有显示表名条目的下拉列表。

我应该提到数据库本身内的表是动态创建的。对于我的模型,我使用了 automap_base() sqlalchemy 的功能:

model.py

Base = automap_base()

engine = create_engine("mysql://sumuser:tehpass@127.0.0.1/syslog")

Base.prepare(engine, reflect=True)

session = Session(engine)

这是我的表单中的内容:

forms.py

def factoryHelper():
return session.query("information_schema.tables.table_name from information_schema.tables where information_schema.tables.table_name like 'messages_hostname0'")



class HostSelectForm(Form):
title = TextField('Fooblah')
hostTables = QuerySelectField(query_factory=factoryHelper,allow_blank=True)

这在 View 中:

views.py

@app.route('/index/', defaults={'page':1})
@app.route('/index/page/<int:page>')
def index(page):
form = HostSelectForm()
count = session.execute("select host,facility,level,msg from messages_hostname0").rowcount
pagination = Pagination(page, PER_PAGE, count)
return render_template('index.html', pagination=pagination, form=form)

那么我是否可以从动态创建的表名称创建一个下拉菜单?另外,如果我使用自动 map 功能?提前致谢。

最佳答案

我设法在 model.py 中解决了这个问题:

def reflectTables():
for i in Base.classes.items():
yield i[0]


def stripTables():
tablelist = []
datelist = []
re0 = r"^(?P<prefix>[a-zA-Z]*)\_(?P<mid>[a-zA-Z,0-9]*)\_(?P<suffix>[0-9]*)"
myre = re.compile(re0, re.MULTILINE)
for x,table in enumerate(reflectTables()):
striptablename = re.match(myre, table.strip("\n"))
if striptablename:
tablelist.append((x, striptablename.group(2)))
datelist.append((x, striptablename.group(3)))
return dicht(tablelist,datelist)

forms.py:

AVAILABLE_CHOICES = stripTables()

class HostSelectForm(Form):
tableSelect = SelectField('LogHost', choices=AVAILABLE_CHOICES, default=0)

最后在views.py中:

 if request.method == "GET":

count = session.query("* from mytable_monitory_counts")
items = session.execute("select * from mytable_%s_%s limit %s, %s" % \
(tableslector[int(request.values['tableSelect'])][1],\
datelist[int(request.values['tableSelect'])][1], my_start_range, PER_PAGE)).fetchall()
pagination = Pagination(page=page, total=count.count(), search=search, record_name='hosts')

if not items and page != 1:
in_error()

return render_template('index.html', pagination=pagination, form=form, items=items)

关于mysql - 从数据库表名称构建下拉列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25278684/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com