Re: Safe SELECT ... LIKE abc% in psycopg

From: Adrian Klaver <adrian(dot)klaver(at)aklaver(dot)com>
To: Philippe Strauss <philippe(at)straussaudio(dot)ch>, psycopg(at)lists(dot)postgresql(dot)org
Subject: Re: Safe SELECT ... LIKE abc% in psycopg
Date: 2024-04-22 16:50:31
Message-ID: 387a4f5e-5886-443d-bc4e-e649706173a4@aklaver.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: psycopg

On 4/22/24 09:34, Philippe Strauss wrote:
> Hello, I'm Philippe from switzerland,
>
> I'm writing using python a small JSON API for a mycology photos archive
> webapp. Aside the main API endpoint are two
> helpers for an autocomplete form.
> Here is the first one:
>
> --8<--
> @app.route('/genus/<genus>')
> def genus(genus):
>     with dbconn.cursor() as cur:
>         cur.execute("""SELECT myco.genus.name
>             FROM myco.genus
>             WHERE myco.genus.name LIKE %s""", (genus.upper()+'%',))
>         lsgenus = cur.fetchall()
>         ls = []
>         for genus in lsgenus:
>             ls.append(genus[0])
>     return jsonify(ls)
> --8<--
>
> My questions:
> - What is the best way to use in psycopg3 to express a SELECT ... WHERE
> ... LIKE blah% ?
> - Is my code above safe or vulnerable to a injection attack?
> - What peoples having passed on the same pattern have to recommend?

Read:

https://www.psycopg.org/psycopg3/docs/basic/params.html

It will answer the above.

For this case from link:

"When parameters are used, in order to include a literal % in the query
you can use the %% string:"

>
> Thanks!
>

--
Adrian Klaver
adrian(dot)klaver(at)aklaver(dot)com

In response to

Responses

Browse psycopg by date

  From Date Subject
Next Message Adrian Klaver 2024-04-22 16:57:10 Re: Safe SELECT ... LIKE abc% in psycopg
Previous Message Philippe Strauss 2024-04-22 16:34:40 Safe SELECT ... LIKE abc% in psycopg