特定のポートで POST 要求を受け入れる単純な HTTP サーバーをインストールしました。
PythonがクラッシュしてHTTPサーバーが機能しなくなる特定のポイントまではすべて正常に機能します。サービスを手動で再起動して、サービスを元に戻す必要があります。次に、スクリプトがクラッシュする理由を理解するために、スクリプトへのログをさらに有効にしました。
私が信じている原因は、「ConnectionResetError: [Errno 104] Connection reset by peer」です。
私のpython v3.8.10コード:
from http.server import BaseHTTPRequestHandler, HTTPServer
import socketserver
import random
import requests
import datetime
import os
class S(BaseHTTPRequestHandler):
def do_POST(self):
try:
print(datetime.datetime.now(), flush=True)
xmac = self.headers.get('X-Mac')
useragent = self.headers.get('User-Agent')
xinfo = self.headers.get('X-Info')
# print("User-Agent: " + useragent)
# print("X-Info: " + xinfo)
self.data_string = self.rfile.read(int(self.headers['Content-Length'])).decode('UTF-8')
HTTP_URL = "MYURL.php"
data = {'data': self.data_string}
r = requests.post(url = HTTP_URL, data = data)
if r.text != '':
status = r.text.split('_')[0]
message = r.text.split('_')[1]
self.send_response(202)
self.end_headers()
print("X-Mac: " + xmac, flush=True)
print(self.data_string, flush=True)
print(r.text, flush=True)
print('', flush=True)
except Exception as e:
print(e, flush=True)
print('Error on post request', flush=True)
return
def run(server_class=HTTPServer, handler_class=S, port=80):
try:
httpd = server_class(('', MYPORT), handler_class)
print('Server start on port MYPORT..', flush=True)
httpd.serve_forever()
except KeyboardInterrupt:
print('^C received, shutting down server', flush=True)
httpd.shutdown()
except Exception as e:
print(e, flush=True)
print('Retrying restart server on port MYPORT..', flush=True)
time.sleep(5)
run()
try:
run()
except Exception as e:
print(e, flush=True)
print('run crashed, error on top', flush=True)
エラーログ:
Exception happened during processing of request from ('FROMIP', 34874)
Traceback (most recent call last):
File "/usr/lib/python3.8/socketserver.py", line 316, in _handle_request_noblock
self.process_request(request, client_address)
File "/usr/lib/python3.8/socketserver.py", line 347, in process_request
self.finish_request(request, client_address)
File "/usr/lib/python3.8/socketserver.py", line 360, in finish_request
self.RequestHandlerClass(request, client_address, self)
File "/usr/lib/python3.8/socketserver.py", line 747, in __init__
self.handle()
File "/usr/lib/python3.8/http/server.py", line 427, in handle
self.handle_one_request()
File "/usr/lib/python3.8/http/server.py", line 395, in handle_one_request
self.raw_requestline = self.rfile.readline(65537)
File "/usr/lib/python3.8/socket.py", line 669, in readinto
return self._sock.recv_into(b)
ConnectionResetError: [Errno 104] Connection reset by peer
どうすればこれを修正できますか? サーバー側のパラメーターを設定する必要がありますか?