Utils

class cf_rules.Utils(directory: str = None)[source]
__init__(directory: str = None) None[source]

Utils class to manage Cloudflare data

>>> utils = Utils("my_expressions")
change_directory(directory: str) None[source]

Change the directory where the expressions are stored

>>> utils.change_directory("my_expressions2")
static escape(string) str[source]

Escape a string

Simply replace slashes with underscores for the file name

>>> utils.escape("Test/1")
>>> "Test_1"
static unescape(string: str) str[source]

Unescape a string

Simply replace underscores with slashes for the rule name

>>> utils.unescape("Test_1")
>>> "Test/1"
static beautify(expression: str) str[source]

Beautify a Cloudflare expression

>>> utils.beautify("(cf.client.bot) or (cf.threat_score ge 1)")
# (cf.client.bot) or
# (cf.threat_score ge 1)
write_expression(rule_file: str, rule_expression: str, header: dict | None = None) None[source]

Write an expression to a readable text file

>>> utils.write_expression("IsBot", "(cf.client.bot)")
>>> utils.write_expression("IsBot", "(cf.client.bot)", header={"action": "managed_challenge", "enabled": "True"})
read_expression(rule_file: str) tuple[str, str][source]

Read an expression from a file

>>> utils.read_expression("IsBot")
>>> "(cf.client.bot)"
process_header(header_line: str) dict | None[source]

Process the header of an expression file if it exists It retrieves all header data and returns a dictionary

>>> utils.process_header("#! action:block enabled:True !#")
>>> {"action": "block", "enabled": "True"}
static get_json_key(json: dict, keys: list[str | int]) object[source]

Get an element from a json using a list of keys

>>> utils.get_json_key({"a": {"b": {"c": "d"}}}, ["a", "b", "c"])
>>> "d"
>>> utils.get_json_key({"a": ["b", "c"]}, ["a", 1])
>>> "c"