I get Data from a webapp in JSON that includes various python escape characters including "\n" and "\r"
I build a little function to clean the data from problematic chars and spaces before feeding it to the sql. (The problematic chars are problematic to another app using the sql).
the current function is:
bad_tokens = [",",";",".","!","'",".","-",'"',"@",r"\n",r"\r"]
from types import StringType, UnicodeType
def sql_text(sqltext, trim = None):
'''
helper function to clean text inserted to sql from Priority problematic characters specified bad_tokens
'''
thistype = type(sqltext)
if thistype not in (StringType, UnicodeType):
return sqltext
sqltext = sqltext.strip() #priority can't handle string starting with space
for token in bad_tokens:
sqltext = sqltext.replace(token,"")
sqltext = " ".join([i for i in sqltext.split(" ") if i != ""]) #priority can't handle string containing double spaces
if trim:
sqltext = sqltext[0:trim]
return sqltext
This approach works fine for regular chars but doesn't seem to clean the \n and \r escape symbols. adding r (as raw string) to the escape symbols doesn't help either.
thanks for the help
EDIT: I'm using an orm (sqlalchemy), so I don't access DBApi directly, and while sqlalchemy does a lot of escaping automatically since sql treats those chars as legal so does sqlalchemy. back to square on - I need to clean the string correctly.