protect psycopg script from sql injection?

MRAB python at mrabarnett.plus.com
Wed Jun 25 19:29:39 EDT 2014


On 2014-06-25 22:58, celati Laurent wrote:
> Hello,
>
> I coded this following python script via psycopg;
>
> web_service_test.py
> <http://python.6.x6.nabble.com/file/n5062113/web_service_test.py>
>
> 1/ When i execute it, the result is 'bad resquest'. Could you tell me why?
>
> 2/ Could you tell me how to protect this script from SQL injections please?
>
In answer to question 2, don't insert the values into the query string
as you're doing here:

     selectString = "SELECT ST_AsText(geom), cult_lib FROM rpg WHERE 
ST_Intersects(SELECT ST_GeomFromText('POINT(%s %s)',2154), rpg)" % (x, y)

Instead, use the placeholder %s in the query string to indicate where a
values should go and then pass that query string and a tuple of the
values to the .execute method:

     selectString = "SELECT ST_AsText(geom), cult_lib FROM rpg WHERE 
ST_Intersects(SELECT ST_GeomFromText('POINT(%s %s)',2154), rpg)"

     cur.execute(selectString, (x, y))

The database engine will insert the values itself, safely.



More information about the Python-list mailing list