def test_wrappedModule(self): """ Deprecating an attribute in a module replaces and wraps that module instance, in C{sys.modules}, with a L{twisted.python.deprecate._ModuleProxy} instance but only if it hasn't already been wrapped. """ sys.modules[self._testModuleName] = mod = types.ModuleType('foo') self.addCleanup(sys.modules.pop, self._testModuleName) setattr(mod, 'first', 1) setattr(mod, 'second', 2) deprecate.deprecatedModuleAttribute( Version('Twisted', 8, 0, 0), 'message', self._testModuleName, 'first') proxy = sys.modules[self._testModuleName] self.assertNotEqual(proxy, mod) deprecate.deprecatedModuleAttribute( Version('Twisted', 8, 0, 0), 'message', self._testModuleName, 'second') self.assertIs(proxy, sys.modules[self._testModuleName])
def test_not_catched_warning(self): buildbot_module = new.module('buildbot_module') buildbot_module.deprecated_attr = 1 with mock.patch.dict(sys.modules, {'buildbot_module': buildbot_module}): deprecatedModuleAttribute(Version("Buildbot", 0, 9, 0), "test message", "buildbot_module", "deprecated_attr") # Overwrite with Twisted's module wrapper. import buildbot_module warnings = self.flushWarnings([self.test_not_catched_warning]) self.assertEqual(len(warnings), 0) # Should produce warning buildbot_module.deprecated_attr warnings = self.flushWarnings([self.test_not_catched_warning]) self.assertEqual(len(warnings), 1) self.assertEqual(warnings[0]['category'], DeprecationWarning) self.assertIn("test message", warnings[0]['message'])
# Copyright (c) Twisted Matrix Laboratories. # See LICENSE for details. """ Twisted Persisted: utilities for managing persistence. """ from twisted.python import versions, deprecate deprecate.deprecatedModuleAttribute( versions.Version('twisted', 11, 0, 0), "Use a different persistence library. This one " "is no longer maintained.", __name__, 'journal')
def getPythonContainers(meth): """Walk up the Python tree from method 'meth', finding its class, its module and all containing packages.""" containers = [] containers.append(meth.im_class) moduleName = meth.im_class.__module__ while moduleName is not None: module = sys.modules.get(moduleName, None) if module is None: module = __import__(moduleName) containers.append(module) moduleName = getattr(module, '__module__', None) return containers deprecate.deprecatedModuleAttribute( versions.Version("Twisted", 12, 3, 0), "This function never worked correctly. Implement lookup on your own.", __name__, "getPythonContainers") def _runSequentially(callables, stopOnFirstError=False): """ Run the given callables one after the other. If a callable returns a Deferred, wait until it has finished before running the next callable. @param callables: An iterable of callables that take no parameters. @param stopOnFirstError: If True, then stop running callables as soon as one raises an exception or fires an errback. False by default. @return: A L{Deferred} that fires a list of C{(flag, value)} tuples. Each
The same channel will be re-used as long as it doesn't get closed. """ if self._channel and not self._channel.closed: # If the channel is already there and still opened, just return # it (the client will be still connected and working as well). return succeed(self._channel) pending = Deferred() self._pending_requests.append(pending) return pending QueueManager = DeprecatedQueueManager # For backward compatibility deprecatedModuleAttribute( Version("txlongpoll", 4, 0, 0), "Use txlongpoll.notification.NotificationSource instead.", __name__, "QueueManager") class FrontEndAjax(Resource): """ A web resource which, when rendered with a C{'uuid'} in the request arguments, will return the raw data from the message queue associated with that UUID. """ isLeaf = True def __init__(self, source): """ @param source: The NotificationSource to fetch notifications from.
""" func = cls.__dict__[name] if _PY3: return _MethodType(func, self) return _MethodType(func, self, cls) from incremental import Version from twisted.python.deprecate import deprecatedModuleAttribute from collections import OrderedDict deprecatedModuleAttribute( Version("Twisted", 15, 5, 0), "Use collections.OrderedDict instead.", "twisted.python.compat", "OrderedDict") if _PY3: from base64 import encodebytes as _b64encodebytes from base64 import decodebytes as _b64decodebytes else: from base64 import encodestring as _b64encodebytes from base64 import decodestring as _b64decodebytes def _bytesChr(i): """ Like L{chr} but always works on ASCII, returning L{bytes}.
__all__ = [ 'supportedMethods', 'Request', 'Session', 'Site', 'version', 'NOT_DONE_YET', 'GzipEncoderFactory' ] # backwards compatability deprecatedModuleAttribute( Version("Twisted", 12, 1, 0), "Please use twisted.web.http.datetimeToString instead", "twisted.web.server", "date_time_string") deprecatedModuleAttribute( Version("Twisted", 12, 1, 0), "Please use twisted.web.http.stringToDatetime instead", "twisted.web.server", "string_date_time") date_time_string = http.datetimeToString string_date_time = http.stringToDatetime # Support for other methods may be implemented on a per-resource basis. supportedMethods = ('GET', 'HEAD', 'POST') def _addressToTuple(addr):
# Import reflect first, so that circular imports (between deprecate and # reflect) don't cause headaches. import twisted.python.reflect from twisted.python.versions import Version from twisted.python.deprecate import deprecatedModuleAttribute # Known module-level attributes. DEPRECATED_ATTRIBUTE = 42 ANOTHER_ATTRIBUTE = 'hello' version = Version('Twisted', 8, 0, 0) message = 'Oh noes!' deprecatedModuleAttribute( version, message, __name__, 'DEPRECATED_ATTRIBUTE')
from twisted.python.deprecate import deprecatedModuleAttribute from twisted.python.versions import Version from twisted.application.internet import StreamServerEndpointService def parse(description, factory, default='tcp'): """ This function is deprecated as of Twisted 10.2. @see: L{twisted.internet.endpoints.server} """ return endpoints._parseServer(description, factory, default) deprecatedModuleAttribute( Version("Twisted", 10, 2, 0), "in favor of twisted.internet.endpoints.serverFromString", __name__, "parse") _DEFAULT = object() def service(description, factory, default=_DEFAULT, reactor=None): """ Return the service corresponding to a description. @param description: The description of the listening port, in the syntax described by L{twisted.internet.endpoints.server}. @type description: C{str} @param factory: The protocol factory which will build protocols for
# Copyright (c) Twisted Matrix Laboratories. # See LICENSE for details. """ Twisted's unit tests. """ from twisted.python.deprecate import deprecatedModuleAttribute from twisted.python.versions import Version from twisted.test import proto_helpers for obj in proto_helpers.__all__: deprecatedModuleAttribute( Version('Twisted', 19, 7, 0, release_candidate=1), 'Please use twisted.internet.testing.{} instead.'.format(obj), 'twisted.test.proto_helpers', obj)
if self.reverseVideo: attrs.append(insults.REVERSE_VIDEO) if self.foreground != WHITE: attrs.append(FOREGROUND + self.foreground) if self.background != BLACK: attrs.append(BACKGROUND + self.background) if attrs: return "\x1b[" + ";".join(map(str, attrs)) + "m" return "" CharacterAttribute = _FormattingState deprecatedModuleAttribute( Version("Twisted", 13, 1, 0), "Use twisted.conch.insults.text.assembleFormattedText instead.", "twisted.conch.insults.helper", "CharacterAttribute", ) # XXX - need to support scroll regions and scroll history @implementer(insults.ITerminalTransport) class TerminalBuffer(protocol.Protocol): """ An in-memory terminal emulator. """ for keyID in ( b"UP_ARROW", b"DOWN_ARROW", b"RIGHT_ARROW",
from twisted.python.deprecate import deprecated, deprecatedModuleAttribute if sys.version_info >= (3, 7, 0): _PY37PLUS = True else: _PY37PLUS = False if platform.python_implementation() == "PyPy": _PYPY = True else: _PYPY = False FileType = IOBase deprecatedModuleAttribute( Version("Twisted", 21, 2, 0), "Obsolete alias for io.IOBase", __name__, "FileType", ) frozenset = frozenset deprecatedModuleAttribute( Version("Twisted", 21, 2, 0), "Obsolete alias for frozenset builtin type", __name__, "frozenset", ) InstanceType = object deprecatedModuleAttribute( Version("Twisted", 21, 2, 0), "Old-style classes don't exist in Python 3",
_DEFAULT = object() def acquireAttribute(objects, attr, default=_DEFAULT): """Go through the list 'objects' sequentially until we find one which has attribute 'attr', then return the value of that attribute. If not found, return 'default' if set, otherwise, raise AttributeError. """ for obj in objects: if hasattr(obj, attr): return getattr(obj, attr) if default is not _DEFAULT: return default raise AttributeError('attribute %r not found in %r' % (attr, objects)) deprecate.deprecatedModuleAttribute( versions.Version("Twisted", 10, 1, 0), "Please use twisted.python.reflect.namedAny instead.", __name__, "findObject") def findObject(name): """Get a fully-named package, module, module-global object or attribute. Forked from twisted.python.reflect.namedAny. Returns a tuple of (bool, obj). If bool is True, the named object exists and is returned as obj. If bool is False, the named object does not exist and the value of obj is unspecified. """ names = name.split('.') topLevelPackage = None moduleNames = names[:]
# This file is part of Buildbot. Buildbot is free software: you can # redistribute it and/or modify it under the terms of the GNU General Public # License as published by the Free Software Foundation, version 2. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # FOR A PARTICULAR PURPOSE. See the GNU General Public License for more # details. # # You should have received a copy of the GNU General Public License along with # this program; if not, write to the Free Software Foundation, Inc., 51 # Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # # Copyright Buildbot Team Members from twisted.python.deprecate import deprecatedModuleAttribute from twisted.python.versions import Version from buildbot.buildslave.libvirt import (EC2LatentBuildSlave) deprecatedModuleAttribute(Version("Buildbot", 0, 8, 8), "It has been moved to buildbot.buildslave.ec2", "buildbot.libvirtbuildslave", "EC2LatentBuildSlave") _hush_pyflakes = [EC2LatentBuildSlave]
"""Walk up the Python tree from method 'meth', finding its class, its module and all containing packages.""" containers = [] containers.append(meth.im_class) moduleName = meth.im_class.__module__ while moduleName is not None: module = sys.modules.get(moduleName, None) if module is None: module = __import__(moduleName) containers.append(module) moduleName = getattr(module, '__module__', None) return containers deprecate.deprecatedModuleAttribute( versions.Version("Twisted", 12, 3, 0), "This function never worked correctly. Implement lookup on your own.", __name__, "getPythonContainers") deprecate.deprecatedModuleAttribute( versions.Version("Twisted", 10, 1, 0), "Please use twisted.python.reflect.namedAny instead.", __name__, "findObject") def findObject(name): """Get a fully-named package, module, module-global object or attribute. Forked from twisted.python.reflect.namedAny. Returns a tuple of (bool, obj). If bool is True, the named object exists and is returned as obj. If bool is False, the named object does not exist and the value of obj is unspecified.
attrs.append(insults.BLINK) if self.reverseVideo: attrs.append(insults.REVERSE_VIDEO) if self.foreground != WHITE: attrs.append(FOREGROUND + self.foreground) if self.background != BLACK: attrs.append(BACKGROUND + self.background) if attrs: return '\x1b[' + ';'.join(map(str, attrs)) + 'm' return '' CharacterAttribute = _FormattingState deprecatedModuleAttribute( Version('Twisted', 13, 1, 0), 'Use twisted.conch.insults.text.assembleFormattedText instead.', 'twisted.conch.insults.helper', 'CharacterAttribute') # XXX - need to support scroll regions and scroll history class TerminalBuffer(protocol.Protocol): """ An in-memory terminal emulator. """ implements(insults.ITerminalTransport) for keyID in ('UP_ARROW', 'DOWN_ARROW', 'RIGHT_ARROW', 'LEFT_ARROW', 'HOME', 'INSERT', 'DELETE', 'END', 'PGUP', 'PGDN', 'F1', 'F2', 'F3', 'F4', 'F5', 'F6', 'F7', 'F8', 'F9',
ERROR_INVALID_NAME = 123 ERROR_DIRECTORY = 267 O_BINARY = getattr(os, "O_BINARY", 0) class FakeWindowsError(OSError): """ Stand-in for sometimes-builtin exception on platforms for which it is missing. """ deprecatedModuleAttribute( Version("Twisted", 21, 2, 0), "Catch OSError and check presence of 'winerror' attribute.", "twisted.python.win32", "FakeWindowsError", ) try: WindowsError: OSError = WindowsError except NameError: WindowsError = FakeWindowsError deprecatedModuleAttribute( Version("Twisted", 21, 2, 0), "Catch OSError and check presence of 'winerror' attribute.", "twisted.python.win32", "WindowsError", )
# This file is part of Buildbot. Buildbot is free software: you can # redistribute it and/or modify it under the terms of the GNU General Public # License as published by the Free Software Foundation, version 2. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # FOR A PARTICULAR PURPOSE. See the GNU General Public License for more # details. # # You should have received a copy of the GNU General Public License along with # this program; if not, write to the Free Software Foundation, Inc., 51 # Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # # Copyright Buildbot Team Members from twisted.python.deprecate import deprecatedModuleAttribute from twisted.python.versions import Version from buildbot.buildslave.ec2 import EC2LatentBuildSlave deprecatedModuleAttribute(Version("Buildbot", 0, 8, 8), "It has been moved to buildbot.buildslave.ec2", "buildbot.ec2buildslave", "EC2LatentBuildSlave") _hush_pyflakes = [ EC2LatentBuildSlave, ]
# Try using the API that we need, which only works right with # zope.interface 3.6 (or 4.0 on Python 3) class IDummy(interface.Interface): pass @interface.implementer(IDummy) class Dummy(object): pass except TypeError: # It is installed but not compatible with this version of Python. raise ImportError(required + ".") _checkRequirements() # Ensure compat gets imported from twisted.python import compat # setup version from twisted._version import version __version__ = version.short() del compat # Deprecating lore. from twisted.python.versions import Version from twisted.python.deprecate import deprecatedModuleAttribute deprecatedModuleAttribute( Version("Twisted", 14, 0, 0), "Use Sphinx instead.", "twisted", "lore")
# Copyright (c) 2001-2011 Twisted Matrix Laboratories. # See LICENSE for details. """ Twisted Persisted: utilities for managing persistence. """ from twisted.python import versions, deprecate deprecate.deprecatedModuleAttribute( versions.Version("twisted", 11, 0, 0), "Use a different persistence library. This one " "is no longer maintained.", __name__, "journal", )
timeout = 0.1 # See comment for identical line in GtkReactor.simulate. self._simtag = gtk.timeout_add((timeout * 1010), self.simulate) def install(): """Configure the twisted mainloop to be run inside the gtk mainloop. """ reactor = GtkReactor() from twisted.internet.main import installReactor installReactor(reactor) return reactor deprecate.deprecatedModuleAttribute(deprecatedSince, deprecationMessage, __name__, "install") def portableInstall(): """Configure the twisted mainloop to be run inside the gtk mainloop. """ reactor = PortableGtkReactor() from twisted.internet.main import installReactor installReactor(reactor) return reactor deprecate.deprecatedModuleAttribute(deprecatedSince, deprecationMessage, __name__, "portableInstall") if runtime.platform.getType() != 'posix':
# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # # Copyright Buildbot Team Members from buildbot.steps.source.base import Source from buildbot.steps.source.oldsource import BK from buildbot.steps.source.oldsource import Bzr from buildbot.steps.source.oldsource import CVS from buildbot.steps.source.oldsource import Darcs from buildbot.steps.source.oldsource import Git from buildbot.steps.source.oldsource import Mercurial from buildbot.steps.source.oldsource import Monotone from buildbot.steps.source.oldsource import P4 from buildbot.steps.source.oldsource import Repo from buildbot.steps.source.oldsource import SVN from twisted.python.deprecate import deprecatedModuleAttribute from twisted.python.versions import Version warningString = "The slave-side %s step is deprecated and will be removed in a future version. Please switch to the corresponding master-side step." oldClasses = ["CVS", "SVN", "Git", "Darcs", "Repo", "Bzr", "Mercurial", "P4", "Monotone", "BK"] for oldClass in oldClasses: deprecatedModuleAttribute(Version("Buildbot", 0, 8, 9), warningString % (oldClass), "buildbot.steps.source", oldClass) _hush_pyflakes = [Source, CVS, SVN, Git, Darcs, Repo, Bzr, Mercurial, P4, Monotone, BK]
# Copyright (c) Twisted Matrix Laboratories. # See LICENSE for details. """ Twisted Runner: Run and monitor processes. """ from twisted.python.versions import Version from twisted.python.deprecate import deprecatedModuleAttribute from twisted._version import version __version__ = version.short() deprecatedModuleAttribute( Version("Twisted", 16, 0, 0), "Use twisted.__version__ instead.", "twisted.runner", "__version__")
# Copyright (c) Twisted Matrix Laboratories. # See LICENSE for details. import stringprep from encodings import idna # We require Unicode version 3.2. from unicodedata import ucd_3_2_0 as unicodedata from twisted.python.versions import Version from twisted.python.deprecate import deprecatedModuleAttribute from zope.interface import Interface, implementer crippled = False deprecatedModuleAttribute(Version("Twisted", 13, 1, 0), "crippled is always False", __name__, "crippled") class ILookupTable(Interface): """ Interface for character lookup classes. """ def lookup(c): """ Return whether character is in this table. """ class IMappingTable(Interface): """ Interface for character mapping classes.
def areDone(self, avatarId): """ Override to determine if the authentication is finished for a given avatarId. @param avatarId: the avatar returned by the first checker. For this checker to function correctly, all the checkers must return the same avatar ID. """ return True deprecatedModuleAttribute( Version("Twisted", 15, 0, 0), ("Please use twisted.conch.checkers.SSHPublicKeyChecker, " "initialized with an instance of " "twisted.conch.checkers.UNIXAuthorizedKeysFiles instead."), __name__, "SSHPublicKeyDatabase") class IAuthorizedKeysDB(Interface): """ An object that provides valid authorized ssh keys mapped to usernames. @since: 15.0 """ def getAuthorizedKeys(avatarId): """ Gets an iterable of authorized keys that are valid for the given C{avatarId}.
if len(property_changes) > 1: self.descriptionDone = '{} properties set'.format( len(property_changes)) elif len(property_changes) == 1: self.descriptionDone = 'property \'{}\' set'.format( list(property_changes)[0]) if cmd.didFail(): return FAILURE return SUCCESS SetPropertyFromCommandNewStyle = SetPropertyFromCommand deprecatedModuleAttribute( Version("buildbot", 3, 0, 0), message= "Use SetPropertyFromCommand instead. This step will be removed in Buildbot 3.2.", moduleName="buildbot.steps.shell", name="SetPropertyFromCommandNewStyle", ) SetProperty = SetPropertyFromCommand deprecatedModuleAttribute(Version("Buildbot", 0, 8, 8), "It has been renamed to SetPropertyFromCommand", "buildbot.steps.shell", "SetProperty") class ShellCommand(buildstep.ShellMixin, buildstep.BuildStep): name = 'shell' def __init__(self, **kwargs):
# exceptions that can be raised while trying to start a build class BuilderInUseError(Exception): pass class WorkerSetupError(Exception): pass WorkerTooOldError = WorkerSetupError deprecatedModuleAttribute( Version("buildbot", 2, 9, 0), message="Use WorkerSetupError instead.", moduleName="buildbot.interfaces", name="WorkerTooOldError", ) class LatentWorkerFailedToSubstantiate(Exception): pass class LatentWorkerCannotSubstantiate(Exception): pass class LatentWorkerSubstantiatiationCancelled(Exception): pass
def loadFromItem(model, item): """ Initialise model parameters from an Axiom item instance. @type model: L{Model} @type item: L{axiom.item.Item} """ for name, param in model.params.iteritems(): param.value = getattr(item, name) ValueParameter = Value deprecatedModuleAttribute(Version('methanal', 0, 2, 0), 'use methanal.model.Value instead', __name__, 'ValueParameter') ListParameter = List deprecatedModuleAttribute(Version('methanal', 0, 2, 0), 'use methanal.model.List instead', __name__, 'ListParameter') EnumerationParameter = Enum deprecatedModuleAttribute(Version('methanal', 0, 2, 0), 'use methanal.model.Enum instead', __name__, 'EnumerationParameter') DecimalParameter = DecimalValue deprecatedModuleAttribute(Version('methanal', 0, 2, 0), 'use methanal.model.DecimalValue instead', __name__,
def get_path(self): return self.get_encoded_path() def get_url(self): return self.get_encoded_url() # Backwards compatibility layer. For deprecation. def URLContext(service_endpoint, bucket=None, object_name=None): args = (service_endpoint,) for s in (bucket, object_name): if s is not None: args += (s.decode("utf-8"),) return s3_url_context(*args) deprecatedModuleAttribute( Version("txAWS", 0, 3, 0), "See txaws.s3.client.query", __name__, "Query", ) deprecatedModuleAttribute( Version("txAWS", 0, 3, 0), "See txaws.s3.client.s3_url_context", __name__, "URLContext", )
attrs.append(insults.BLINK) if self.reverseVideo: attrs.append(insults.REVERSE_VIDEO) if self.foreground != WHITE: attrs.append(FOREGROUND + self.foreground) if self.background != BLACK: attrs.append(BACKGROUND + self.background) if attrs: return '\x1b[' + ';'.join(map(str, attrs)) + 'm' return '' CharacterAttribute = _FormattingState deprecatedModuleAttribute( Version('Twisted', 13, 1, 0), 'Use twisted.conch.insults.text.assembleFormattedText instead.', 'twisted.conch.insults.helper', 'CharacterAttribute') # XXX - need to support scroll regions and scroll history @implementer(insults.ITerminalTransport) class TerminalBuffer(protocol.Protocol): """ An in-memory terminal emulator. """ for keyID in ('UP_ARROW', 'DOWN_ARROW', 'RIGHT_ARROW', 'LEFT_ARROW', 'HOME', 'INSERT', 'DELETE', 'END', 'PGUP', 'PGDN', 'F1', 'F2', 'F3', 'F4', 'F5', 'F6', 'F7', 'F8', 'F9', 'F10', 'F11', 'F12'): exec('%s = object()' % (keyID, ))
from twisted.python.versions import Version from twisted.python.compat import _PY3 from twisted.application.internet import StreamServerEndpointService def parse(description, factory, default='tcp'): """ This function is deprecated as of Twisted 10.2. @see: L{twisted.internet.endpoints.server} """ return endpoints._parseServer(description, factory, default) deprecatedModuleAttribute( Version("Twisted", 10, 2, 0), "in favor of twisted.internet.endpoints.serverFromString", __name__, "parse") _DEFAULT = object() def service(description, factory, default=_DEFAULT, reactor=None): """ Return the service corresponding to a description. @param description: The description of the listening port, in the syntax described by L{twisted.internet.endpoints.server}. @type description: C{str}
""" Emitted when L{IReactorProcess.spawnProcess} is called in a way which may result in termination of the created child process not being reported. Deprecated in Twisted 10.0. """ MESSAGE = ("spawnProcess called, but the SIGCHLD handler is not " "installed. This probably means you have not yet " "called reactor.run, or called " "reactor.run(installSignalHandler=0). You will probably " "never see this process finish, and it may become a " "zombie process.") deprecate.deprecatedModuleAttribute( Version("Twisted", 10, 0, 0), "There is no longer any potential for zombie process.", __name__, "PotentialZombieWarning") class ProcessDone(ConnectionDone): """A process has ended without apparent errors""" def __init__(self, status): Exception.__init__(self, "process finished with exit code 0") self.exitCode = 0 self.signal = None self.status = status class ProcessTerminated(ConnectionLost): """A process has ended with a probable error condition""" def __init__(self, exitCode=None, signal=None, status=None):
import types for tran in 'TCP UNIX SSL UDP UNIXDatagram Multicast'.split(): for side in 'Server Client'.split(): if tran == "Multicast" and side == "Client": continue base = globals()['_Abstract'+side] doc = _doc[side] % vars() klass = types.ClassType(tran+side, (base,), {'method': tran, '__doc__': doc}) globals()[tran+side] = klass deprecatedModuleAttribute( Version("Twisted", 13, 1, 0), "It relies upon IReactorUDP.connectUDP " "which was removed in Twisted 10. " "Use twisted.application.internet.UDPServer instead.", "twisted.application.internet", "UDPClient") class TimerService(_VolatileDataService): """ Service to periodically call a function Every C{step} seconds call the given function with the given arguments. The service starts the calls when it starts, and cancels them when it stops. @ivar clock: Source of time. This defaults to L{None} which is causes L{twisted.internet.reactor} to be used.
__all__ = [ 'supportedMethods', 'Request', 'Session', 'Site', 'version', 'NOT_DONE_YET', 'GzipEncoderFactory' ] # backwards compatibility deprecatedModuleAttribute( Version("Twisted", 12, 1, 0), "Please use twisted.web.http.datetimeToString instead", "twisted.web.server", "date_time_string") deprecatedModuleAttribute( Version("Twisted", 12, 1, 0), "Please use twisted.web.http.stringToDatetime instead", "twisted.web.server", "string_date_time") date_time_string = http.datetimeToString string_date_time = http.stringToDatetime # Support for other methods may be implemented on a per-resource basis. supportedMethods = ('GET', 'HEAD', 'POST') def _addressToTuple(addr):
Emitted when L{IReactorProcess.spawnProcess} is called in a way which may result in termination of the created child process not being reported. Deprecated in Twisted 10.0. """ MESSAGE = ( "spawnProcess called, but the SIGCHLD handler is not " "installed. This probably means you have not yet " "called reactor.run, or called " "reactor.run(installSignalHandler=0). You will probably " "never see this process finish, and it may become a " "zombie process.") deprecate.deprecatedModuleAttribute( Version("Twisted", 10, 0, 0), "There is no longer any potential for zombie process.", __name__, "PotentialZombieWarning") class ProcessDone(ConnectionDone): """A process has ended without apparent errors""" def __init__(self, status): Exception.__init__(self, "process finished with exit code 0") self.exitCode = 0 self.signal = None self.status = status
def areDone(self, avatarId): """ Override to determine if the authentication is finished for a given avatarId. @param avatarId: the avatar returned by the first checker. For this checker to function correctly, all the checkers must return the same avatar ID. """ return True deprecatedModuleAttribute( Version("Twisted", 15, 0, 0), ("Please use twisted.conch.checkers.SSHPublicKeyChecker, " "initialized with an instance of " "twisted.conch.checkers.UNIXAuthorizedKeysFiles instead."), __name__, "SSHPublicKeyDatabase") class IAuthorizedKeysDB(Interface): """ An object that provides valid authorized ssh keys mapped to usernames. @since: 15.0.0 """ def getAuthorizedKeys(avatarId): """ Gets an iterable of authorized keys that are valid for the given C{avatarId}.
import stringprep from encodings import idna # We require Unicode version 3.2. from unicodedata import ucd_3_2_0 as unicodedata from twisted.python.versions import Version from twisted.python.deprecate import deprecatedModuleAttribute from zope.interface import Interface, implementer crippled = False deprecatedModuleAttribute( Version("Twisted", 13, 1, 0), "crippled is always False", __name__, "crippled") class ILookupTable(Interface): """ Interface for character lookup classes. """ def lookup(c): """ Return whether character is in this table. """
if isinstance(x, text_type): x = x.encode(encoding, errors) return x def bytes2unicode(x, encoding='utf-8', errors='strict'): if isinstance(x, (text_type, type(None))): return x return text_type(x, encoding, errors) _hush_pyflakes = [json] deprecatedModuleAttribute( Version("buildbot", 0, 9, 4), message="Use json from the standard library instead.", moduleName="buildbot.util", name="json", ) def toJson(obj): if isinstance(obj, datetime.datetime): return datetime2epoch(obj) # changes and schedulers consider None to be a legitimate name for a branch, # which makes default function keyword arguments hard to handle. This value # is always false. class NotABranch:
# Copyright (c) Twisted Matrix Laboratories. # See LICENSE for details. """ Chat protocols. """ from twisted.python import deprecate, versions deprecate.deprecatedModuleAttribute( versions.Version("Twisted", 15, 1, 0), "MSN has shutdown.", __name__, "msn")
return SUCCESS def interrupt(self, reason): try: self.process.signalProcess(self.interruptSignal) except KeyError: # Process not started yet pass except error.ProcessExitedAlready: pass super().interrupt(reason) MasterShellCommandNewStyle = MasterShellCommand deprecatedModuleAttribute( Version("buildbot", 3, 0, 0), message="Use MasterShellCommand instead. This step will be removed in Buildbot 3.2.", moduleName="buildbot.steps.master", name="MasterShellCommandNewStyle", ) class SetProperty(BuildStep): name = 'SetProperty' description = ['Setting'] descriptionDone = ['Set'] renderables = ['property', 'value'] def __init__(self, property, value, **kwargs): super().__init__(**kwargs) self.property = property self.value = value
reference_atom = 'reference' # r # mutable collections dictionary_atom = "dictionary" # d list_atom = 'list' # l set_atom = 'set' # immutable collections # (assignment to __dict__ and __class__ still might go away!) tuple_atom = "tuple" # t instance_atom = 'instance' # i frozenset_atom = 'frozenset' deprecatedModuleAttribute( Version("Twisted", 15, 0, 0), "instance_atom is unused within Twisted.", "twisted.spread.jelly", "instance_atom") # errors unpersistable_atom = "unpersistable"# u unjellyableRegistry = {} unjellyableFactoryRegistry = {} _NO_STATE = object() def _newInstance(cls, state=_NO_STATE): """ Make a new instance of a class without calling its __init__ method. Supports both new- and old-style classes. @param state: A C{dict} used to update C{inst.__dict__} or C{_NO_STATE}
# -*- test-case-name: twisted.conch.test -*- # Copyright (c) Twisted Matrix Laboratories. # See LICENSE for details. """ Twisted Conch: The Twisted Shell. Terminal emulation, SSHv2 and telnet. """ from incremental import Version from twisted.python.deprecate import deprecatedModuleAttribute from twisted._version import __version__ as version __version__ = version.short() deprecatedModuleAttribute(Version("Twisted", 16, 0, 0), "Use twisted.__version__ instead.", "twisted.conch", "__version__")
from xml.dom import minidom as dom import parser import urlparse import os.path from twisted.lore import tree, process from twisted.web import domhelpers from twisted.python import reflect from twisted.python.versions import Version from twisted.python.deprecate import deprecatedModuleAttribute parserErrors = (SyntaxError,) deprecatedModuleAttribute( Version("Twisted", 13, 1, 0), "parserErrors is deprecated", __name__, "parserErrors") class TagChecker: def check(self, dom, filename): self.hadErrors = 0 for method in reflect.prefixedMethods(self, 'check_'): method(dom, filename) if self.hadErrors: raise process.ProcessingFailure("invalid format") def _reportError(self, filename, element, error): hlint = element.hasAttribute('hlint') and element.getAttribute('hlint')
# -*- test-case-name: twisted.web.test -*- # Copyright (c) Twisted Matrix Laboratories. # See LICENSE for details. """ Twisted Web: a L{web server<twisted.web.server>} (including an L{HTTP implementation<twisted.web.http>} and a L{resource model<twisted.web.resource>}) and a L{web client<twisted.web.client>}. """ from twisted.web._version import version from twisted.python.versions import Version from twisted.python.deprecate import deprecatedModuleAttribute __version__ = version.short() deprecatedModuleAttribute( Version('Twisted', 11, 1, 0), "Google module is deprecated. Use Google's API instead", __name__, "google")
self.__dict__.clear() self.__dict__.update(v) else: self.__dict__[k]=v def reallyDel(self, k): """ *actually* del self.k without incurring side-effects. This is a hook to be overridden by subclasses. """ del self.__dict__[k] # just in case OriginalAccessor = Accessor deprecatedModuleAttribute( Version("Twisted", 12, 1, 0), "OriginalAccessor is a reference to class twisted.python.reflect.Accessor " "which is deprecated.", "twisted.python.reflect", "OriginalAccessor") class Summer(Accessor): """ Extend from this class to get the capability to maintain 'related sums'. Have a tuple in your class like the following:: sums=(('amount','credit','credit_total'), ('amount','debit','debit_total')) and the 'credit_total' member of the 'credit' member of self will always be incremented when the 'amount' member of self is incremented, similiarly for the debit versions. """
persistent_atom = b'persistent' # p reference_atom = b'reference' # r # mutable collections dictionary_atom = b"dictionary" # d list_atom = b'list' # l set_atom = b'set' # immutable collections # (assignment to __dict__ and __class__ still might go away!) tuple_atom = b"tuple" # t instance_atom = b'instance' # i frozenset_atom = b'frozenset' deprecatedModuleAttribute(Version("Twisted", 15, 0, 0), "instance_atom is unused within Twisted.", "twisted.spread.jelly", "instance_atom") # errors unpersistable_atom = b"unpersistable" # u unjellyableRegistry = {} unjellyableFactoryRegistry = {} def _createBlank(cls): """ Given an object, if that object is a type (or a legacy old-style class), return a new, blank instance of that type which has not had C{__init__} called on it. If the object is not a type, return C{None}. @param cls: The type (or class) to create an instance of.
import ipaddr import re from twisted.python import deprecate from twisted.python.versions import Version PORTSPEC_LENGTH = 16 re_ipv6 = re.compile("\[([a-fA-F0-9:]+)\]:(.*$)") re_ipv4 = re.compile("((?:\d{1,3}\.?){4}):(.*$)") deprecate.deprecatedModuleAttribute( Version('bridgedb', 0, 0, 1), "Removed due to 'bridgedb.Bridges.PortList' being moved to "\ "'bridgedb.parse.addr.PortList.", "bridgedb.Bridges", "PORTSPEC_LENGTH") deprecate.deprecatedModuleAttribute( Version('bridgedb', 0, 0, 1), "Attribute 'bridgedb.Bridges.re_ipv4' was removed due to "\ "'bridgedb.Bridges.parseORAddressLine' moving to "\ "'bridgedb.parse.networkstatus.", "bridgedb.Bridges", "re_ipv4") deprecate.deprecatedModuleAttribute( Version('bridgedb', 0, 0, 1), "Attribute 'bridgedb.Bridges.re_ipv6' was removed due to "\ "'bridgedb.Bridges.parseORAddressLine' moving to "\
@see: L{twisted.conch.insults.text.attributes} @author: Jp Calderone """ from twisted.conch.insults import helper, insults from twisted.python import _textattributes from twisted.python.deprecate import deprecatedModuleAttribute from twisted.python.versions import Version flatten = _textattributes.flatten deprecatedModuleAttribute( Version('Twisted', 13, 1, 0), 'Use twisted.conch.insults.text.assembleFormattedText instead.', 'twisted.conch.insults.text', 'flatten') _TEXT_COLORS = { 'black': helper.BLACK, 'red': helper.RED, 'green': helper.GREEN, 'yellow': helper.YELLOW, 'blue': helper.BLUE, 'magenta': helper.MAGENTA, 'cyan': helper.CYAN, 'white': helper.WHITE}
class GtkReactor(posixbase.PosixReactorBase): """ GTK+ event loop reactor. @ivar _reads: A dictionary mapping L{FileDescriptor} instances to gtk INPUT_READ watch handles. @ivar _writes: A dictionary mapping L{FileDescriptor} instances to gtk INTPUT_WRITE watch handles. @ivar _simtag: A gtk timeout handle for the next L{simulate} call. """ implements(IReactorFDSet) deprecate.deprecatedModuleAttribute(deprecatedSince, deprecationMessage, __name__, "GtkReactor") def __init__(self): """ Initialize the file descriptor tracking dictionaries and the base class. """ self._simtag = None self._reads = {} self._writes = {} posixbase.PosixReactorBase.__init__(self) def addReader(self, reader): if reader not in self._reads: self._reads[reader] = gtk.input_add(reader, gtk.GDK.INPUT_READ, self.callback) def addWriter(self, writer): if writer not in self._writes: self._writes[writer] = gtk.input_add(writer, gtk.GDK.INPUT_WRITE, self.callback) def getReaders(self): return self._reads.keys() def getWriters(self): return self._writes.keys() def removeAll(self): return self._removeAll(self._reads, self._writes) def removeReader(self, reader): if reader in self._reads: gtk.input_remove(self._reads[reader]) del self._reads[reader] def removeWriter(self, writer): if writer in self._writes: gtk.input_remove(self._writes[writer]) del self._writes[writer] doIterationTimer = None def doIterationTimeout(self, *args): self.doIterationTimer = None return 0 # auto-remove def doIteration(self, delay): # flush some pending events, return if there was something to do # don't use the usual "while gtk.events_pending(): mainiteration()" # idiom because lots of IO (in particular test_tcp's # ProperlyCloseFilesTestCase) can keep us from ever exiting. log.msg(channel='system', event='iteration', reactor=self) if gtk.events_pending(): gtk.mainiteration(0) return # nothing to do, must delay if delay == 0: return # shouldn't delay, so just return self.doIterationTimer = gtk.timeout_add(int(delay * 1000), self.doIterationTimeout) # This will either wake up from IO or from a timeout. gtk.mainiteration(1) # block # note: with the .simulate timer below, delays > 0.1 will always be # woken up by the .simulate timer if self.doIterationTimer: # if woken by IO, need to cancel the timer gtk.timeout_remove(self.doIterationTimer) self.doIterationTimer = None def crash(self): posixbase.PosixReactorBase.crash(self) gtk.mainquit() def run(self, installSignalHandlers=1): self.startRunning(installSignalHandlers=installSignalHandlers) gtk.timeout_add(0, self.simulate) gtk.mainloop() def _readAndWrite(self, source, condition): # note: gtk-1.2's gtk_input_add presents an API in terms of gdk # constants like INPUT_READ and INPUT_WRITE. Internally, it will add # POLL_HUP and POLL_ERR to the poll() events, but if they happen it # will turn them back into INPUT_READ and INPUT_WRITE. gdkevents.c # maps IN/HUP/ERR to INPUT_READ, and OUT/ERR to INPUT_WRITE. This # means there is no immediate way to detect a disconnected socket. # The g_io_add_watch() API is more suited to this task. I don't think # pygtk exposes it, though. why = None didRead = None try: if condition & gtk.GDK.INPUT_READ: why = source.doRead() didRead = source.doRead if not why and condition & gtk.GDK.INPUT_WRITE: # if doRead caused connectionLost, don't call doWrite # if doRead is doWrite, don't call it again. if not source.disconnected and source.doWrite != didRead: why = source.doWrite() didRead = source.doWrite # if failed it was in write except: why = sys.exc_info()[1] log.msg('Error In %s' % source) log.deferr() if why: self._disconnectSelectable(source, why, didRead == source.doRead) def callback(self, source, condition): log.callWithLogger(source, self._readAndWrite, source, condition) self.simulate() # fire Twisted timers return 1 # 1=don't auto-remove the source def simulate(self): """Run simulation loops and reschedule callbacks. """ if self._simtag is not None: gtk.timeout_remove(self._simtag) self.runUntilCurrent() timeout = min(self.timeout(), 0.1) if timeout is None: timeout = 0.1 # Quoth someone other than me, "grumble", yet I know not why. Try to be # more specific in your complaints, guys. -exarkun self._simtag = gtk.timeout_add(int(timeout * 1010), self.simulate)
# Copyright (c) Twisted Matrix Laboratories. # See LICENSE for details. """ Subpackage containing the modules that implement the command line tools. Note that these are imported by top-level scripts which are intended to be invoked directly from a shell. """ from twisted.python.versions import Version from twisted.python.deprecate import deprecatedModuleAttribute deprecatedModuleAttribute( Version("Twisted", 11, 1, 0), "Seek unzipping software outside of Twisted.", __name__, "tkunzip") del Version, deprecatedModuleAttribute
] self.addCompleteLog('property changes', "\n".join(props_set)) def describe(self, done=False): if len(self.property_changes) > 1: return ["%d properties set" % len(self.property_changes)] elif len(self.property_changes) == 1: return ["property '%s' set" % list(self.property_changes)[0]] else: # let ShellCommand describe return ShellCommand.describe(self, done) SetProperty = SetPropertyFromCommand deprecatedModuleAttribute(Version("Buildbot", 0, 8, 8), "It has been renamed to SetPropertyFromCommand", "buildbot.steps.shell", "SetProperty") class Configure(ShellCommand): name = "configure" haltOnFailure = 1 flunkOnFailure = 1 description = ["configuring"] descriptionDone = ["configure"] command = ["./configure"] class WarningCountingShellCommand(ShellCommand, CompositeStepMixin): renderables = ['suppressionFile']
for k,v in self.property_changes.items() ] self.addCompleteLog('property changes', "\n".join(props_set)) def getText(self, cmd, results): if len(self.property_changes) > 1: return [ "%d properties set" % len(self.property_changes) ] elif len(self.property_changes) == 1: return [ "property '%s' set" % self.property_changes.keys()[0] ] else: # let ShellCommand describe return ShellCommand.getText(self, cmd, results) SetProperty = SetPropertyFromCommand deprecatedModuleAttribute(Version("Buildbot", 0, 8, 8), "It has been renamed to SetPropertyFromCommand", "buildbot.steps.shell", "SetProperty") class Configure(ShellCommand): name = "configure" haltOnFailure = 1 flunkOnFailure = 1 description = ["configuring"] descriptionDone = ["configure"] command = ["./configure"] class StringFileWriter(pb.Referenceable): """ FileWriter class that just puts received data into a buffer.
@return: a bound method @rtype: L{types.MethodType} """ func = cls.__dict__[name] if _PY3: return _MethodType(func, self) return _MethodType(func, self, cls) from twisted.python.versions import Version from twisted.python.deprecate import deprecatedModuleAttribute from collections import OrderedDict deprecatedModuleAttribute(Version("Twisted", 15, 5, 0), "Use collections.OrderedDict instead.", "twisted.python.compat", "OrderedDict") if _PY3: from base64 import encodebytes as _b64encodebytes from base64 import decodebytes as _b64decodebytes else: from base64 import encodestring as _b64encodebytes from base64 import decodestring as _b64decodebytes def _bytesChr(i): """ Like L{chr} but always works on ASCII, returning L{bytes}. @param i: The ASCII code point to return.
import math from zope.interface import implements # Twisted imports from twisted.internet import protocol, defer, interfaces, error from twisted.python import log, deprecate, versions LENGTH, DATA, COMMA = range(3) NUMBER = re.compile('(\d*)(:?)') deprecatedSince = versions.Version("Twisted", 10, 2, 0) message = "NetstringReceiver parser state is private." for attr in ["LENGTH", "DATA", "COMMA", "NUMBER"]: deprecate.deprecatedModuleAttribute( deprecatedSince, message, __name__, attr) del deprecatedSince, message, attr DEBUG = 0 class NetstringParseError(ValueError): """ The incoming data is not in valid Netstring format. """ class IncompleteNetstring(Exception): """ Not enough data to complete a netstring. """
s = s + '\n' return s def isMultiline(s): """Returns True if this string has a newline in it.""" return (string.find(s, '\n') != -1) def endsInNewline(s): """Returns True if this string ends in a newline.""" return (s[-len('\n'):] == '\n') deprecate.deprecatedModuleAttribute( versions.Version("Twisted", 10, 2, 0), "Please use inspect.getdoc instead.", __name__, "docstringLStrip") def docstringLStrip(docstring): """ Gets rid of unsightly lefthand docstring whitespace residue. You'd think someone would have done this already, but apparently not in 1.5.2. BUT since we're all using Python 2.1 now, use L{inspect.getdoc} instead. I{This function should go away soon.} """
# Copyright (c) Twisted Matrix Laboratories. # See LICENSE for details. """ Twisted's unit tests. """ from twisted.python.deprecate import deprecatedModuleAttribute from twisted.python.versions import Version from twisted.test import proto_helpers for obj in proto_helpers.__all__: deprecatedModuleAttribute( Version('Twisted', 'NEXT', 0, 0), 'Please use twisted.internet.testing.{} instead.'.format(obj), 'twisted.test.proto_helpers', obj)