I'm using Tornado Web Framework to build a websocket server and I need to connect via WebSocket from javascript. How can I get the server url and port from tornado templates?
I'm thinking in something like this:
<script>
var _url = "{{ (server_url) }}";
var _port = "{{ (server_port) }}";
var ws = new WebSocket("ws://" + _url + ":" + _port + "/socket");
</script>
I think you have to define it as context variables. Tornado doesn't provide this information to templates automatically.
It is a good idea to use tornado.options
to set this variables. And then, pass them to your template.
Simplified contents of app.py:
from tornado.options import options, define
define("host", default="localhost", help="app host", type=str)
define("port", default=3000, help="app port", type=int)
class WebsocketHandler(tornado.web.RequestHandler):
def get(self):
self.render(
"index_websocket.html",
server_url=options.host,
server_port=options.port
)
options.parse_command_line() # don't forget to parse command line
app = tornado.web.Application(...)
app.listen(options.port)
tornado.ioloop.IOLoop.instance().start()
In that case, you can run you application and provide defined settings:
python app.py --host=yourserveraddres.com --port=3000