0

I'm running my project on localhost(http://127.0.0.1:5000/) and would be differently on my client server. So I try tried to dynamically get the URL Address but with no avail.

I tried: request.host_url as showing in this thread. However, it returned

RuntimeError: working outside of request context

Here what I tried to do is run python unittest that need full URL as parameter post(), that's a reason I need it dynamic url.

import json, requests

from flask import request
from .base import *

class TestProvince(BaseTest):

    # Test Data
    ID               = '41'
    DESCRIPTION      = 'Province Test'
    LOCAL_DESCRIPTION = 'Province local Description'

    def test_add_record(self):

        print "Adding a new record"

        url = "http://127.0.0.1:5000/Project/API/Province/" # <-- Here I want it to be dynamic url
        payload = {
                    "Status":"AUTH",
                    "Curr":"0",
                    "Inputter":"System",
                    "Createdon":"2019-05-03",
                    "Authorizer":"System",
                    "Authorizeon":"2019-05-03",
                    "Branch":"HO",
                    "ID":self.ID,
                    "Description":self.DESCRIPTION,
                    "LocalDescription":self.LOCAL_DESCRIPTION
                }
        headers = {
            'Content-Type': "application/json",
            'Accept': "application/json"
            }

        response = requests.request("POST", url, data=json.dumps(payload), headers=headers)


if __name__ == "__main__":
    unittest.main()

Any tip for how can I get current URL Address correctly in python? Thanks

Houy Narun
  • 1,557
  • 5
  • 37
  • 86
  • can you show us the part of code where you're using this – Shadowfax Jul 03 '19 at 09:35
  • @Shadowfax, I have edited question adding code snippet for you already. Just I think it is not code error, that's why I did not post long snippet. Please kindly help. Thanks – Houy Narun Jul 03 '19 at 09:54

3 Answers3

0

From request documentation

request.base_url should be what you should be using. I can't find documentation for request.host_url anywhere.

deezpeeps
  • 114
  • 2
  • 10
0

The request object has a .host attribute, it will give you the IP and the port where your code is running.

request.host

To get just the host name or IP address, try:

request.host.split(':')[0]

Or you could query the WSGI environment directly:

request.environ['SERVER_NAME']
Shadowfax
  • 556
  • 2
  • 13
0

From what I've learnt, request.host do not work outside the routes function in flask. For example, do something like this

@app.route('/')
def get_something():
    print(request.host)

This will work because it is in a route function.