【问题标题】:Flask's test_client() is not passing custom HTTP Headers to the Flask appFlask 的 test_client() 没有将自定义 HTTP 标头传递给 Flask 应用程序
【发布时间】:2018-09-17 12:59:28
【问题描述】:

我的测试脚本中有这样的内容:

def setUp(self):
    app = create_app()
    self.app = app.test_client()

def test_001(self):

    with self.app as app:
        headers = { 'API-KEY': 'myKey' }            
        app.get('/endpoint1', follow_redirects=True,headers=headers)

阅读我的应用程序的打印语句,我可以看到我的应用程序端点被调用,除了请求中缺少标头之外,一切看起来都很正常。

在我的 API 中,我有这个打印语句:

log("Headers: " + str(request.headers))

这会在控制台中输出以下消息:

Headers: User-Agent: werkzeug/0.14.1
Host: localhost
Content-Length: 0

显然,客户端确实发送了一些标题,但没有发送我添加的自定义标题。

有没有人看到我做错了什么,这导致标头要么一开始就没有被发送,要么服务器无法访问它们?

【问题讨论】:

  • self.app = create_app() 并尝试client = app.test_client() 而不是self.app = app.test_client() 然后client.get() 你需要app.config['TESTING'] = True

标签: python-3.x flask flask-restful


【解决方案1】:
def setUp(self):
    self.app = create_app()
    self.app.config['TESTING'] = True
    self.app_context = self.app.app_context()
    self.app_context.push()
    self.client = self.app.test_client()

def test_001(self):
    headers = { 'API-KEY': 'myKey' }            
    response = self.client.get('/endpoint1', follow_redirects=True, headers=headers)

【讨论】:

    【解决方案2】:

    对于仍在苦苦挣扎的人: 使用follow_redirects=True 会以某种方式丢失重定向的标头。

    简单的解决方法是自己进行重定向:

    headers = { 'KEY': '123' }
    code = 301
    url = '/v1/endpoint'
    
    while code == 301:
        response = client.get(url, headers=headers)
        code = response._status_code
        if code == 301: #'Location' is only in header if 301
            url = response.headers['Location']
    
    

    【讨论】:

      猜你喜欢
      • 2020-07-17
      • 1970-01-01
      • 1970-01-01
      • 2012-11-17
      • 2022-01-18
      • 2016-02-14
      • 2017-12-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多