在处理 Flask 的 GET 请求时,我收到错误信息:’tuple’ 对象无法解释为整数。

huangapple go评论113阅读模式
英文:

During GET request handling with flask, I get the error: 'tuple' object cannot be interpreted as an integer

问题

I'll provide the translation for the code parts you provided:

我正在制作一个代理正确的术语吗?)来将我的Flask Web服务器的所有流量转发到google.com然后返回它。(如果我访问127.0.0.1/search?q=stack%20overflow它应该返回google.com/search?q=stack%20overflow的内容)。

代码如下

from flask import Flask, request, Response
import requests
import urllib.parse

app = Flask(__name__)

# 为URL添加百分比编码(如%20)
def add_percent_codes(urlsection):
    return urllib.parse.quote(urlsection.encode('utf8'))

def parse_sent_args(args_dict):
    args_str = '?'
    for key in args_dict:
        args_str += str(key) + '=' + str(args_dict[key]) + '&'
    return args_str[:-1]

# 定义处理每个数据包的函数
def forward_packet(packet):
    # 根据需要修改或处理数据包
    print('Received packet:', packet)

    try:
        # 将数据包转发到Google.com
        google_response = requests.get('https://www.google.com/' + packet)
        response_to_return = [
            google_response.content.decode('utf8', errors='ignore'),
            int(google_response.status_code),
            bytes(google_response.headers.items()).decode('utf8', errors='ignore')
        ]
        print('Forwarded packet to Google.com.')

        # 返回响应
        return response_to_return

    except requests.exceptions.HTTPError as e:
        print('Error forwarding packet:', e)
        return 'HTTPError occurred: {}'.format(e), 500

    except requests.exceptions.RequestException as e:
        print('Error forwarding packet:', e)
        return 'RequestException occurred: {}'.format(e), 500

# 处理GET请求的函数
def handle_get_request(path):
    try:
        # 调用处理数据包的函数
        response = forward_packet(path)
        return response
    finally:
        pass

@app.route('/<path:path>', methods=['GET'])
def handle_get(path):
    # 从URL路径中获取传入的数据包
    args_dict = dict(request.args)
    end_url_args = parse_sent_args(args_dict)
    full_path = '/' + path + end_url_args
    return handle_get_request(path)

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=8080)

错误部分:

Traceback (most recent call last):
File "/usr/lib/python3/dist-packages/flask/app.py", line 2525, in wsgi_app
response = self.full_dispatch_request()
...
TypeError: 'tuple' object cannot be interpreted as an integer

希望这些翻译有所帮助。如果您需要进一步的帮助,请随时提问。

英文:

I am working on a proxy (correct term?) to forward all traffic from my Flask web server to google.com, then return it. (If I go to 127.0.0.1/search?q=stack%20overflow, it should return the content of google.com/search?q=stack%20overflow).

<strike>The error occurs in flask, not my code.</strike>
Thank you to @LukeWoodward for pointing this out.

My code:

from flask import Flask, request, Response
import requests
import urllib.parse
app = Flask(__name__)
# Add percent codes (like %20) to URLs
def add_percent_codes(urlsection):
return urllib.parse.quote(urlsection.encode(&#39;utf8&#39;))
def parse_sent_args(args_dict):
args_str = &#39;?&#39;
for key in args_dict:
args_str += str(key) + &#39;=&#39; + str(args_dict[key]) + &#39;&amp;&#39;
return args_str[:-1]
# Define the handling function for every packet
def forward_packet(packet):
# Modify or process the packet as needed
print(&#39;Received packet:&#39;, packet)
try:
# Forward the packet to Google.com
google_response = requests.get(&#39;https://www.google.com/&#39; + packet)
response_to_return = \
[google_response.content.decode(&#39;utf8&#39;, errors=&#39;ignore&#39;),
int(google_response.status_code),
bytes(google_response.headers.items()).decode(&#39;utf8&#39;, errors=&#39;ignore&#39;)]
print(&#39;Forwarded packet to Google.com.&#39;)
# Return the response
return response_to_return
except requests.exceptions.HTTPError as e:
print(&#39;Error forwarding packet:&#39;, e)
return &#39;HTTPError occurred: {}&#39;.format(e), 500
except requests.exceptions.RequestException as e:
print(&#39;Error forwarding packet:&#39;, e)
return &#39;RequestException occurred: {}&#39;.format(e), 500
def handle_get_request(path):
try:
# Call the handling function for the packet
response = forward_packet(path)
return response
finally: pass
#except Exception as e:
#print(&#39;Error handling GET request:\n&#39;)
#return str(e), 500
@app.route(&#39;/&lt;path:path&gt;&#39;, methods=[&#39;GET&#39;])
def handle_get(path):
# Get the incoming packet from the URL path
args_dict = dict(request.args)
end_url_args = parse_sent_args(args_dict)
full_path = &#39;/&#39; + path + end_url_args
return handle_get_request(path)
if __name__ == &#39;__main__&#39;:
app.run(host=&#39;0.0.0.0&#39;, port=8080)

The error:

Traceback (most recent call last):
File &quot;/usr/lib/python3/dist-packages/flask/app.py&quot;, line 2525, in wsgi_app
response = self.full_dispatch_request()
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File &quot;/usr/lib/python3/dist-packages/flask/app.py&quot;, line 1822, in full_dispatch_request
rv = self.handle_user_exception(e)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File &quot;/usr/lib/python3/dist-packages/flask/app.py&quot;, line 1820, in full_dispatch_request
rv = self.dispatch_request()
^^^^^^^^^^^^^^^^^^^^^^^
File &quot;/usr/lib/python3/dist-packages/flask/app.py&quot;, line 1796, in dispatch_request
return self.ensure_sync(self.view_functions[rule.endpoint])(**view_args)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File &quot;/home/eesa/Code/proxyforblocking/attempt2.py&quot;, line 63, in handle_get
return handle_get_request(path)
^^^^^^^^^^^^^^^^^^^^^^^^
File &quot;/home/eesa/Code/proxyforblocking/attempt2.py&quot;, line 49, in handle_get_request
response = forward_packet(path)
^^^^^^^^^^^^^^^^^^^^
File &quot;/home/eesa/Code/proxyforblocking/attempt2.py&quot;, line 30, in forward_packet
bytes(google_response.headers.items()).decode(&#39;utf8&#39;, errors=&#39;ignore&#39;)]
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: &#39;tuple&#39; object cannot be interpreted as an integer

Small note: I commented out error handling to get the full traceback, and added the "finally" block to avoid other errors.

答案1

得分: 0

你的错误在这里的回溯中:

> 文件 "/home/eesa/Code/proxyforblocking/attempt2.py",第30行,在
> forward_packet
> 字节(google_response.headers.items()).decode('utf8', errors='ignore')]
> ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 类型错误:'tuple'对象无法解释为整数

请求的响应对象包含Response.headers中的HTTP头的字典,在你的代码中应该是google_response.headers。在这个字典上调用items()会返回一个字典视图。你正试图将一个字典视图传递给bytes构造函数,这会失败。

我不确定你在尝试做什么,但如果你只想返回Response对象提供的头,你可以将字典转换为字符串,或者你可以使用json模块创建头字典的JSON字符串表示。

例如:

import json

# ...
要返回的响应 = [
  google_response.content.decode(&#39;utf8&#39;, errors=&#39;ignore&#39;),
  int(google_response.status_code),
  json.dumps(google_response.headers)  # 或者,str(google_response.headers)
]
# ...
英文:

Your error is right here in the traceback:

> File "/home/eesa/Code/proxyforblocking/attempt2.py", line 30, in
> forward_packet
> bytes(google_response.headers.items()).decode('utf8', errors='ignore')]
> ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ TypeError: 'tuple' object cannot be interpreted as an integer

The requests Response object contains a dictionary of HTTP headers at Response.headers, which would be google_response.headers in your code. Calling items() on this dictionary returns a dictionary view. You are trying to pass a dictionary view to the bytes constructor, which is failing.

I'm not sure exactly what you're trying to do here, but if you just want to return the headers provided by the Response object, you could convert the dictionary to a string, or you could use the json module to create a JSON string representation of the headers dictionary.

For example:

import json

# ...
response_to_return = [
  google_response.content.decode(&#39;utf8&#39;, errors=&#39;ignore&#39;),
  int(google_response.status_code),
  json.dumps(google_response.headers)  # alternatively, str(google_response.headers)
]
# ...

huangapple
  • 本文由 发表于 2023年4月20日 04:47:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/76058689.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定