-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcomplete_unicode_example.py
More file actions
318 lines (267 loc) · 10.6 KB
/
complete_unicode_example.py
File metadata and controls
318 lines (267 loc) · 10.6 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
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Complete Example: Unicode Support for Text and HTML Templates
This example demonstrates all the Unicode and template type features
of the CustomTemplateEngine.
"""
from template_engine import TemplateEngine
def main():
"""Demonstrate complete Unicode and template type support."""
print("🌍 CustomTemplateEngine - Complete Unicode & Template Type Example")
print("=" * 80)
# Sample data with extensive Unicode content
context = {
'website_name': 'Global Connect 🌍',
'tagline': 'Connecting the world through technology',
'current_year': 2025,
# International user data
'users': [
{
'name': 'Emma Johnson',
'country': 'United States 🇺🇸',
'greeting': 'Hello!',
'bio': 'Software engineer & tech enthusiast'
},
{
'name': 'François Dubois',
'country': 'France 🇫🇷',
'greeting': 'Bonjour!',
'bio': 'Développeur passionné de technologie'
},
{
'name': '田中太郎',
'country': 'Japan 🇯🇵',
'greeting': 'こんにちは!',
'bio': 'ソフトウェア開発者として働いています'
},
{
'name': 'Ahmed Al-Rashid',
'country': 'Saudi Arabia 🇸🇦',
'greeting': 'مرحبا!',
'bio': 'مطور برمجيات متخصص في التقنيات الحديثة'
},
{
'name': '李明',
'country': 'China 🇨🇳',
'greeting': '你好!',
'bio': '专注于软件开发的工程师'
},
{
'name': 'Владимир Петров',
'country': 'Russia 🇷🇺',
'greeting': 'Привет!',
'bio': 'Разработчик программного обеспечения'
}
],
# Special characters and symbols
'features': [
'Multi-language support ⚡',
'Real-time collaboration 🔄',
'Advanced security 🔒',
'Cloud integration ☁️',
'Mobile responsive 📱'
],
'stats': {
'users_count': '1,000,000+',
'countries': '195+',
'languages': '50+',
'satisfaction': '99.9%'
},
'contact_info': {
'email': 'contact@globalconnect.com',
'phone': '+1 (555) 123-4567',
'address': '123 Tech Street, San Francisco, CA'
}
}
# 1. HTML Template Example
print("\n📄 1. HTML Template (with XSS protection)")
print("-" * 60)
html_template = '''<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>$website_name - $tagline</title>
<style>
body { font-family: Arial, sans-serif; margin: 0; padding: 20px; }
.header { background: #f0f8ff; padding: 20px; border-radius: 8px; }
.user-card { border: 1px solid #ddd; margin: 10px 0; padding: 15px; border-radius: 5px; }
.stats { display: flex; gap: 20px; margin: 20px 0; }
.stat { background: #e8f4fd; padding: 10px; border-radius: 5px; text-align: center; }
.footer { margin-top: 40px; padding: 20px; background: #f9f9f9; border-radius: 5px; }
</style>
</head>
<body>
<div class="header">
<h1>$website_name</h1>
<p>$tagline</p>
</div>
<main>
<section>
<h2>Meet Our Global Community 🌏</h2>
<div class="users">
{% for user in users %}
<div class="user-card">
<h3>$user.name from $user.country</h3>
<p><strong>Says:</strong> <em>$user.greeting</em></p>
<p><strong>Bio:</strong> $user.bio</p>
</div>
{% endfor %}
</div>
</section>
<section>
<h2>Platform Features ✨</h2>
<ul>
{% for feature in features %}
<li>$feature</li>
{% endfor %}
</ul>
</section>
<section>
<h2>Global Statistics 📊</h2>
<div class="stats">
<div class="stat">
<h3>$stats.users_count</h3>
<p>Active Users</p>
</div>
<div class="stat">
<h3>$stats.countries</h3>
<p>Countries</p>
</div>
<div class="stat">
<h3>$stats.languages</h3>
<p>Languages</p>
</div>
<div class="stat">
<h3>$stats.satisfaction</h3>
<p>Satisfaction</p>
</div>
</div>
</section>
</main>
<footer class="footer">
<h3>Contact Us 📞</h3>
<p>Email: $contact_info.email</p>
<p>Phone: $contact_info.phone</p>
<p>Address: $contact_info.address</p>
<p>© $current_year $website_name. All rights reserved.</p>
</footer>
</body>
</html>'''
# Create HTML engine with XSS protection
html_engine = TemplateEngine(auto_escape=True, strict_mode=False)
try:
html_result = html_engine.render_html(html_template, context)
# Save to file manually
with open('complete_example.html', 'w', encoding='utf-8') as f:
f.write(html_result)
print("✅ HTML template rendered and saved to 'complete_example.html'")
print(f" File size: {len(html_result)} characters")
except Exception as e:
print(f"❌ HTML template failed: {e}")
# 2. Plain Text Template Example
print("\n📄 2. Plain Text Template (no HTML escaping)")
print("-" * 60)
text_template = '''$website_name
$tagline
==========================================
🌍 GLOBAL COMMUNITY MEMBERS:
{% for user in users %}
👤 $user.name ($user.country)
Greeting: "$user.greeting"
Bio: $user.bio
{% endfor %}
✨ PLATFORM FEATURES:
{% for feature in features %}
• $feature
{% endfor %}
📊 GLOBAL STATISTICS:
• Active Users: $stats.users_count
• Countries: $stats.countries
• Languages: $stats.languages
• Satisfaction Rate: $stats.satisfaction
📞 CONTACT INFORMATION:
Email: $contact_info.email
Phone: $contact_info.phone
Address: $contact_info.address
© $current_year $website_name. All rights reserved.
This template demonstrates full Unicode support including:
- Emojis and symbols: 🌍✨📊📞👤💫⚡🔄🔒☁️📱
- International characters: àáâãäåæçèéêë
- Multiple languages: English, Français, 日本語, العربية, 中文, Русский
- Mathematical symbols: ∑∏∆∇∂∫∞≠≤≥±×÷√
- Currency symbols: €£¥¢ (and many more)'''
# Create text engine without HTML escaping
text_engine = TemplateEngine(auto_escape=False, strict_mode=False)
try:
text_result = text_engine.render_text(text_template, context)
# Save to file manually
with open('complete_example.txt', 'w', encoding='utf-8') as f:
f.write(text_result)
print("✅ Text template rendered and saved to 'complete_example.txt'")
print(f" File size: {len(text_result)} characters")
# Show preview
print("\n📋 Text Template Preview (first 500 characters):")
print("-" * 60)
print(text_result[:500] + "..." if len(text_result) > 500 else text_result)
except Exception as e:
print(f"❌ Text template failed: {e}")
# 3. Demonstrate different encoding support
print("\n🔤 3. Multi-Encoding File Support")
print("-" * 60)
encoding_test_data = {
'test_content': 'Unicode Test: 🌍 Café résumé naïve 中文 العربية ñáéíóú'
}
simple_template = 'Encoding Test: $test_content'
# Test different encodings
encodings = ['utf-8', 'utf-16', 'utf-32']
for encoding in encodings:
try:
engine = TemplateEngine()
with open(f'encoding_test_{encoding.replace("-", "_")}.txt', 'w', encoding=encoding) as f:
result = engine.render_text(simple_template, encoding_test_data)
f.write(result)
print(f"✅ Successfully saved with {encoding} encoding")
except Exception as e:
print(f"❌ Failed with {encoding}: {e}")
# 4. Security demonstration
print("\n🔒 4. Security Features Demonstration")
print("-" * 60)
# Potentially dangerous content
security_context = {
'user_input': '<script>alert("XSS Attack!")</script>',
'html_content': '<p>Safe HTML content</p>',
'special_chars': 'Data with "quotes" & <brackets>',
'safe_content': 'This is completely safe 🔒'
}
security_template = '''Security Test Results:
User Input (XSS attempt): $user_input
HTML Content: $html_content
Special Characters: $special_chars
Safe Content: $safe_content'''
# Test with HTML escaping (secure)
secure_engine = TemplateEngine(auto_escape=True, strict_mode=False)
secure_result = secure_engine.render(security_template, security_context)
print("🔒 With XSS Protection (HTML escaped):")
print(secure_result)
# Test without escaping (potentially unsafe)
unsafe_engine = TemplateEngine(auto_escape=False, strict_mode=False)
unsafe_result = unsafe_engine.render(security_template, security_context)
print("\n⚠️ Without XSS Protection (raw content):")
print(unsafe_result)
print("\n🎉 Complete Unicode and Template Type Example Finished!")
print("=" * 80)
print("Generated files:")
print(" 📄 complete_example.html - Full HTML page with Unicode")
print(" 📄 complete_example.txt - Plain text with Unicode")
print(" 📄 encoding_test_*.txt - Files in different encodings")
print("\nKey Features Demonstrated:")
print(" ✅ Full Unicode support (emojis, international languages)")
print(" ✅ HTML templates with XSS protection")
print(" ✅ Plain text templates without escaping")
print(" ✅ Multiple encoding support")
print(" ✅ Auto-detection of template types")
print(" ✅ Security features and escaping control")
if __name__ == "__main__":
main()