from django.http import HttpRequest

import inspect

class RequestFetchingMixin(object):
    def __new__(cls, *args, **kwargs):
        obj = object.__new__(cls, *args, **kwargs)
        f = inspect.currentframe()
        requests = []
        request = None
        backup_count = 0
        while not requests and f.f_back is not None and backup_count < 5:
            f = f.f_back
            for var, val in f.f_locals.iteritems():
                if isinstance(val, HttpRequest):
                    requests.append((var, val))
            backup_count += 1
        if not requests:
            request = None
        elif len(requests) == 1:
            request = requests[0][1]
        else:
            for var, val in requests:
                if var == 'request':
                    request = val
            if request is None:
                request = requests[0][1]
        obj.request = request
        return obj