[mod_python] How to sanitize input?

Byron Ellacott bje at apnic.net
Tue Dec 14 00:45:09 EST 2004

Kevin White wrote:
> Before I take form data and start putting it into an sql statement for
> updating/inserting to a database, I assume I will need to clean it up.
> That is, in PHP, I used to addslashes() to each field before inserting
> to the database, in case it has characters that would mess up the sql.

I work the other way around -- ensuring user input has all valid 
characters, rather than any invalid characters.  The reason for doing 
this is that I cannot overlook anything - I'm clearly defining what's 

> How do I sanitize my input in python?

A simple approach would be:

OK_CHARS = "abcdefghijklmnopqrstuvwxyz0123456789 .,!?:"

def is_safe(str):
     return [x for x in str if x.lower() not in OK_CHARS] == []

Not necessarily very processor friendly; Python 2.4's set operations 
would make this even more trivial, and probably a fair bit faster.  I 
don't know if mod_python is capable of being built with Python 2.4, however.


More information about the Mod_python mailing list