Search code examples
pythontornado

How to show warning using Python tornado


Is there a way to show a warning to the user and just continue with the called function?

All I can find in tornado is the HTTPError. Is there anything like this to show a warning?

Current snippet:

if warning_bool:
    warning_text = "Warning! You can still continue though..."
    raise HTTPError(status_code=400, reason=warning_text)

put_function()

This raises an Error and the function is not called.


Solution

  • If you want to continue with your processing you will not want to raise an error. That has a number of effects depending on your setup. Typically raising an error will set the status to something other than 200, which probably isn't what you want. It will generally trip whatever exception logging you have (in our case it sends errors to sentry), and it will typically automatically roll back your database transactions.

    If you just want to display a warning to a user because they did something "bad" but continue processing you will want another mechanism. I have two different ways I handle this situation depending on the context. Most of the time I display a message automatically on the next page load(after the post that had the warning) by setting a cookie and displaying it. What works for you will be different depending on how your app is set up. If your calls are all ajax calls you can have an object for returning warnings and other messages built into you ajax calls.

    The other thing we do is that for some pages that are handling batch commands where there could be many warnings, then we have a special page that loads if there are warnings that knows how to handle a list of warnings.

    Here is our code that sets and reads the warning message in Python. This is in our base controller class so that it is available in all controllers. You could also write the read part in javascript:

    def flash(self, msg, msg_type="info"):
        self.flash_info = (msg, msg_type)
        self.set_cookie('flash', base64.b64encode(bytes(json.dumps([msg, msg_type]), 'utf-8')))
    
    def get_flash(self):
        msg = None
        msg_type = None
        if hasattr(self, "flash_info"):
            msg, msg_type = self.flash_info
        else:
            flash_msg = self.get_cookie('flash')
            if flash_msg:
                msg, msg_type = json.loads(base64.b64decode(flash_msg).decode('utf-8'))
                self.clear_cookie('flash')
        self.clear_cookie('flash')
        return msg, msg_type