【问题标题】:How to correctly get current URL Address in Python?如何在 Python 中正确获取当前 URL 地址?
【发布时间】:2019-07-03 09:33:28
【问题描述】:

我在 localhost(http://127.0.0.1:5000/) 上运行我的项目,并且在我的客户端服务器上会有所不同。所以我尝试尝试动态获取 URL 地址但无济于事。

我试过:request.host_url,如 thread 所示。但是,它返回了

RuntimeError: working outside of request context

我在这里尝试运行需要完整 URL 作为参数 post() 的 python unittest,这就是我需要动态 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()

关于如何在 python 中正确获取当前 URL 地址的任何提示?谢谢

【问题讨论】:

  • 你能告诉我们你正在使用的代码部分吗
  • @Shadowfax,我已经为您编辑了添加代码 sn-p 的问题。只是我认为这不是代码错误,这就是我没有发布长 sn-p 的原因。请帮助。谢谢

标签: python request


【解决方案1】:

来自request 文档

request.base_url 应该是您应该使用的。我在任何地方都找不到request.host_url 的文档。

【讨论】:

  • 谢谢我仍然收到错误:在请求上下文之外工作。
  • @HouyNarun 来自here,将你的线程代码包装在test_request_context
【解决方案2】:

请求对象有一个.host 属性,它会给你IP和你的代码运行的端口。

request.host

要仅获取主机名或 IP 地址,请尝试:

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

或者您可以直接查询WSGI 环境:

request.environ['SERVER_NAME']

【讨论】:

    【解决方案3】:

    据我所知,request.host 在烧瓶中的路由功能之外不起作用。 例如,做这样的事情

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

    这会起作用,因为它在路由函数中。

    【讨论】:

      猜你喜欢
      • 2017-11-29
      • 1970-01-01
      • 1970-01-01
      • 2016-05-04
      • 1970-01-01
      • 2012-11-04
      • 2017-05-03
      • 1970-01-01
      • 2012-03-31
      相关资源
      最近更新 更多