【问题标题】:issue while creating an endpoint in Flask using Python [duplicate]使用 Python 在 Flask 中创建端点时出现问题 [重复]
【发布时间】:2017-12-22 12:04:46
【问题描述】:

我正在尝试为 RESTful Web 服务编写微服务。 我在“Postgresql”中创建了一个数据库,目前使用 Flask 和 psycopg2(用于将 db-object 转换为 json 对象)。 以下是我的代码的一部分,但由于某种原因,我遇到了错误。我正在尝试建立的 URI 有点像 localhost/events/20171222 处理这个问题的正确方法是什么?

代码:

app = Flask(__name__)
conn = psycopg2.connect("dbname='postgresdb'")
cur = conn.cursor(cursor_factory=RealDictCursor)

@app.route('/events/<dated>', methods=['GET'])
def getDatedEvents(dated):
    date_obj = datetime.strptime(dated, '%Y%m%d')
    #print(type(date_obj))
    #print(date_obj)

    cur.execute("""
        SELECT event_id, timestamp
        FROM event_tbl
        WHERE timestamp < date_obj
        ORDER BY timestamp
        LIMIT 25
        """)

    return json.dumps(cur.fetchall(), default=json_serial)

错误输出:

psycopg2.ProgrammingError: column "date_obj" does not exist
LINE 4:   WHERE timestamp < date_obj
                    ^

localhost - - [22/Dec/2017 17:22:29] "GET /events/20161020 HTTP/1.1" 500 -

【问题讨论】:

    标签: python postgresql rest flask


    【解决方案1】:

    您需要修改查询。目前您正在将时间戳与字符串 date_obj 进行比较,这就是 postgreSQL 抛出错误的原因,因为它无法将时间戳与字符串进行比较。使用字符串格式在查询中传递您的date_obj

    cur.execute("""
        SELECT event_id, timestamp
        FROM event_tbl
        WHERE timestamp < %s
        ORDER BY timestamp
        LIMIT 25
        """, (date_obj,))`
    

    根据docs的说法,如下面的cmets中提到的,之前修改过的一个答案可能会导致SQL注入,所以要注意使用字符串格式,正确使用API​​。

    【讨论】:

    • 哦,谢谢哥们 :) @py_dude
    • @GabbarSingh 如果对您有帮助,您可以将此答案标记为正确:)
    • 不要format 查询,这就是您在代码中创建 SQL 注入漏洞的方式。使用查询参数:stackoverflow.com/questions/1466741/…
    猜你喜欢
    • 1970-01-01
    • 2021-03-18
    • 2018-12-08
    • 1970-01-01
    • 2011-03-20
    • 2021-06-16
    • 2021-06-21
    • 1970-01-01
    • 2020-04-29
    相关资源
    最近更新 更多