Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

230
Vistas
how to properly refactor this function into another file? django

I have a try and except which is used super often, so I am thinking of taking it out and make it into a function in other file but I cannot seem to make it work.

Can someone please give me a hand?

this is the code which I use really really often

    try:
        user = get_object_or_404(User, email=data['email'])
    except Exception as e:
        print(e)
        return JSONresponse(False, e.message)

I tried making it into another file and did it this way

def auth_token(data):
    try:
        return get_object_or_404(User, email=data['email'])
    except Exception as e:
        return JSONresponse({'status': False})

then when I call auth_token I did it this way in another way and of course I did import it

user = auth_token(data)

I can understand this would then return me JSONresponse({'status': False}) and I tried using raise and it would tell me that I can't use JSONresponse

Can someone give me an idea how this can be done?

over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

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'.

over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda