I'm trying to make an HTTP Server from scratch and wanted to write the log in a text file so I created this function.
def do_LOG(self, addr, request):
path = 'log/logging.txt'
host = addr[0]
port = addr[1]
method = request[:4]
headers = request.split('\n')
filename = headers[0].split()[1]
f = open(path, "a ")
f.writelines('Server used: ' host '\n' 'Port used: ' port '\n' 'Method Served: ' method '\n' 'Filename: ' filename '\n\n')
f.close()
return
This function only creates a file but is not able to write in the file. I'm overriding this function from the parent class.This is the definition in the parent class.
def do_LOG(self, addr, request):
return
CodePudding user response:
Please Provide some more code
For better handling, add relative path of the directory by adding './' at the start.
Still I'm providing a temporary fix-
class Logs: def do_LOG(self, addr, request): path = './log/logging.txt' host = addr[0] port = addr[1] method = request[:4] headers = request.split('\n') filename = headers[0].split()[1] f = open(path, "a ") f.writelines('Server used: ' host '\n' 'Port used: ' port '\n' 'Method Served: ' method '\n' 'Filename: ' filename '\n\n') f.close() return Logs().do_LOG("<addr>", "<request>")
Hope this helps!
CodePudding user response:
First, be careful to use proper indentation (I suspect this is from copying your code).
Second, you chose the mode 'a ' which I don't know about. In order to write to a file, you should use the 'w' mode, I also recommend providing the encoding:
f = open(path, "w", encoding= "utf-8")
f.write('Server used: ' host '\nPort used: ' port '\n' 'Method Served: ' method '\n' 'Filename: ' filename '\n\n')
f.close()
If this does not work, maybe that's because there is a problem with the values of host
, port
or method
, you should then try to write the file with multiple calls, to see where the problem occurs:
f.write('Server used')
f.write(host)
...