user11862294
user11862294

Reputation:

Get the URL of a server

I am using flask and flask email for sending an email. When I work on I used the localhost as a base url. I deployed it on the server and email sent is still showing with localhost address. For example

base_url = "http://localhost:0.0.0.6465"
url=base_url+'/login'

I sent an email(i am using flask-mail) with the url and I can login with the url.

With the same script when I deployed on the server I am getting with same localhost address.I need the server URL should be the base url. To debug this I tried

url=request.base_url+'/login'

I am getting 404 error in the browser if I use this. I dont want to change the initializtion of base_url because I have to use both in the local as well as in the server. How can I do that?

Upvotes: 0

Views: 1269

Answers (1)

MatsLindh
MatsLindh

Reputation: 52882

You can get the URL to the currently running app through request.host_url. But what you really want to to do to get an external URL to a specific part of your application, is to use url_for as you'd do when referencing your regular endpoints, but with the parameter _external=True:

Given that you have:

@app.route('/login')
def login():
    ....

You can generate an external URL by using:

from flask import (
    url_for,
)

...

url = url_for('login', _external=True)

This will also take into account any proxies in front of your application if you need that, as long as you've used the ProxyFix middleware when setting up your app object.

Since this uses the same mechanism as Flask uses when generating URLs between different pages, it should behave just as you want - i.e. it'll work both on localhost and on the remote host.

Upvotes: 2

Related Questions