我正在使用代理(正确的术语?)将Flask Web服务器的所有流量转发到google.com,然后返回它。(如果我转到127.0.0.1/search?q = stack%20overflow,它应该返回google.com/search?q = stack%20overflow的内容)。
错误发生在flask中,而不是我的代码。感谢@LukeWoodward指出这一点。
我的代码:
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)
错误:
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
小提示:我注解掉了错误处理以获得完整的回溯,并添加了“finally”块以避免其他错误。
1条答案
按热度按时间z5btuh9x1#
您的错误就在traceback中:
文件"/home/eesa/Code/proxyforblocking/www.example.com ",第30行,forward_packet字节(google_response. headers. items()). decode('utf8 ',errors ='ignore')]^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^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
requests Response对象在
Response.headers
处包含HTTP标头的字典,在代码中为google_response.headers
。在此字典上调用items()
将返回字典视图。您正在尝试将字典视图传递给bytes构造函数,但失败了。我不确定你在这里到底想做什么,但是如果你只是想返回
Response
对象提供的头,你可以将字典转换为字符串,或者你可以使用json
模块来创建字典头的JSON字符串表示。例如: