Miserlou / Zappa

Serverless Python
https://blog.zappa.io/
MIT License
11.89k stars 1.2k forks source link

Provider an easier way for users to add their own UWSGI Middleware #815

Open bxm156 opened 7 years ago

bxm156 commented 7 years ago

It would be nice if the handler could be refactored just a little to allow for easier UWSGI Middleware classes to be applied.

I'm trying to integrate 'Sentry' into my application, and I would like to be able to add the UWSGI Middleware https://docs.sentry.io/clients/python/integrations/django/#wsgi-middleware

Ideally, I would just subclass the existing Zappa Handler, to add my functionality, but the middleware is applied in the init method, which has a lot of logic.

I imagine some of the handler code could be refactored and to add a few methods, such as:

def _get_uwsgi_application(self)
...

def wrap_middleware(self, wsgi_app)
      return ZappaWSGIMiddleware(wsgi_app)

Then I would subclass wrap_middleware and add my middleware wrapper.

I could provide a branch that does this, if people seem open to the idea.

Miserlou commented 7 years ago

So Zappa speaks WSGI, I believe that if you do

(from the Sentry docs)

# yourproject/main.py
from raven.contrib.django.raven_compat.middleware.wsgi import Sentry
from django.core.wsgi import get_wsgi_application

application = Sentry(get_wsgi_application())

and then set app_function: yourproject.main.application - it should JustWork^tm. Right?

bxm156 commented 7 years ago

Oh hey, thats true! app_function doesn't seem to be very clear in the documentation. I will definitely try that.

On a side note however, that would apply the middleware like such: ZappaWGSIMiddleware(SentryMiddleware(wsgi_app))

I'm wondering if it would be more ideal for my case to have it wrapped as: SentryMiddleware(ZappaWSGIMiddleware(wsgi_app))

So that sentry can report any errors that occur in the ZappaWSGIMiddleware

Miserlou commented 7 years ago

Yes, I suppose that's true, but it's a fairly skinny middleware: https://github.com/Miserlou/Zappa/blob/master/zappa/middleware.py

+1 for making this clearer in the docs.

owenfi commented 6 years ago

If I follow the approach in @Miserlou post:

application = Sentry(get_wsgi_application())

I don't get the 404 capturing in Sentry.

If I try:

application = SentryMiddleware(get_wsgi_application())

I just get a failure to deploy and a not terribly decipherable error:

__call__() takes 2 positional arguments but 3 were given

Any pointers on how to use the Sentry 404 middleware would be much appreciated (I feel I've gotten the application / deploy / app_function settings roughly correct; but am not super confident as I'm not sure if main.py should sit in my project TLD, or next to my settings file?)