this is my http server:
from BaseHTTPServer import BaseHTTPRequestHandler,HTTPServer
class test:
def show(self):
return "aaaa"
class http_server:
def __init__(self, t1):
self.t1 = t1
server = HTTPServer(('', 8080), myHandler)
server.serve_forever()
class myHandler(BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(200)
self.send_header('Content-type','text/html')
self.end_headers()
self.wfile.write(self.t1.show()) #Doesnt work
return
class main:
def __init__(self):
self.t1 = test()
self.server = http_server(self.t1)
if __name__ == '__main__':
m = main()
I need to acces instance t1 inside of myHander.
Is there any way how to do it ?
Thanks!
there a way to do it is to set the property to the class :
from BaseHTTPServer import BaseHTTPRequestHandler,HTTPServer
class test:
def show(self):
return "aaaa"
class http_server:
def __init__(self, t1):
myHandler.t1 = t1
server = HTTPServer(('', 8080), myHandler)
server.serve_forever()
class myHandler(BaseHTTPRequestHandler):
t1 = None
def do_GET(self):
self.send_response(200)
self.send_header('Content-type','text/html')
self.end_headers()
self.wfile.write(self.t1.show()) #Doesnt work
return
class main:
def __init__(self):
self.t1 = test()
self.server = http_server(self.t1)
if __name__ == '__main__':
m = main()
You have to be careful that's every where you use myHandler that's will be the same instance of t1
Slightly better version, where t1 will not be the same for each instance.
from BaseHTTPServer import BaseHTTPRequestHandler,HTTPServer
class test:
def show(self):
return "aaaa"
class http_server:
def __init__(self, t1):
def handler(*args):
myHandler(t1, *args)
server = HTTPServer(('', 8080), handler)
server.serve_forever()
class myHandler(BaseHTTPRequestHandler):
def __init__(self, t1, *args):
self.t1 = t1
BaseHTTPRequestHandler.__init__(self, *args)
def do_GET(self):
self.send_response(200)
self.send_header('Content-type','text/html')
self.end_headers()
self.wfile.write(self.t1.show()) #Doesnt work
return
class main:
def __init__(self):
self.t1 = test()
self.server = http_server(self.t1)
if __name__ == '__main__':
m = main()
I know I'm answering pretty late, but that could probably be helpful for future viewers. There is a really easy way to access t1
like it was asked by using the server
variable of the BaseHTTPRequestHandler
object:
from BaseHTTPServer import BaseHTTPRequestHandler,HTTPServer
class test:
def show(self):
return "aaaa"
class http_server:
def __init__(self, t1):
server = HTTPServer(('', 8080), myHandler)
server.t1 = t1
server.serve_forever()
class myHandler(BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(200)
self.send_header('Content-type','text/html')
self.end_headers()
self.wfile.write(self.server.t1.show())
return
class main:
def __init__(self):
self.t1 = test()
self.server = http_server(self.t1)
if __name__ == '__main__':
m = main()
来源:https://stackoverflow.com/questions/18444395/basehttprequesthandler-with-custom-instance