SlideShare a Scribd company logo
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.
A Django like messages framework for Tornado
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

PPTX
jQuery - Web Engineering
PPTX
Nodejs functions & modules
PPT
KnockoutJS and MVVM
PDF
4η διάλεξη Τεχνολογίες Παγκόσμιου Ιστού
PDF
Ride on the Fast Track of Web with Ruby on Rails
PDF
Ride on the Fast Track of Web with Ruby on Rails- Part 1
PDF
An introduction to knockout.js
PPT
JS, CMS, untangle the mess
jQuery - Web Engineering
Nodejs functions & modules
KnockoutJS and MVVM
4η διάλεξη Τεχνολογίες Παγκόσμιου Ιστού
Ride on the Fast Track of Web with Ruby on Rails
Ride on the Fast Track of Web with Ruby on Rails- Part 1
An introduction to knockout.js
JS, CMS, untangle the mess

What's hot (20)

PPTX
Harness jQuery Templates and Data Link
PDF
03 Web Events and jQuery
PPT
Node.js Express Framework
PPTX
J servlets
PPTX
Introduction to jQuery
PDF
Spring ws
PPT
PPTX
Fundaments of Knockout js
PPTX
A slightly advanced introduction to node.js
PPTX
Cache for community edition
PPTX
Beginning jQuery
PDF
JavaScript Dependencies, Modules & Browserify
PDF
Synchronizing without internet - Multipeer Connectivity (iOS)
PDF
A SOLID Design in InterSystems ObjectScript
PDF
Multipeer Connectivity
PPTX
JavaScript and jQuery Basics
PDF
Difference between java script and jquery
PDF
NSCoder Keynote - Multipeer Connectivity Framework
PDF
Jms слайды
PPTX
[Mas 500] Web Basics
Harness jQuery Templates and Data Link
03 Web Events and jQuery
Node.js Express Framework
J servlets
Introduction to jQuery
Spring ws
Fundaments of Knockout js
A slightly advanced introduction to node.js
Cache for community edition
Beginning jQuery
JavaScript Dependencies, Modules & Browserify
Synchronizing without internet - Multipeer Connectivity (iOS)
A SOLID Design in InterSystems ObjectScript
Multipeer Connectivity
JavaScript and jQuery Basics
Difference between java script and jquery
NSCoder Keynote - Multipeer Connectivity Framework
Jms слайды
[Mas 500] Web Basics
Ad

Similar to A Django like messages framework for Tornado (20)

PDF
Best Wordprees development company in bangalore
PDF
Website development PDF which helps others make it easy
PPTX
Wordpress
PPTX
Introduction to Jquery
PPTX
WordPress Internationalization and Localization - WordPress Translation Day 3...
PDF
Meebo performance ny_web_performance
PDF
Wordpress beyond blogging
PDF
Selenium Introduction by Sandeep Sharda
PDF
The Time for Vanilla Web Components has Arrived
PPTX
7 tips for javascript rich ajax websites
KEY
Ruby For Startups
PPTX
WordPress Theme Development: Part 2
PDF
Message Driven Beans (6)
PPTX
Requiring your own files.pptx
PDF
Osiąganie mądrej architektury z Symfony2
PPTX
MAKE YOUR THEMES AND PLUGINS READY FOR TRANSLATION
PDF
Real World Seaside Applications
PPTX
React Basic and Advance || React Basic
PDF
EWD 3 Training Course Part 7: Applying the QEWD Messaging Pattern
KEY
WordPress Developers Israel Meetup #1
Best Wordprees development company in bangalore
Website development PDF which helps others make it easy
Wordpress
Introduction to Jquery
WordPress Internationalization and Localization - WordPress Translation Day 3...
Meebo performance ny_web_performance
Wordpress beyond blogging
Selenium Introduction by Sandeep Sharda
The Time for Vanilla Web Components has Arrived
7 tips for javascript rich ajax websites
Ruby For Startups
WordPress Theme Development: Part 2
Message Driven Beans (6)
Requiring your own files.pptx
Osiąganie mądrej architektury z Symfony2
MAKE YOUR THEMES AND PLUGINS READY FOR TRANSLATION
Real World Seaside Applications
React Basic and Advance || React Basic
EWD 3 Training Course Part 7: Applying the QEWD Messaging Pattern
WordPress Developers Israel Meetup #1
Ad

Recently uploaded (20)

PPTX
sap open course for s4hana steps from ECC to s4
PDF
Electronic commerce courselecture one. Pdf
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PPTX
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
PDF
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
PDF
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PDF
Chapter 3 Spatial Domain Image Processing.pdf
PDF
Review of recent advances in non-invasive hemoglobin estimation
PDF
NewMind AI Weekly Chronicles - August'25 Week I
PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
PPTX
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PDF
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PDF
Machine learning based COVID-19 study performance prediction
PDF
Encapsulation theory and applications.pdf
sap open course for s4hana steps from ECC to s4
Electronic commerce courselecture one. Pdf
The Rise and Fall of 3GPP – Time for a Sabbatical?
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
“AI and Expert System Decision Support & Business Intelligence Systems”
Chapter 3 Spatial Domain Image Processing.pdf
Review of recent advances in non-invasive hemoglobin estimation
NewMind AI Weekly Chronicles - August'25 Week I
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
Reach Out and Touch Someone: Haptics and Empathic Computing
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
Per capita expenditure prediction using model stacking based on satellite ima...
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
Diabetes mellitus diagnosis method based random forest with bat algorithm
Machine learning based COVID-19 study performance prediction
Encapsulation theory and applications.pdf

A Django like 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.
  • 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!