简体   繁体   English

Python Flask “make_response”来自字符串

[英]Python Flask “make_response” from string

I have a string which contains a specific response.我有一个包含特定响应的字符串。 For example:例如:

b'HTTP/1.0 302 Redirect\r\nServer: Http Server\r\nDate: Sun Jun  7 12:53:19 2020\r\nPragma: no-cache\r\nCache-Control: no-cache\r\nContent-Type: text/html\r\nLocation: http://192.168.3.1/main.html\r\n\r\n<html><head></head><body>\r\n\t\tThis document has moved to a new <a href="http://192.168.3.1/main.html">location</a>.\r\n\t\tPlease update your documents to reflect the new location.\r\n\t\t</body></html>\r\n\r\n'

And I want to build and return the response from this.我想建立并返回这个响应。 Is there any way I can do that with a Flask function?有什么办法可以用 Flask function 做到这一点?

I already tried make_response function as such return make_response(my_string) but it returns:我已经尝试过 make_response function 这样return make_response(my_string)但它返回:

HTTP/1.0 200 OK
Content-Type: text/html; charset=utf-8
Content-Length: 383
Server: Werkzeug/1.0.1 Python/3.6.9
Date: Sun, 07 Jun 2020 12:32:05 GMT

HTTP/1.0 302 Redirect
Server: Http Server
Date: Sun Jun  7 12:53:19 2020
Pragma: no-cache
Cache-Control: no-cache
Content-Type: text/html
Location: http://192.168.3.1/main.html

<html><head></head><body>
        This document has moved to a new <a href="http://192.168.3.1/main.html">location</a>.
        Please update your documents to reflect the new location.
        </body></html>

Thanks.谢谢。

I don't think this is possible in a simple way with flask.我认为使用 flask 不可能以简单的方式实现这一点。

You have a raw HTTP response containing all the response headers and the HTTP contents in one string.您有一个原始的 HTTP 响应,其中包含一个字符串中的所有响应标头和 HTTP 内容。

flask is a wsgi application returning headers and the response in separate fields and letting the wsgi server combine both. flask 是一个 wsgi 应用程序,它在单独的字段中返回标头和响应,并让 wsgi 服务器将两者结合起来。

Theoretically you could try to parse the string, split it into head fields and contents, return it and let the wsgi server recombine it to a string.从理论上讲,您可以尝试解析字符串,将其拆分为头字段和内容,将其返回并让 wsgi 服务器将其重新组合为字符串。 (potentially you could use libraries like requests and try to monkeypatch / mock it to do the parsing for you) (可能您可以使用requests之类的库并尝试对其进行monkeypatch / mock它来为您进行解析)

But this feels like a major patchwork and I wouldn't recommend it.但这感觉像是一个主要的拼凑,我不会推荐它。

Perhaps you can explain the bigger context and we might come up with a solution that does what it wants, though it will probably not convert a string into a flask response that will be returned by the wsgi server.也许您可以解释更大的上下文,我们可能会想出一个解决方案来做它想要的,尽管它可能不会将字符串转换为将由 wsgi 服务器返回的 flask 响应。

Where did you / do you get the string from Couldn't you reveive it already as a parsed HTTP response?你从哪里/你从哪里得到的字符串你不能把它作为解析的 HTTP 响应吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM