5

我希望我的网络应用程序的所有生产数据也能流经我的测试环境。本质上,我想将生产站点的每个 http 请求转发到测试站点(并且还要让生产站点为它服务!)。

有什么好方法可以做到这一点?我的网站是用 Django 构建的,由 mod_wsgi 提供服务。这最好在应用程序级别 (Django)、Web 服务器级别 (Apache) 还是 mod_wsgi 级别实现?

4

1 回答 1

7

我设法转发这样的请求

def view(request):
    # do what you planned to do here
    ...

    # processing headers
    def format_header_name(name):
        return "-".join([ x[0].upper()+x[1:] for x in name[5:].lower().split("_") ])
    headers = dict([ (format_header_name(k),v) for k,v in request.META.items() if k.startswith("HTTP_") ])
    headers["Cookie"] = "; ".join([ k+"="+v for k,v in request.COOKIES.items()])

    # this conversion is needed to avoid http://bugs.python.org/issue12398
    url = str(request.get_full_path())

    # forward the request to SERVER_DOMAIN
    conn = httplib.HTTPConnection("SERVER_DOMAIN")
    conn.request(
        request.method,
        url,
        request.raw_post_data,
        headers
    )
    response = conn.getresponse()

    # some error handling if needed
    if response.status != 200:
        ...

    # render web page as usual
    return render_to_response(...)

对于代码重用,考虑装饰器

于 2011-08-23T11:51:02.703 回答