I\'m passing some values into a postgres character field using psycopg2 in Python. Some of the string values contain periods, slashes, quotes etc.
With MySQL I\'d ju
In the unlikely event that query parameters aren't sufficient and you need to escape strings yourself, you can use Postgres escaped string constants along with Python's repr
(because Python's rules for escaping non-ascii and unicode characters are the same as Postgres's):
def postgres_escape_string(s):
if not isinstance(s, basestring):
raise TypeError("%r must be a str or unicode" %(s, ))
escaped = repr(s)
if isinstance(s, unicode):
assert escaped[:1] == 'u'
escaped = escaped[1:]
if escaped[:1] == '"':
escaped = escaped.replace("'", "\\'")
elif escaped[:1] != "'":
raise AssertionError("unexpected repr: %s", escaped)
return "E'%s'" %(escaped[1:-1], )