我正在尝试为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 -
答案 0 :(得分:-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,如下面的评论所述,回答的上一版本可能会导致SQL注入,因此请注意使用字符串格式,并正确使用API。