SlideShare a Scribd company logo
1 of 19
Download to read offline
Introduction to a simple
messages framework for
Tornado
Gao Chao
2014.03.14
Tornado
• A high performance asynchronous web
framework.
• Originated in FriendFeed, acquired by Facebook
later on.
• We are using it!
Messages Framework
• Taken from Django’s messages framework.
• Flash a message after certain actions by user.
Design concern
• Easy to use and simple implementation.
• Messages cannot be dropped on redirection.
• All unseen messages need to be displayed.
Problems
• Implementation
• Storage
Messages Lifetime
• Request coming in.
• Server execute an action based on passed
parameters.
• Server popup a message to user.
• User sees the web page and the message.
Hook
• def prepare(self)
• def render(self, template_name, **kwargs)
Easy Solution
def prepare(self):
# Define a message array as a property of each
# request, and just append every message to
# it.
self.request.messages = []
!
def MyHandler(tornado.web.RequestHandler):
def get(self):
self.request.messages.append("error")
return self.render("my_page.html")
Redirection
Message got lost.!
why?
Cookies!
or session storage
Solution
• Save messages in cookies
• Clear messages only after user has seen.
How?
• def redirect(self, url, permanet=False,
status=None)
• def __iter__(self)
HTML
{% if messages %}
<ul class="messages">
{% for message in messages %}
<li>{{ message }}</li>
{% end %}
</ul>
{% end %}
Clear
• We can erase all messages stored in cookies
after __iter__ method of Message object was
called.
• We don’t need to update cookies when there is
no redirections happen.
To sum up
class BaseHandler(tornado.web.RequestHandler):
def prepare(self):
# Create Message object in order to store instant messages.
self.messages = FlashMessage(handler=self)
!
def redirect(self, url, permanent=False, status=None):
if hasattr(self, "messages"):
# Update messages in Cookie, write in or clear all.
self.messages.update_messages()
!
!
class LoginHandler(BaseHandler):
def post(self):
# Write message to object owned structure.
messages.success(self.messages, "Login successfully!")
!
# Redirect to another handler.
self.redirect("/")
Message Insight
!
!
class FlashMessage(object):
"""
A Django messages framework mockup, use cookie to store messages.
"""
…
!
def __iter__(self):
self.used = True
if self._queued_messages:
self._loaded_messages.extend(self._queued_messages)
self._queued_messages = []
# Update messages stored in Cookie
self.update_messages()
return iter(self._loaded_messages)
!
def update_messages(self):
if self.used:
self._store(self._queued_messages)
elif self.added_new:
messages = self._loaded_messages + self._queued_messages
self._store(messages)
!
def _update_cookie(self, encoded_data):
if encoded_data and eval(encoded_data or ''):
self._handler.set_secure_cookie(self.cookie_name, encoded_data,
expires_days=None,
domain=settings.SESSION_COOKIE_DOMAIN)
else:
self._handler.clear_cookie(self.cookie_name,
domain=settings.SESSION_COOKIE_DOMAIN)
!
def _store(self, messages):
encoded_data = self._encode(messages)
# Update cookie, remove if no data included.
self._update_cookie(encoded_data)
Read the source code to get more of it!
Thank you!

More Related Content

What's hot

Harness jQuery Templates and Data Link
Harness jQuery Templates and Data LinkHarness jQuery Templates and Data Link
Harness jQuery Templates and Data LinkBorisMoore
 
03 Web Events and jQuery
03 Web Events and jQuery03 Web Events and jQuery
03 Web Events and jQuerycrgwbr
 
Introduction to jQuery
Introduction to jQueryIntroduction to jQuery
Introduction to jQueryJames Johnson
 
A slightly advanced introduction to node.js
A slightly advanced introduction to node.jsA slightly advanced introduction to node.js
A slightly advanced introduction to node.jsSudar Muthu
 
Cache for community edition
Cache for community editionCache for community edition
Cache for community editionirfan1008
 
JavaScript Dependencies, Modules & Browserify
JavaScript Dependencies, Modules & BrowserifyJavaScript Dependencies, Modules & Browserify
JavaScript Dependencies, Modules & BrowserifyJohan Nilsson
 
Synchronizing without internet - Multipeer Connectivity (iOS)
Synchronizing without internet - Multipeer Connectivity (iOS)Synchronizing without internet - Multipeer Connectivity (iOS)
Synchronizing without internet - Multipeer Connectivity (iOS)Jorge Maroto
 
A SOLID Design in InterSystems ObjectScript
A SOLID Design in InterSystems ObjectScriptA SOLID Design in InterSystems ObjectScript
A SOLID Design in InterSystems ObjectScriptAnastasiaDyubaylo
 
Multipeer Connectivity
Multipeer ConnectivityMultipeer Connectivity
Multipeer Connectivitywaynehartman
 
JavaScript and jQuery Basics
JavaScript and jQuery BasicsJavaScript and jQuery Basics
JavaScript and jQuery BasicsKaloyan Kosev
 
Difference between java script and jquery
Difference between java script and jqueryDifference between java script and jquery
Difference between java script and jqueryUmar Ali
 
NSCoder Keynote - Multipeer Connectivity Framework
NSCoder Keynote - Multipeer Connectivity FrameworkNSCoder Keynote - Multipeer Connectivity Framework
NSCoder Keynote - Multipeer Connectivity FrameworkAlex Rupérez
 
Jms слайды
Jms слайдыJms слайды
Jms слайдыSergey D
 
[Mas 500] Web Basics
[Mas 500] Web Basics[Mas 500] Web Basics
[Mas 500] Web Basicsrahulbot
 

What's hot (20)

Harness jQuery Templates and Data Link
Harness jQuery Templates and Data LinkHarness jQuery Templates and Data Link
Harness jQuery Templates and Data Link
 
03 Web Events and jQuery
03 Web Events and jQuery03 Web Events and jQuery
03 Web Events and jQuery
 
Node.js Express Framework
Node.js Express FrameworkNode.js Express Framework
Node.js Express Framework
 
J servlets
J servletsJ servlets
J servlets
 
Introduction to jQuery
Introduction to jQueryIntroduction to jQuery
Introduction to jQuery
 
Spring ws
Spring wsSpring ws
Spring ws
 
Dwr
DwrDwr
Dwr
 
Fundaments of Knockout js
Fundaments of Knockout jsFundaments of Knockout js
Fundaments of Knockout js
 
A slightly advanced introduction to node.js
A slightly advanced introduction to node.jsA slightly advanced introduction to node.js
A slightly advanced introduction to node.js
 
Cache for community edition
Cache for community editionCache for community edition
Cache for community edition
 
Beginning jQuery
Beginning jQueryBeginning jQuery
Beginning jQuery
 
JavaScript Dependencies, Modules & Browserify
JavaScript Dependencies, Modules & BrowserifyJavaScript Dependencies, Modules & Browserify
JavaScript Dependencies, Modules & Browserify
 
Synchronizing without internet - Multipeer Connectivity (iOS)
Synchronizing without internet - Multipeer Connectivity (iOS)Synchronizing without internet - Multipeer Connectivity (iOS)
Synchronizing without internet - Multipeer Connectivity (iOS)
 
A SOLID Design in InterSystems ObjectScript
A SOLID Design in InterSystems ObjectScriptA SOLID Design in InterSystems ObjectScript
A SOLID Design in InterSystems ObjectScript
 
Multipeer Connectivity
Multipeer ConnectivityMultipeer Connectivity
Multipeer Connectivity
 
JavaScript and jQuery Basics
JavaScript and jQuery BasicsJavaScript and jQuery Basics
JavaScript and jQuery Basics
 
Difference between java script and jquery
Difference between java script and jqueryDifference between java script and jquery
Difference between java script and jquery
 
NSCoder Keynote - Multipeer Connectivity Framework
NSCoder Keynote - Multipeer Connectivity FrameworkNSCoder Keynote - Multipeer Connectivity Framework
NSCoder Keynote - Multipeer Connectivity Framework
 
Jms слайды
Jms слайдыJms слайды
Jms слайды
 
[Mas 500] Web Basics
[Mas 500] Web Basics[Mas 500] Web Basics
[Mas 500] Web Basics
 

Similar to Introduction to a simple messages framework for Tornado

WordPress Internationalization and Localization - WordPress Translation Day 3...
WordPress Internationalization and Localization - WordPress Translation Day 3...WordPress Internationalization and Localization - WordPress Translation Day 3...
WordPress Internationalization and Localization - WordPress Translation Day 3...WordPress Trivandrum
 
Meebo performance ny_web_performance
Meebo performance ny_web_performanceMeebo performance ny_web_performance
Meebo performance ny_web_performancemarcuswestin
 
Wordpress beyond blogging
Wordpress beyond bloggingWordpress beyond blogging
Wordpress beyond bloggingJulien Minguely
 
Selenium Introduction by Sandeep Sharda
Selenium Introduction by Sandeep ShardaSelenium Introduction by Sandeep Sharda
Selenium Introduction by Sandeep ShardaEr. Sndp Srda
 
The Time for Vanilla Web Components has Arrived
The Time for Vanilla Web Components has ArrivedThe Time for Vanilla Web Components has Arrived
The Time for Vanilla Web Components has ArrivedGil Fink
 
7 tips for javascript rich ajax websites
7 tips for javascript rich ajax websites7 tips for javascript rich ajax websites
7 tips for javascript rich ajax websitesoazabir
 
WordPress Theme Development: Part 2
WordPress Theme Development: Part 2WordPress Theme Development: Part 2
WordPress Theme Development: Part 2Josh Lee
 
Message Driven Beans (6)
Message Driven Beans (6)Message Driven Beans (6)
Message Driven Beans (6)Abdalla Mahmoud
 
Osiąganie mądrej architektury z Symfony2
Osiąganie mądrej architektury z Symfony2 Osiąganie mądrej architektury z Symfony2
Osiąganie mądrej architektury z Symfony2 3camp
 
MAKE YOUR THEMES AND PLUGINS READY FOR TRANSLATION
MAKE YOUR THEMES AND PLUGINS READY FOR TRANSLATIONMAKE YOUR THEMES AND PLUGINS READY FOR TRANSLATION
MAKE YOUR THEMES AND PLUGINS READY FOR TRANSLATIONMakarand Mane
 
Real World Seaside Applications
Real World Seaside ApplicationsReal World Seaside Applications
Real World Seaside ApplicationsESUG
 
React Basic and Advance || React Basic
React Basic and Advance   || React BasicReact Basic and Advance   || React Basic
React Basic and Advance || React Basicrafaqathussainc077
 
EWD 3 Training Course Part 7: Applying the QEWD Messaging Pattern
EWD 3 Training Course Part 7: Applying the QEWD Messaging PatternEWD 3 Training Course Part 7: Applying the QEWD Messaging Pattern
EWD 3 Training Course Part 7: Applying the QEWD Messaging PatternRob Tweed
 
WordPress Developers Israel Meetup #1
WordPress Developers Israel Meetup #1WordPress Developers Israel Meetup #1
WordPress Developers Israel Meetup #1Yoav Farhi
 
Working with the django admin
Working with the django admin Working with the django admin
Working with the django admin flywindy
 
WordPress Customization and Security
WordPress Customization and SecurityWordPress Customization and Security
WordPress Customization and SecurityJoe Casabona
 

Similar to Introduction to a simple messages framework for Tornado (20)

Wordpress
WordpressWordpress
Wordpress
 
Introduction to Jquery
Introduction to JqueryIntroduction to Jquery
Introduction to Jquery
 
WordPress Internationalization and Localization - WordPress Translation Day 3...
WordPress Internationalization and Localization - WordPress Translation Day 3...WordPress Internationalization and Localization - WordPress Translation Day 3...
WordPress Internationalization and Localization - WordPress Translation Day 3...
 
Meebo performance ny_web_performance
Meebo performance ny_web_performanceMeebo performance ny_web_performance
Meebo performance ny_web_performance
 
Wordpress beyond blogging
Wordpress beyond bloggingWordpress beyond blogging
Wordpress beyond blogging
 
Selenium Introduction by Sandeep Sharda
Selenium Introduction by Sandeep ShardaSelenium Introduction by Sandeep Sharda
Selenium Introduction by Sandeep Sharda
 
The Time for Vanilla Web Components has Arrived
The Time for Vanilla Web Components has ArrivedThe Time for Vanilla Web Components has Arrived
The Time for Vanilla Web Components has Arrived
 
7 tips for javascript rich ajax websites
7 tips for javascript rich ajax websites7 tips for javascript rich ajax websites
7 tips for javascript rich ajax websites
 
Ruby For Startups
Ruby For StartupsRuby For Startups
Ruby For Startups
 
WordPress Theme Development: Part 2
WordPress Theme Development: Part 2WordPress Theme Development: Part 2
WordPress Theme Development: Part 2
 
Message Driven Beans (6)
Message Driven Beans (6)Message Driven Beans (6)
Message Driven Beans (6)
 
Requiring your own files.pptx
Requiring your own files.pptxRequiring your own files.pptx
Requiring your own files.pptx
 
Osiąganie mądrej architektury z Symfony2
Osiąganie mądrej architektury z Symfony2 Osiąganie mądrej architektury z Symfony2
Osiąganie mądrej architektury z Symfony2
 
MAKE YOUR THEMES AND PLUGINS READY FOR TRANSLATION
MAKE YOUR THEMES AND PLUGINS READY FOR TRANSLATIONMAKE YOUR THEMES AND PLUGINS READY FOR TRANSLATION
MAKE YOUR THEMES AND PLUGINS READY FOR TRANSLATION
 
Real World Seaside Applications
Real World Seaside ApplicationsReal World Seaside Applications
Real World Seaside Applications
 
React Basic and Advance || React Basic
React Basic and Advance   || React BasicReact Basic and Advance   || React Basic
React Basic and Advance || React Basic
 
EWD 3 Training Course Part 7: Applying the QEWD Messaging Pattern
EWD 3 Training Course Part 7: Applying the QEWD Messaging PatternEWD 3 Training Course Part 7: Applying the QEWD Messaging Pattern
EWD 3 Training Course Part 7: Applying the QEWD Messaging Pattern
 
WordPress Developers Israel Meetup #1
WordPress Developers Israel Meetup #1WordPress Developers Israel Meetup #1
WordPress Developers Israel Meetup #1
 
Working with the django admin
Working with the django admin Working with the django admin
Working with the django admin
 
WordPress Customization and Security
WordPress Customization and SecurityWordPress Customization and Security
WordPress Customization and Security
 

Recently uploaded

How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
Google AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGGoogle AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGSujit Pal
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...gurkirankumar98700
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...HostedbyConfluent
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 

Recently uploaded (20)

How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Google AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGGoogle AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAG
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 

Introduction to a simple messages framework for Tornado

  • 1. Introduction to a simple messages framework for Tornado Gao Chao 2014.03.14
  • 2. Tornado • A high performance asynchronous web framework. • Originated in FriendFeed, acquired by Facebook later on. • We are using it!
  • 3. Messages Framework • Taken from Django’s messages framework. • Flash a message after certain actions by user.
  • 4.
  • 5. Design concern • Easy to use and simple implementation. • Messages cannot be dropped on redirection. • All unseen messages need to be displayed.
  • 7. Messages Lifetime • Request coming in. • Server execute an action based on passed parameters. • Server popup a message to user. • User sees the web page and the message.
  • 8. Hook • def prepare(self) • def render(self, template_name, **kwargs)
  • 9. Easy Solution def prepare(self): # Define a message array as a property of each # request, and just append every message to # it. self.request.messages = [] ! def MyHandler(tornado.web.RequestHandler): def get(self): self.request.messages.append("error") return self.render("my_page.html")
  • 12. Solution • Save messages in cookies • Clear messages only after user has seen.
  • 13. How? • def redirect(self, url, permanet=False, status=None) • def __iter__(self)
  • 14. HTML {% if messages %} <ul class="messages"> {% for message in messages %} <li>{{ message }}</li> {% end %} </ul> {% end %}
  • 15. Clear • We can erase all messages stored in cookies after __iter__ method of Message object was called. • We don’t need to update cookies when there is no redirections happen.
  • 16. To sum up class BaseHandler(tornado.web.RequestHandler): def prepare(self): # Create Message object in order to store instant messages. self.messages = FlashMessage(handler=self) ! def redirect(self, url, permanent=False, status=None): if hasattr(self, "messages"): # Update messages in Cookie, write in or clear all. self.messages.update_messages() ! ! class LoginHandler(BaseHandler): def post(self): # Write message to object owned structure. messages.success(self.messages, "Login successfully!") ! # Redirect to another handler. self.redirect("/")
  • 17. Message Insight ! ! class FlashMessage(object): """ A Django messages framework mockup, use cookie to store messages. """ … ! def __iter__(self): self.used = True if self._queued_messages: self._loaded_messages.extend(self._queued_messages) self._queued_messages = [] # Update messages stored in Cookie self.update_messages() return iter(self._loaded_messages) ! def update_messages(self): if self.used: self._store(self._queued_messages) elif self.added_new: messages = self._loaded_messages + self._queued_messages self._store(messages) ! def _update_cookie(self, encoded_data): if encoded_data and eval(encoded_data or ''): self._handler.set_secure_cookie(self.cookie_name, encoded_data, expires_days=None, domain=settings.SESSION_COOKIE_DOMAIN) else: self._handler.clear_cookie(self.cookie_name, domain=settings.SESSION_COOKIE_DOMAIN) ! def _store(self, messages): encoded_data = self._encode(messages) # Update cookie, remove if no data included. self._update_cookie(encoded_data)
  • 18. Read the source code to get more of it!