Security and SQL Injection
By default peewee will parameterize queries, so any parameters passed in by theuser will be escaped. The only exception to this rule is if you are writing araw SQL query or are passing in a SQL
object which may contain untrusteddata. To mitigate this, ensure that any user-defined data is passed in as aquery parameter and not part of the actual SQL query:
- # Bad! DO NOT DO THIS!
- query = MyModel.raw('SELECT * FROM my_table WHERE data = %s' % (user_data,))
- # Good. `user_data` will be treated as a parameter to the query.
- query = MyModel.raw('SELECT * FROM my_table WHERE data = %s', user_data)
- # Bad! DO NOT DO THIS!
- query = MyModel.select().where(SQL('Some SQL expression %s' % user_data))
- # Good. `user_data` will be treated as a parameter.
- query = MyModel.select().where(SQL('Some SQL expression %s', user_data))
Note
MySQL and Postgresql use '%s'
to denote parameters. SQLite, on theother hand, uses '?'
. Be sure to use the character appropriate to yourdatabase. You can also find this parameter by checkingDatabase.param
.