Changeset View
Changeset View
Standalone View
Standalone View
swh/search/utils.py
Show First 20 Lines • Show All 49 Lines • ▼ Show 20 Lines | try: | ||||
datetime.strptime(date_str, "%Y-%m-%d") | datetime.strptime(date_str, "%Y-%m-%d") | ||||
return True | return True | ||||
except Exception: | except Exception: | ||||
try: | try: | ||||
iso8601.parse_date(date_str) | iso8601.parse_date(date_str) | ||||
return True | return True | ||||
except Exception: | except Exception: | ||||
return False | return False | ||||
def escape(obj): | |||||
r"""Makes the object directly injectable into the | |||||
query language by converting the escapable parts of | |||||
the object into escape sequences. | |||||
For strings, appends \ before special characters like ', ", and \ | |||||
For arrays, applies the same transformation on each element, joins the | |||||
elements and returns a string-like representation of the list. | |||||
>>> print(escape("foo ' bar")) | |||||
"foo \' bar" | |||||
>>> print(escape([r"foo ' bar", r"bar \\\' baz", r'foo " baz'])) | |||||
["foo \' bar", "bar \\\\\\\' baz", "foo \" baz"] | |||||
""" | |||||
if type(obj) == list: | |||||
items = [escape(item) for item in obj] | |||||
return "[" + ", ".join(items) + "]" | |||||
elif type(obj) == str: | |||||
return ( | |||||
'"' | |||||
+ obj.translate({ord("'"): r"\'", ord('"'): r"\"", ord("\\"): r"\\",}) | |||||
+ '"' | |||||
) | |||||
else: | |||||
raise Exception(f"Unexpected item type {type(obj)}") | |||||
vlorentz: call it `unescape` | |||||
def unescape(string): | |||||
r"""Processes the escaped special characters | |||||
>>> unescape(r'''foo " bar''') == r'''foo " bar''' | |||||
True | |||||
>>> unescape(r'''foo \" bar''') == r'''foo " bar''' | |||||
True | |||||
>>> unescape(r'''foo \\" bar''') == r'''foo \" bar''' | |||||
True | |||||
>>> unescape(r'''foo \\\" bar''') == r'''foo \" bar''' | |||||
True | |||||
>>> unescape(r'''foo \\\\" bar''') == r'''foo \\" bar''' | |||||
True | |||||
""" | |||||
return bytes(string, "utf-8").decode("unicode_escape") |
call it unescape