如何让HTTPServer通过do_GET传回我自己的类?

时间:2017-02-16 21:38:15

标签: python python-2.7 python-3.x basehttpserver

我有一个特殊的数据库类实例,我希望将其传递到HTTPServer处理程序,以便我可以将其返回以供在do_GET和do_POST回调处理程序中使用。我尝试了子类化将我的数据库类作为附加参数添加到Handler中...但是这并没有将它一直放到我的HTTPServerRequestHandler类中。

我也尝试了什么不起作用:

即使我设法将参数添加到HTTPServerRequestHandler类,这只会产生错误,因为serve_forever仍将使用原始的4(self + 3)参数回调类,省略我的第5个(数据库)参数。

以前,我会将数据库类实例化为全局常量,但这似乎是一个坏主意。

这是我到目前为止所做的工作:

此代码成功提供了我的页面,但我无权访问任何数据库方法(包括我的日志处理程序,它是数据库实例的一部分):

def run_server(state_database, port):
    state_database.log.info('starting server.')
    server_address = ('', port)

    HandlerClass = MakeHandlerClassforDB(state_database)

    httpserver = HTTPServer(server_address, HandlerClass)
    state_database.log.info('Server loaded.')
    httpserver.serve_forever()


def MakeHandlerClassforDB(state_database):
    class CustomHandler(HTTPServerRequestHandler, object):
        def __init__(self, *args, **kwargs):
            self.database = state_database
            super(CustomHandler, self).__init__(*args, **kwargs)
    return CustomHandler


# HTTPRequestHandler class
# noinspection PyPep8Naming
class HTTPServerRequestHandler(BaseHTTPRequestHandler):
    def __init__(self, request, client_address, server):
        BaseHTTPRequestHandler.__init__(self, request, client_address, server)
        # would like to be able to get database into here as a self....
    def do_GET(self):
        ip = self.client_address[0].split(".")
        if ip[0] in self.page.blocked_ip_highs:
            # `self.database` does not resolve, so this does not work...
            self.database.log.info(
                "Ignored request from %s" % self.client_address)
            return
          ...

    def do_POST(self):
        time_start = time.time()
        # again, self.database does not exist in the callback
        self.database.log.debug(
            "Headers_________\n%s\n______________\n" % self.headers)

我也希望这适用于Python 3和Python 2(这就是我不使用super().__init__(...)的原因。)

1 个答案:

答案 0 :(得分:0)

这似乎有效:

#include "Vector2D.h"



Vector2D::Vector2D():
    _x(1.0f),
    _y(1.0f)
{

}


Vector2D::~Vector2D()
{

}

void Vector2D::SetX(float x)
{
    _x = x;
}

float Vector2D::GetX()
{
    return _x;
}


void Vector2D::SetY(float y)
{
    _y = y;
}

float Vector2D::GetY()
{
    return _y;
}


void Vector2D::SetAngleRad(float angle)
{
    float hypotenuse = GetMagnitude();

    SetX( cos(angle) * hypotenuse); // cos of angle = x / hypotenuse
                                    // so x = cos of angle * hypotenuse

    SetY( sin(angle) * hypotenuse); //sin of angle = y / hypotenuse
                                    // so y = sin of angle * hypotenuse
}

float Vector2D::GetAngleRad()
{
    float hypotenuse = GetMagnitude();
    return asin( _y / hypotenuse ); // if sin of angle A = y / hypotenuse
                                    // then asin of y / hypotenuse = angle
}


void Vector2D::SetMagnitude(float magnitude)
{
    float angle = GetAngleRad();
    float hypotenuse = GetMagnitude();

    SetX( (cos(angle) * hypotenuse) * magnitude ); // cos of angle = x / hypotenuse
                                                   // so cos of angle * hypotenuse = x
                                                   // multiplied by the new magnitude


    SetY( (sin(angle) * hypotenuse) * magnitude); //sin of angle = y / hypotenuse
                                                  // so sin of angle * hypotenuse = y
                                                  // multipied by the new magnitude
}

float Vector2D::GetMagnitude()
{
    return sqrt( (_x * _x) + (_y * _y) ); // a^2 + b^2 = c^2
                                          //so c = sqrt( a^2 + b^2 )
}

我可以将这些项重新添加到类HTTPServerRequestHandler def run_server(state_database, port): server_address = ('', port) handlerclass = makehandlerclassfordb(state_database) httpserver = HTTPServer(server_address, handlerclass) httpserver.serve_forever() def makehandlerclassfordb(state_database): class CustomHandler(HTTPServerRequestHandler, object): def __init__(self, *args, **kwargs): self.database = state_database self.page = HTMLPage() super(CustomHandler, self).__init__(*args, **kwargs) return CustomHandler class HTTPServerRequestHandler(BaseHTTPRequestHandler): def do_GET(self): self.database.log.debug( "Get Header_________%s______________" % self.headers) """both self.page and self.database DO resolve (although PyCharm does not think they should :P )""" ip = self.client_address[0].split(".") if ip[0] in self.page.blocked_ip_highs: self.database.log.info( "Ignored request from %s" % self.client_address) return ,但这不会改变功能,我认为没有理由让IDE错误消失。