-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #643 from NASA-IMPACT/638-add-title-rules-with-f-s…
…tring-formatting 638 add title rules with f string formatting
- Loading branch information
Showing
2 changed files
with
47 additions
and
47 deletions.
There are no files selected for viewing
This file contains 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
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,8 +1,18 @@ | ||
def interpret_title_pattern(url, scraped_title, title_pattern): | ||
"""Interpret a title pattern.""" | ||
# If "{title}" is in the title_pattern, replace it with scraped_title | ||
if "{title}" in title_pattern: | ||
return title_pattern.replace("{title}", scraped_title) | ||
# If "{title}" is not in the title_pattern, return title_pattern as is | ||
else: | ||
return title_pattern | ||
import _ast | ||
import ast | ||
|
||
|
||
def safe_f_string_evaluation(pattern, context): | ||
"""Safely interpolates the variables in an f-string pattern using the provided context.""" | ||
parsed = ast.parse(f"f'''{pattern}'''", mode="eval") | ||
|
||
# Walk through the AST to ensure it only contains safe expressions | ||
for node in ast.walk(parsed): | ||
if isinstance(node, _ast.FormattedValue): | ||
if not isinstance(node.value, _ast.Name): | ||
raise ValueError("Unsupported expression in f-string pattern.") | ||
if node.value.id not in context: | ||
raise ValueError(f"Variable {node.value.id} not allowed in f-string pattern.") | ||
|
||
compiled = compile(parsed, "<string>", "eval") | ||
return eval(compiled, {}, context) |