【问题标题】:Sqlite format output in pythonpython中的Sqlite格式输出
【发布时间】:2020-05-01 19:02:19
【问题描述】:

我设置了一个简单的烧瓶网络应用程序,用户可以在其中添加和删除数据库中的任务。数据库中的所有条目都显示在模板中,按分配的类型排序。不过,我无法将输出格式化为至少有点可读性。我怎么做?

实际的数据库使用不同的值等等,所以现在并不是所有的值都有意义。

这是从我的 sqlite 数据库中获取所有条目的函数:

def get_tsk_by_type(type):
  c.execute("SELECT * FROM tasks WHERE type=:type", {'type': type})
  result = c.fetchall()
  return result

数据库:

c.execute("""CREATE TABLE IF NOT EXISTS tasks (
            type text,
            description text,
            amount integer,
            id integer
            )""")

这就是我如何返回然后显示在模板中的所有条目。如果您输入他们的id,还有一个删除任务的功能。

@app.route('/', methods = ['GET', 'POST'])
def index():
  form = DeleteForm()
  curr_homework = str(get_tsk_by_type("homework"))
  curr_cleaning = str(get_tsk_by_type("cleaning"))
  curr_cooking = str(get_tsk_by_type("cooking"))
  if form.validate_on_submit():
    try:
      conn = sqlite3.connect('tasks.db', check_same_thread=False)
      c = conn.cursor()
      delete = request.form['delete']
      if (delete):
        remove_tsk(delete)
      return redirect('/')
      conn.close()
    except:
      return "Something went wrong while submitting the form"
  return render_template('index.html', curr_homework = curr_homwork, curr_cleaning = curr_cleaning, curr_cooking = curr_cooking, form = form)

我的 index.html 的相关部分如下所示:

{% block content %}
    <div>
        <p>
            <span>Currently registered homework: {{ curr_homework }}</span><br />
            <span>Currently registered cleaning tasks: {{ curr_cleaning }}</span><br />
            <span>Currently registered cooking tasks {{ curr_cooking }}</span>
        </p>
    </div>
{% endblock content %}

但是,我得到的输出是这样的:

Currently registered homework: [('homework', 'math', 1, 'df19c0b1-a2128-431274-2e32-3a2f901b1b26')]
Currently registered cleaning tasks: [('cleaning', 'kitchen', 1, 'df19c0b1-aa18-4874-9e32-3a2f901b1b26')]
Currently registered cooking tasks: [('cooking', 'lunch', 1, '0697c139-0299-4c93-88ac-c07d77377796')]

我已经尝试过 for 循环和类似的东西,但它只返回 get_tsk_by_type() 返回的列表中的第一个元组。我也尝试过 panda 但我也无法以我想要的方式输出它。我如何将它美化到易于阅读的程度?没有括号等?稍后我想分别显示每个单独的任务,最好是在 div 中。

【问题讨论】:

    标签: python list sqlite flask tuples


    【解决方案1】:

    我建议使用 dict 游标,以便您可以按名称访问结果元素。
    你可以这样做(来自:https://stackoverflow.com/a/3300514/42346):

    def dict_factory(cursor, row):
        d = {}
        for idx, col in enumerate(cursor.description):
            d[col[0]] = row[idx]
        return d
    
    conn.row_factory = dict_factory
    

    那么你会得到这样的结果:

    result = c.fetchall()
    result
    # [{'type':'homework','description':'math',
    #   'amount':1,'id':'df19c0b1-a2128-431274-2e32-3a2f901b1b26'}]
    

    然后在您的模板中,您可以执行以下操作:

      {% for homework in curr_homework %}
        <div>
          <h6>{{ homework['type'] }}</h6>
          <div>{{ homework['description'] }}</div>
        </div>
        {% if not loop.last %}
          <hr>
        {% endif %}
      {% endfor %}
    

    您可能会受益于对数据库特定代码的一些重新组织。
    你可以这样做:

    from flask import g
    
    def dict_factory(cursor, row):
        d = {}
        for idx, col in enumerate(cursor.description):
            d[col[0]] = row[idx]
        return d
    
    def get_db():
        if 'db' not in g:
            conn = sqlite3.connect('tasks.db', check_same_thread=False)
            conn.row_factory = dict_factory
            g.db = conn.cursor()
        return g.db
    

    然后在你看来这样做:

    db = get_db()
    db.execute('your query here')
    

    【讨论】:

    • 感谢您的帮助! conn.row_factory = dict_factory 必须去特定的地方吗? get_tsk_by_type() 仍在返回元组。因此,我的模板中的代码返回所有
      和 div,但不返回实际数据。还是我应该以任何方式更改dict_factory()
    • 是的,它需要在您的光标为 get_tsk_by_type() 函数初始化之前进行。
    • 让我添加一个示例,说明如何更好地组织它。
    • @Lacrowx:添加了如何将连接和光标行工厂代码移动到另一个函数中的示例。
    • 非常感谢,这很有效,get_db() 让我的代码更干净了!
    猜你喜欢
    • 1970-01-01
    • 2021-02-12
    • 1970-01-01
    • 2014-01-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多