-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtext_escape_demo.py
More file actions
193 lines (153 loc) Β· 6.17 KB
/
text_escape_demo.py
File metadata and controls
193 lines (153 loc) Β· 6.17 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Demonstrate what happens when auto_escape=True is used for text templates
"""
from template_engine import TemplateEngine
def text_template_escaping_demo():
"""Show the effects of HTML escaping on text templates."""
print("π TEXT TEMPLATE ESCAPING DEMO")
print("=" * 60)
engine = TemplateEngine(strict_mode=False) # Use non-strict mode
# Sample data with characters that would be escaped in HTML
text_data = {
'user_name': 'John & Jane',
'email_subject': 'Meeting @ 3:00 PM <urgent>',
'message': 'Please review the proposal & send feedback',
'code_example': 'if (x < 5 && y > 10) { return true; }',
'html_content': '<p>This is a paragraph with <strong>bold</strong> text</p>',
'special_chars': 'Symbols: < > & " \' = % # @',
'math_formula': '5 < x < 10 && result = x & y',
'file_path': 'C:\\Users\\Admin\\Documents\\file.txt'
}
# Text template (like for emails, reports, config files)
text_template = '''
Email Notification
==================
To: $user_name
Subject: $email_subject
Message:
$message
Code Example:
$code_example
HTML Content:
$html_content
Special Characters:
$special_chars
Math Formula:
$math_formula
File Path:
$file_path
Best regards,
System Administrator
'''.strip()
print("π Sample Data:")
for key, value in text_data.items():
print(f" π {key}: {repr(value)}")
print(f"\nπ TEXT OUTPUT (auto_escape=False) - CORRECT:")
print("=" * 50)
text_result = engine.render(text_template, text_data, auto_escape=False)
print(text_result)
print(f"\nπ TEXT OUTPUT (auto_escape=True) - WRONG:")
print("=" * 50)
html_escaped_result = engine.render(text_template, text_data, auto_escape=True)
print(html_escaped_result)
return text_result, html_escaped_result
def show_specific_problems():
"""Show specific problems when HTML escaping text."""
print(f"\n\nβ οΈ SPECIFIC PROBLEMS WITH HTML ESCAPING TEXT")
print("=" * 60)
engine = TemplateEngine(strict_mode=False)
examples = [
{
'name': 'Email Addresses',
'data': {'email': 'user@example.com'},
'template': 'Contact: $email',
'problem': 'The @ symbol might get escaped in some contexts'
},
{
'name': 'File Paths',
'data': {'path': 'C:\\Program Files\\App\\config.xml'},
'template': 'Config file: $path',
'problem': 'Backslashes and angle brackets in paths get escaped'
},
{
'name': 'Programming Code',
'data': {'code': 'if (x < y && z > 0) return true;'},
'template': 'Code: $code',
'problem': 'Comparison operators < > get escaped'
},
{
'name': 'Natural Language',
'data': {'text': 'I love <3 this & that!'},
'template': 'Comment: $text',
'problem': 'Heart symbol <3 and ampersand get escaped'
},
{
'name': 'Mathematical Expressions',
'data': {'formula': '2 < x < 10 & y >= 5'},
'template': 'Formula: $formula',
'problem': 'Math symbols become unreadable'
}
]
for example in examples:
print(f"\nπ {example['name']}:")
print(f" Input: {repr(example['data'])}")
correct = engine.render(example['template'], example['data'], auto_escape=False)
wrong = engine.render(example['template'], example['data'], auto_escape=True)
print(f" β
Correct (no escape): {correct}")
print(f" β Wrong (escaped): {wrong}")
print(f" π‘ Problem: {example['problem']}")
def use_case_scenarios():
"""Show different use case scenarios."""
print(f"\n\nπ― USE CASE SCENARIOS")
print("=" * 50)
print("π§ EMAIL TEMPLATES:")
print(" β
auto_escape=False - Preserve natural text")
print(" β auto_escape=True - Makes emails hard to read")
print("\nπ PLAIN TEXT REPORTS:")
print(" β
auto_escape=False - Clean, readable output")
print(" β auto_escape=True - Cluttered with HTML entities")
print("\nπ LOG FILES:")
print(" β
auto_escape=False - Proper log formatting")
print(" β auto_escape=True - Corrupted log entries")
print("\nβοΈ CONFIG FILES:")
print(" β
auto_escape=False - Valid syntax")
print(" β auto_escape=True - Broken configuration")
print("\nπ¨ SMS/TEXT MESSAGES:")
print(" β
auto_escape=False - Natural text flow")
print(" β auto_escape=True - Weird HTML entities in messages")
def recommendations():
"""Provide clear recommendations."""
print(f"\n\nπ‘ RECOMMENDATIONS")
print("=" * 50)
print("π― DECISION MATRIX:")
print(" π Text Templates (emails, logs, configs):")
print(" β auto_escape=False β
")
print(" β Preserves natural text formatting")
print(" β No HTML entities in output")
print("\n π HTML Templates (web pages, HTML emails):")
print(" β auto_escape=True β
")
print(" β Prevents XSS attacks")
print(" β Safe for web browsers")
print("\nπ¨ WHEN TO BE CAREFUL:")
print(" β οΈ HTML Email Templates:")
print(" β auto_escape=True (for security)")
print(" β But be aware text might look different")
print("\n β οΈ Mixed Content:")
print(" β Consider separate templates")
print(" β Or manual escaping for specific fields")
if __name__ == "__main__":
text_result, html_result = text_template_escaping_demo()
show_specific_problems()
use_case_scenarios()
recommendations()
print(f"\n\nπ SUMMARY:")
print("=" * 50)
print("Setting auto_escape=True for text templates:")
print("β
PROS: None for plain text")
print("β CONS: Makes text harder to read")
print("β CONS: Corrupts natural language")
print("β CONS: Breaks code examples")
print("β CONS: Mangles file paths")
print("\nπ― CONCLUSION: Use auto_escape=False for text templates!")