How to set the protocol (http, ws etc.) for the end-point using Jinja2 & url_for

Question:

I am trying to use the url_for(...) function in Python/Jinja2 to create an end-point for a web-socket.

How can I tell url_for(...) inside my template to use the ‘ws’ (web socket) protocol instead of ‘http’?

Asked By: JimmyNJ

||

Answers:

The url_for has two attributes you can use for this purpose:

  • _external = True for generating absolute URLs
  • _scheme = '' for setting an empty URL scheme (ws or wss is not supported directly)

After that, just put the ws: or wss: URL scheme string just before the url_for call in your template, e.g.:

wss:{{ url_for('websocket_endpoint', _external=True, _scheme='') }}

which will produce:

wss://yourdomain.com/websocket_endpoint
Answered By: Dauros
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.