safely specifying 'order by' clause from user input in python / postgresql / psycopg2

三世轮回 提交于 2020-01-25 04:36:20

问题


i feel like this is a stupid question but i can't find anything anywhere.

I want to build an SQL query using psycopg2 where the user specifies the sort / order by column.. client-side its a javascript grid of data offering sorting / paging etc.

normal substitution practice doesn't work: (note the E'xx')

cur.mogrify('select * from table offset %s limit %s order by %s', [0,5,'sort_column'])
>>> "select * from table offset 0 limit 5 order by E'sort_column'"

short of cleansing / substituting the order by clause in myself, what is the recommended way to do this ?

am i a duplicate of: psycopg2 E' on table, field and schema ?

cheers

-i


回答1:


Entity names (tables/columns etc...) in Python's DBAPI shouldn't be run through any place holder processing as variables are supposed to be. You will have to do your own formatting:

'select * from table offset %s limit %s order by %s' % (0,5,'sort_column')

But do use the proper escaping/placeholder functions for WHERE var = %s etc...



来源:https://stackoverflow.com/questions/11556711/safely-specifying-order-by-clause-from-user-input-in-python-postgresql-psy

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!