« Back to Index

[Simple Tornado]

View original Gist on GitHub

Tags: #python #python3 #tornado #example #basic #simple

Simple Tornado.py

import tornado.ioloop
import tornado.web


class MainHandler(tornado.web.RequestHandler):
    def get(self):
        self.set_cookie('foo', 'bar')
        print(self.request.headers)
        self.render('form.html')

    def post(self):
        print(self.request.headers)
        cookie = self.get_cookie('foo')
        self.finish({'state': 'success', 'foo_cookie': cookie})

def make_app():
    return tornado.web.Application([
        (r'/', MainHandler),
    ])


if __name__ == '__main__':
    app = make_app()
    app.listen(9000)
    tornado.ioloop.IOLoop.current().start()

form.html

<html>
<head>
  <script>
    function request(url, params, callback) {
      var xhr = new XMLHttpRequest();

      xhr.open('POST', url, true);
      xhr.setRequestHeader('content-type', 'application/x-www-form-urlencoded');

      xhr.onreadystatechange = function() {
        if (xhr.readyState == 4) {
          if (xhr.status == 500) {
            return callback({
              'state': 'error',
              'message': 'There was a problem processing this request.'
            });
          }
          var response = JSON.parse(xhr.responseText);
          return callback(response);
        }
      };

      xhr.send(params);
    }


    document.addEventListener('DOMContentLoaded', (event) => {
      var submit = document.getElementById('myform');
      submit.addEventListener('submit', function(e){
        e.preventDefault();

        var url = '/';
        var params = 'beep=boop&tokens=blah&_xsrf=123';
        var callback = function(response){
          console.log(response);
        };

        request(url, params, callback);
      });
    });
  </script>
</head>
<body>
  <form id="myform">
    <input type="submit">
  </form>
</body>
</html>