英文:
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('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]
# Define the handling function for every packet
def forward_packet(packet):
# Modify or process the packet as needed
print('Received packet:', packet)
try:
# Forward the packet to 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 the response
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
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('Error handling GET request:\n')
#return str(e), 500
@app.route('/<path:path>', methods=['GET'])
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 = '/' + path + end_url_args
return handle_get_request(path)
if __name__ == '__main__':
app.run(host='0.0.0.0', port=8080)
The error:
Traceback (most recent call last):
File "/usr/lib/python3/dist-packages/flask/app.py", line 2525, in wsgi_app
response = self.full_dispatch_request()
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/usr/lib/python3/dist-packages/flask/app.py", line 1822, in full_dispatch_request
rv = self.handle_user_exception(e)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/usr/lib/python3/dist-packages/flask/app.py", line 1820, in full_dispatch_request
rv = self.dispatch_request()
^^^^^^^^^^^^^^^^^^^^^^^
File "/usr/lib/python3/dist-packages/flask/app.py", line 1796, in dispatch_request
return self.ensure_sync(self.view_functions[rule.endpoint])(**view_args)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/eesa/Code/proxyforblocking/attempt2.py", line 63, in handle_get
return handle_get_request(path)
^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/eesa/Code/proxyforblocking/attempt2.py", line 49, in handle_get_request
response = forward_packet(path)
^^^^^^^^^^^^^^^^^^^^
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
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('utf8', errors='ignore'),
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('utf8', errors='ignore'),
int(google_response.status_code),
json.dumps(google_response.headers) # alternatively, str(google_response.headers)
]
# ...
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论