heroku-python / flask-sockets

[DEPRECATED] Alternative: https://github.com/miguelgrinberg/flask-sock
MIT License
1.74k stars 164 forks source link

Support url_for() #6

Open mbr opened 10 years ago

mbr commented 10 years ago

It'd be really nice to have url_for support, like:

@sockets.route('/echo/')
def echo():
    # ....

@app.route('/')
def index():
    return render_template('index.html', ws_url=url_for('sockets.echo', _external=True))

This should cause ws_url to be set to something like ws://localhost:5000/echo/.

digulla commented 10 years ago

I was struggling with the same issue. My current solution is this code in the template:

var wsurl = "{{ url_for('index') }}";

and then later in some JavaScript, I convert that into a WS URL:

// copied from http://stackoverflow.com/questions/470832/getting-an-absolute-url-from-a-relative-one-ie6-issue
var resolve = function(url) {
    var a = document.createElement('a');
    a.href = url;
    return a.href;
};

wsurl = 'ws' + resolve(wsurl).substring(4) + 'echo';

Note: You'll get strange errors if you use /echo (the resulting URL will contain domain//echo).