[Fixed]-How to properly refactor this function into another file? django

1👍

Best practice is to use as simple parameters as possible (this makes your function easier to test).

What you’re looking for in the exception case is something that can be sent from auth_token through your view:

def auth_token(email):  # this returns a User not a token..?
    try:
        return User.objects.get(email=email)
    except User.DoesNotExist:
        raise ImmediateHttpResponse(JSONresponse({'status': False}))

Usage would then be:

def myview(request, ...):
    token = auth_token(data['email'])
    ...

Any ImmediateHttpResponse exception will escape the view and must be picked up by a middleware class.

Unfortunately, Django doesn’t come with an ImmediateHttpResponse class, but TastyPie has one that we can steal. First the exception class:

class ImmediateHttpResponse(Exception):
    """This exception is used to interrupt the flow of processing to immediately
       return a custom HttpResponse.

       Common uses include::

           * for authentication (like digest/OAuth)
           * for throttling

       (from TastyPie).
    """
    _response = http.HttpResponse("Nothing provided.")

    def __init__(self, response):
        self._response = response

    @property
    def response(self):
        return self._response

then the middleware:

from myexceptions import ImmediateHttpResponse

class ImmediateHttpResponseMiddleware(object):
    """Middleware that handles ImmediateHttpResponse exceptions, allowing 
       us to return a response from deep in form handling code.
    """
    def process_exception(self, request, exception):
        if isinstance(exception, ImmediateHttpResponse):
            return exception.response
        return None

This class must be added to your MIDDLEWARE_CLASSES in your settings.py file as 'mymiddleware.ImmediateHttpResponseMiddleware'.

Leave a comment