Created
August 7, 2024 15:31
-
-
Save MohammadHosseinGhorbani/b22231ac6207c31a6a1f44bcf6f996a7 to your computer and use it in GitHub Desktop.
Python Evaluation in text like Django Templates
This file contains hidden or 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
### Example 1: | |
>>> format_eval("Hello {{ 'world'.upper() }}") | |
'Hello WORLD' | |
### Example 2: | |
>>> import requests | |
>>> format_eval("Request to Google: Code {{ requests.get('https://google.com').status_code) }}") | |
'Request to Google: Code SyntaxError' | |
>>> format_eval("Request to Google: Code {{ requests.get('https://google.com').status_code }}") | |
'Request to Google: Code 200' | |
### Example 3: | |
>>> print(format_eval("""Your Username: {{ (username := 'MohammadHosseinGhorbani') }} | |
... Is Valid: {{ not username.startswith('_') }}""")) | |
Your Username: MohammadHosseinGhorbani | |
Is Valid: True |
This file contains hidden or 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
def format_eval(text: str): | |
while '{{' in text and '}}' in text: | |
start = text.index('{{') | |
end = text.index('}}') | |
try: | |
text = text.replace(text[start:end+2], str(eval(text[start+2:end]))) | |
except Exception as e: | |
text = text.replace(text[start:end+2], repr(type(e)())[:-2]) | |
return text | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment