是的你可以。我希望这个例子会有所帮助:
import SimpleHTTPServer
import SocketServer
class myServer(SimpleHTTPServer.SimpleHTTPRequestHandler):
def do_GET(self):
"""Serve a GET request."""
# do something here
self.finish(
"Hello world! Request path: " + self.path
)
def finish(self, value, status=200, ctype="text/html"):
try:
self.send_response(status)
self.send_header("Content-type", ctype)
self.send_header("Content-Length", str(len(value)))
self.end_headers()
self.wfile.write(str(value))
finally:
self.wfile.close()
httpd = SocketServer.TCPServer(("", 80), myServer)
httpd.serve_forever()
有关更多信息,请查看源代码SimpleHTTPRequestHandler
UPD: WebhookHandler代码可能是一个更好的例子
如果你想重用现有的实例,你可以做猴子补丁:
# wrapper for original do_GET
def patch(get_func):
def wrapper(self):
if self.path == '/test_url':
# do something
message = "Successful" # or not :(
self.send_response(200)
self.send_header("Content-type", 'text/plain')
self.send_header("Content-Length", str(len(message)))
self.end_headers()
self.wfile.write(message)
else:
return get_func(self)
return wrapper
# assume `server` is an instance of WebhookHandler
server.do_GET = patch(server.do_GET) # monkeypatching
UPD2:在仔细查看BaseServer的代码后,我发现它为每个请求启动了一个新的请求处理程序实例。这意味着修补实例不起作用,我们需要修补类本身。下面是它的工作原理:
# ... somewhere in the code far far away
from telegram.ext import Updater
from telegram.utils import webhookhandler as wh
# IMPORTANT: do it before making an instance of updater
# IMPORTANT #2: this is considered dirty hack. Don't repeat it at home!
if not wh.WebhookHandler._fuse:
# note we're patching handler class itself, not an instance
wh.WebhookHandler.do_GET = patch(wh.WebhookHandler.do_GET) # use patch() from above
wh.WebhookHandler._fuse = True
updater = Updater(token='TOKEN')