decorators.py 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. import warnings
  2. from functools import wraps
  3. from twisted.internet import defer, threads
  4. from scrapy.exceptions import ScrapyDeprecationWarning
  5. def deprecated(use_instead=None):
  6. """This is a decorator which can be used to mark functions
  7. as deprecated. It will result in a warning being emitted
  8. when the function is used."""
  9. def deco(func):
  10. @wraps(func)
  11. def wrapped(*args, **kwargs):
  12. message = "Call to deprecated function %s." % func.__name__
  13. if use_instead:
  14. message += " Use %s instead." % use_instead
  15. warnings.warn(message, category=ScrapyDeprecationWarning, stacklevel=2)
  16. return func(*args, **kwargs)
  17. return wrapped
  18. if callable(use_instead):
  19. deco = deco(use_instead)
  20. use_instead = None
  21. return deco
  22. def defers(func):
  23. """Decorator to make sure a function always returns a deferred"""
  24. @wraps(func)
  25. def wrapped(*a, **kw):
  26. return defer.maybeDeferred(func, *a, **kw)
  27. return wrapped
  28. def inthread(func):
  29. """Decorator to call a function in a thread and return a deferred with the
  30. result
  31. """
  32. @wraps(func)
  33. def wrapped(*a, **kw):
  34. return threads.deferToThread(func, *a, **kw)
  35. return wrapped