Created
October 9, 2013 18:42
-
-
Save mudgen/6906043 to your computer and use it in GitHub Desktop.
escape arguments to SQL queries
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # Key characters in this mappings dictionary will be | |
| # replaced in escaped strings with their corresponding values. | |
| # | |
| # For example, if you had the mapping: 'B':'!B!' in the dictionary, | |
| # then escape('Barb') would return the string: '!B!arb' | |
| # (it is case sensitive) | |
| # | |
| # Add anything you like to the mappings dict | |
| # This should work well for SQL-compliant databases | |
| mappings = {"'":"''", "\\":"\\\\", "\n":"\\n", "\r":"\\r", "\t":"\\t"} | |
| # If the call is trying to escape multiple args, return multiple | |
| # escaped values in a return tuple | |
| def escape(*args): | |
| from app.sql import * | |
| arg_lst = [] | |
| if len(args)==1: | |
| return escape_single(args[0]) | |
| for x in args: | |
| arg_lst.append(escape_single(x)) | |
| return tuple(arg_lst) | |
| # This is the 'real' escape function. Note that it only will try | |
| # to escape strings | |
| def escape_single(x): | |
| from app.sql import * | |
| if type(x)==type(()) or type(x)==type([]): | |
| return escape(x) | |
| if type(x)==type(""): | |
| tmpstr='' | |
| for c in range(len(x)): | |
| if x[c] in mappings.keys(): | |
| tmpstr+=mappings[x[c]] | |
| else: | |
| tmpstr+=x[c] | |
| else: | |
| tmpstr=x | |
| return tmpstr |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment