【问题标题】:Building the appropriate SQL queries for a web from, when order doesn't matter当顺序无关紧要时,为 Web 构建适当的 SQL 查询
【发布时间】:2016-06-07 15:09:03
【问题描述】:

我会将输入读入以下网络表单:

因此通过 Flask:

def query():
    if request.method == "POST":
        job_title_input = request.form['title']
        description_operator = request.form['DescriptionOperator']
        description_input = request.form['description']
        salary_operator = request.form['SalaryOperator']
        salary_input = request.form['salary']
        location_input = request.form['location']

收到的值将用于在 SQLite 中查询该表:

CREATE TABLE scrapedjobs
             (id integer primary key autoincrement not null,
             huburl text,
             business_name text,
             location text,
             jobtitle text,
             description text,
             joburl text,
             salary int,
             date_first_scraped date)

这是我第一次尝试处理 Web 表单提交中的排列,并且在仅通过前两个字段级联之后,我可以看到它已经变得令人费解了:

    base_query = """SELECT * FROM scrapedjobs"""
    if job_title_input != '':
        base_query = base_query + """ WHERE jobtitle IN ('""" + job_title_input + """')"""
        job_title_input_flag = """ AND"""
    else:
        job_title_input_flag = """"""

    if description_input != '':
        if job_title_input_flag != '':
            base_query = base_query + """ AND description """ + description_operator + " " + "('" + description_input + "')"
            description_input_flag = """ AND"""
        else:
            base_query = base_query + """ WHERE description """ + description_operator + " " + "('" + description_input + "')"
            description_input_flag = """ AND"""
    else:
        description_input_flag = """"""

我越往下走,if/else 的嵌套就越多,如果在表单中添加新字段是不可持续的。一个主要缺陷也是我正在设置的东西,每个字段都取决于前面的字段是否有值,等等。现实情况当然是,在像这样没有分组或连接等的直接查询中,顺序无关,一旦我需要AND(如果字段确实有)一个值),当我需要 WHERE 时。更糟糕的是,当我在sqlite3 中将其传递给cursor.execute() 时,我将不得不参数化所有这些。

我不是第一个从多个表单中读取值并构建适当的SELECTs 的人 - 我可以利用哪些模式或更有效的技术?

【问题讨论】:

    标签: python sql forms sqlite flask


    【解决方案1】:

    我去过那里,我知道它会如何结束。在您的情况下手动构建查询非常容易出错,不可读,并导致支持噩梦。相反,请考虑使用 sqlalchemyflask-sqlalchemy 来抽象化事物。使用 SQLAlchemy,您可以分段组合查询,它会正确构建最终查询。

    作为一个真实世界的例子,研究Flask Mega-Tutorialsqlalchemy 用于chapter 4 及更高版本)。

    【讨论】:

      猜你喜欢
      • 2018-07-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-11
      • 1970-01-01
      • 2020-09-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多