【问题标题】:Werkzeug(Flask) response with redirect not workingWerkzeug(Flask)响应重定向不起作用
【发布时间】:2015-11-01 22:13:19
【问题描述】:

我正在构建一个简单的Flask 应用程序,我想返回重定向响应。另外,我想保持对标题的完全控制。

这是我目前得到的:

from flask import Flask
from werkzeug.wrappers import Response

app = Flask(__name__)

@app.route('/toexample')
def to_example():

    headers = {
            'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:39.0) Gecko/20100101 Firefox/39.0',
            'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
            'Accept-Language': 'en-US,en;q=0.5',
            'Accept-Encoding': 'gzip, deflate',
    }

    return Response('www.example.com', status_code=302, headers=headers)

if __name__ == '__main__':
    app.run(debug=True)

我收到一个错误:

TypeError: __init__() got an unexpected keyword argument 'status_code'

好的,看起来status_code__init__() 上不存在,但正确的做法是什么?

我最终想要的是一个用户会点击的链接,但我想再次保持对标题的控制(连接、Cookie、Referer 等

【问题讨论】:

    标签: python flask werkzeug


    【解决方案1】:

    我必须在标题中添加Location。还有,status_code 错了,应该是status=302

    工作示例:

    from flask import Flask
    from werkzeug.wrappers import Response
    
    app = Flask(__name__)
    
    @app.route('/toexample')
    def to_example():
    
        headers = {
                'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:39.0) Gecko/20100101 Firefox/39.0',
                'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
                'Accept-Language': 'en-US,en;q=0.5',
                'Accept-Encoding': 'gzip, deflate',
                'Location': 'http://www.example.com'
        }
    
        return Response('http://www.example.com', status=302, headers=headers)
    
    if __name__ == '__main__':
        app.run(debug=True)
    

    【讨论】:

    • 有趣。我没想到!看看我的例子。让我知道你的想法。实际上,我对我的解决方案持怀疑态度。有趣...
    【解决方案2】:

    这对我有用:

    from flask import Flask, redirect
    
    app = Flask(__name__)
    
    
    @app.route('/toexample')
    def to_example():
        response = redirect("http://www.example.com", code=302)
        headers = dict(response.headers)
        headers.update({'X-Custom-Header1': 'value1', 'X-Custom-Header2': 'value2'})
        response.headers = headers
        return response
    

    这对我有用 Flask v0.10.1。干杯!

    【讨论】:

      【解决方案3】:

      您想在这里使用两件事。首先,对于重定向,您想在您的to_example 调用中使用redirect

      @app.route('/toexample')
      def to_example():
          return redirect("http://www.example.com", code=302)
      

      现在,对于自定义标头和 cookie 的控制,您可以使用after_request,它允许您在向响应对象发出请求后设置某些自定义细节:

      @app.after_request
      def after_request(response):
          response.headers.add('Custom-Header', 'Custom Header')
          response.headers.add('Content-Type', 'application/json')
          response.set_cookie('some-cookie', value='some-cookie-value')
          return response
      

      综上所述,您的示例现在如下所示:

      from flask import Flask, redirect
      
      app = Flask(__name__)
      
      
      @app.route('/toexample')
      def to_example():
          return redirect("http://www.example.com", code=302)
      
      
      @app.after_request
      def after_request(response):
          response.headers.add('Custom-Header', 'Custom Header')
          response.headers.add('Content-Type', 'application/json')
          response.set_cookie('some-cookie', value='some-cookie-value')
          return response
      
      if __name__ == '__main__':
          app.run(debug=True)
      

      这是一个 curl 调用。注意标题。

      ▶ curl -v http://127.0.0.1:5000/toexample
      *   Trying 127.0.0.1...
      * Connected to 127.0.0.1 (127.0.0.1) port 5000 (#0)
      > GET /toexample HTTP/1.1
      > Host: 127.0.0.1:5000
      > User-Agent: curl/7.43.0
      > Accept: */*
      >
      * HTTP 1.0, assume close after body
      < HTTP/1.0 302 FOUND
      < Content-Type: text/html; charset=utf-8
      < Content-Length: 251
      < Location: http://www.example.com
      < Custom-Header: Custom Header
      < Content-Type: application/json
      < Set-Cookie: some-cookie=some-cookie-value; Path=/
      < Server: Werkzeug/0.10.4 Python/3.5.0
      < Date: Sun, 01 Nov 2015 23:11:30 GMT
      <
      <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
      <title>Redirecting...</title>
      <h1>Redirecting...</h1>
      * Closing connection 0
      <p>You should be redirected automatically to target URL: <a href="http://www.example.com">http://www.example.com</a>.  If not click the link.%
      

      【讨论】:

      • 我已经尝试过了,但它只是打印www.example.com 而根本没有重定向。 response 应该是什么字符串?
      • @intelis 告诉我你的想法。
      • 感谢您的回复,虽然我觉得我的方式更干净:)
      • 老实说,我自己并没有想到这一点 :) 这是在 Flask 定义 redirect 的源中完成的 ;)
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-19
      • 1970-01-01
      • 2019-09-02
      • 2015-12-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多