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:

  1. # Bad! DO NOT DO THIS!
  2. query = MyModel.raw('SELECT * FROM my_table WHERE data = %s' % (user_data,))
  3.  
  4. # Good. `user_data` will be treated as a parameter to the query.
  5. query = MyModel.raw('SELECT * FROM my_table WHERE data = %s', user_data)
  6.  
  7. # Bad! DO NOT DO THIS!
  8. query = MyModel.select().where(SQL('Some SQL expression %s' % user_data))
  9.  
  10. # Good. `user_data` will be treated as a parameter.
  11. 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.