_cmd.py 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. import logging
  2. from pip._vendor import requests
  3. from pip._vendor.cachecontrol.adapter import CacheControlAdapter
  4. from pip._vendor.cachecontrol.cache import DictCache
  5. from pip._vendor.cachecontrol.controller import logger
  6. from argparse import ArgumentParser
  7. def setup_logging():
  8. logger.setLevel(logging.DEBUG)
  9. handler = logging.StreamHandler()
  10. logger.addHandler(handler)
  11. def get_session():
  12. adapter = CacheControlAdapter(
  13. DictCache(), cache_etags=True, serializer=None, heuristic=None
  14. )
  15. sess = requests.Session()
  16. sess.mount("http://", adapter)
  17. sess.mount("https://", adapter)
  18. sess.cache_controller = adapter.controller
  19. return sess
  20. def get_args():
  21. parser = ArgumentParser()
  22. parser.add_argument("url", help="The URL to try and cache")
  23. return parser.parse_args()
  24. def main(args=None):
  25. args = get_args()
  26. sess = get_session()
  27. # Make a request to get a response
  28. resp = sess.get(args.url)
  29. # Turn on logging
  30. setup_logging()
  31. # try setting the cache
  32. sess.cache_controller.cache_response(resp.request, resp.raw)
  33. # Now try to get it
  34. if sess.cache_controller.cached_request(resp.request):
  35. print("Cached!")
  36. else:
  37. print("Not cached :(")
  38. if __name__ == "__main__":
  39. main()