Skip to content

Instantly share code, notes, and snippets.

@dongweiming
Created August 15, 2019 12:32
Show Gist options
  • Save dongweiming/d1476a7b3d5997350ef19a64298a6c17 to your computer and use it in GitHub Desktop.
Save dongweiming/d1476a7b3d5997350ef19a64298a6c17 to your computer and use it in GitHub Desktop.
requests 中间件的写法
from requests import Session, Response
from requests.adapters import HTTPAdapter
class MiddlewareHTTPAdapter(HTTPAdapter):
def __init__(self, middlewares=None, *args, **kwargs):
self.middlewares = middlewares or []
super().__init__(*args, **kwargs)
def register(self, middleware):
self.middlewares.append(middleware)
def send(self, request, *args, **kwargs):
for middleware in self.middlewares:
middleware.before_send(request, **kwargs)
return super().send(request, *args, **kwargs)
def build_response(self, req, resp):
response = super().build_response(req, resp)
for middleware in reversed(self.middlewares):
response = middleware.after_build_response(req, resp, response)
return response
class LoggingMiddleware:
def before_send(self, request, *args, **kwargs):
print(f'URL: {request.url}')
def after_build_response(self, req, resp, response):
print(f'{response.url}: {response.status_code}')
return response
if __name__ == '__main__':
session = Session()
middlewares = [LoggingMiddleware()]
adapter = MiddlewareHTTPAdapter(middlewares)
session.mount('http://', adapter)
session.mount('https://', adapter)
session.get('https://www.douban.com')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment