code
stringlengths
26
870k
docstring
stringlengths
1
65.6k
func_name
stringlengths
1
194
language
stringclasses
1 value
repo
stringlengths
8
68
path
stringlengths
5
194
url
stringlengths
46
254
license
stringclasses
4 values
def cmd_STORED(self): """ Manage a success response to a set operation. """ self._current.popleft().success(True)
Manage a success response to a set operation.
cmd_STORED
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/memcache.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/memcache.py
MIT
def cmd_NOT_STORED(self): """ Manage a specific 'not stored' response to a set operation: this is not an error, but some condition wasn't met. """ self._current.popleft().success(False)
Manage a specific 'not stored' response to a set operation: this is not an error, but some condition wasn't met.
cmd_NOT_STORED
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/memcache.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/memcache.py
MIT
def cmd_END(self): """ This the end token to a get or a stat operation. """ cmd = self._current.popleft() if cmd.command == b"get": if cmd.multiple: values = {key: val[::2] for key, val in iteritems(cmd.values)} cmd.success(values) else: cmd.success((cmd.flags, cmd.value)) elif cmd.command == b"gets": if cmd.multiple: cmd.success(cmd.values) else: cmd.success((cmd.flags, cmd.cas, cmd.value)) elif cmd.command == b"stats": cmd.success(cmd.values) else: raise RuntimeError( "Unexpected END response to %s command" % (nativeString(cmd.command),))
This the end token to a get or a stat operation.
cmd_END
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/memcache.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/memcache.py
MIT
def cmd_NOT_FOUND(self): """ Manage error response for incr/decr/delete. """ self._current.popleft().success(False)
Manage error response for incr/decr/delete.
cmd_NOT_FOUND
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/memcache.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/memcache.py
MIT
def cmd_VALUE(self, line): """ Prepare the reading a value after a get. """ cmd = self._current[0] if cmd.command == b"get": key, flags, length = line.split() cas = b"" else: key, flags, length, cas = line.split() self._lenExpected = int(length) self._getBuffer = [] self._bufferLength = 0 if cmd.multiple: if key not in cmd.keys: raise RuntimeError("Unexpected commands answer.") cmd.currentKey = key cmd.values[key] = [int(flags), cas] else: if cmd.key != key: raise RuntimeError("Unexpected commands answer.") cmd.flags = int(flags) cmd.cas = cas self.setRawMode()
Prepare the reading a value after a get.
cmd_VALUE
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/memcache.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/memcache.py
MIT
def cmd_STAT(self, line): """ Reception of one stat line. """ cmd = self._current[0] key, val = line.split(b" ", 1) cmd.values[key] = val
Reception of one stat line.
cmd_STAT
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/memcache.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/memcache.py
MIT
def cmd_VERSION(self, versionData): """ Read version token. """ self._current.popleft().success(versionData)
Read version token.
cmd_VERSION
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/memcache.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/memcache.py
MIT
def cmd_ERROR(self): """ A non-existent command has been sent. """ log.err("Non-existent command sent.") cmd = self._current.popleft() cmd.fail(NoSuchCommand())
A non-existent command has been sent.
cmd_ERROR
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/memcache.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/memcache.py
MIT
def cmd_CLIENT_ERROR(self, errText): """ An invalid input as been sent. """ errText = repr(errText) log.err("Invalid input: " + errText) cmd = self._current.popleft() cmd.fail(ClientError(errText))
An invalid input as been sent.
cmd_CLIENT_ERROR
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/memcache.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/memcache.py
MIT
def cmd_SERVER_ERROR(self, errText): """ An error has happened server-side. """ errText = repr(errText) log.err("Server error: " + errText) cmd = self._current.popleft() cmd.fail(ServerError(errText))
An error has happened server-side.
cmd_SERVER_ERROR
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/memcache.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/memcache.py
MIT
def cmd_DELETED(self): """ A delete command has completed successfully. """ self._current.popleft().success(True)
A delete command has completed successfully.
cmd_DELETED
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/memcache.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/memcache.py
MIT
def cmd_OK(self): """ The last command has been completed. """ self._current.popleft().success(True)
The last command has been completed.
cmd_OK
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/memcache.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/memcache.py
MIT
def cmd_EXISTS(self): """ A C{checkAndSet} update has failed. """ self._current.popleft().success(False)
A C{checkAndSet} update has failed.
cmd_EXISTS
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/memcache.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/memcache.py
MIT
def lineReceived(self, line): """ Receive line commands from the server. """ self.resetTimeout() token = line.split(b" ", 1)[0] # First manage standard commands without space cmd = getattr(self, "cmd_" + nativeString(token), None) if cmd is not None: args = line.split(b" ", 1)[1:] if args: cmd(args[0]) else: cmd() else: # Then manage commands with space in it line = line.replace(b" ", b"_") cmd = getattr(self, "cmd_" + nativeString(line), None) if cmd is not None: cmd() else: # Increment/Decrement response cmd = self._current.popleft() val = int(line) cmd.success(val) if not self._current: # No pending request, remove timeout self.setTimeout(None)
Receive line commands from the server.
lineReceived
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/memcache.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/memcache.py
MIT
def increment(self, key, val=1): """ Increment the value of C{key} by given value (default to 1). C{key} must be consistent with an int. Return the new value. @param key: the key to modify. @type key: L{bytes} @param val: the value to increment. @type val: L{int} @return: a deferred with will be called back with the new value associated with the key (after the increment). @rtype: L{Deferred} """ return self._incrdecr(b"incr", key, val)
Increment the value of C{key} by given value (default to 1). C{key} must be consistent with an int. Return the new value. @param key: the key to modify. @type key: L{bytes} @param val: the value to increment. @type val: L{int} @return: a deferred with will be called back with the new value associated with the key (after the increment). @rtype: L{Deferred}
increment
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/memcache.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/memcache.py
MIT
def decrement(self, key, val=1): """ Decrement the value of C{key} by given value (default to 1). C{key} must be consistent with an int. Return the new value, coerced to 0 if negative. @param key: the key to modify. @type key: L{bytes} @param val: the value to decrement. @type val: L{int} @return: a deferred with will be called back with the new value associated with the key (after the decrement). @rtype: L{Deferred} """ return self._incrdecr(b"decr", key, val)
Decrement the value of C{key} by given value (default to 1). C{key} must be consistent with an int. Return the new value, coerced to 0 if negative. @param key: the key to modify. @type key: L{bytes} @param val: the value to decrement. @type val: L{int} @return: a deferred with will be called back with the new value associated with the key (after the decrement). @rtype: L{Deferred}
decrement
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/memcache.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/memcache.py
MIT
def _incrdecr(self, cmd, key, val): """ Internal wrapper for incr/decr. """ if self._disconnected: return fail(RuntimeError("not connected")) if not isinstance(key, bytes): return fail(ClientError( "Invalid type for key: %s, expecting bytes" % (type(key),))) if len(key) > self.MAX_KEY_LENGTH: return fail(ClientError("Key too long")) fullcmd = b" ".join([cmd, key, intToBytes(int(val))]) self.sendLine(fullcmd) cmdObj = Command(cmd, key=key) self._current.append(cmdObj) return cmdObj._deferred
Internal wrapper for incr/decr.
_incrdecr
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/memcache.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/memcache.py
MIT
def replace(self, key, val, flags=0, expireTime=0): """ Replace the given C{key}. It must already exist in the server. @param key: the key to replace. @type key: L{bytes} @param val: the new value associated with the key. @type val: L{bytes} @param flags: the flags to store with the key. @type flags: L{int} @param expireTime: if different from 0, the relative time in seconds when the key will be deleted from the store. @type expireTime: L{int} @return: a deferred that will fire with C{True} if the operation has succeeded, and C{False} with the key didn't previously exist. @rtype: L{Deferred} """ return self._set(b"replace", key, val, flags, expireTime, b"")
Replace the given C{key}. It must already exist in the server. @param key: the key to replace. @type key: L{bytes} @param val: the new value associated with the key. @type val: L{bytes} @param flags: the flags to store with the key. @type flags: L{int} @param expireTime: if different from 0, the relative time in seconds when the key will be deleted from the store. @type expireTime: L{int} @return: a deferred that will fire with C{True} if the operation has succeeded, and C{False} with the key didn't previously exist. @rtype: L{Deferred}
replace
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/memcache.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/memcache.py
MIT
def add(self, key, val, flags=0, expireTime=0): """ Add the given C{key}. It must not exist in the server. @param key: the key to add. @type key: L{bytes} @param val: the value associated with the key. @type val: L{bytes} @param flags: the flags to store with the key. @type flags: L{int} @param expireTime: if different from 0, the relative time in seconds when the key will be deleted from the store. @type expireTime: L{int} @return: a deferred that will fire with C{True} if the operation has succeeded, and C{False} with the key already exists. @rtype: L{Deferred} """ return self._set(b"add", key, val, flags, expireTime, b"")
Add the given C{key}. It must not exist in the server. @param key: the key to add. @type key: L{bytes} @param val: the value associated with the key. @type val: L{bytes} @param flags: the flags to store with the key. @type flags: L{int} @param expireTime: if different from 0, the relative time in seconds when the key will be deleted from the store. @type expireTime: L{int} @return: a deferred that will fire with C{True} if the operation has succeeded, and C{False} with the key already exists. @rtype: L{Deferred}
add
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/memcache.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/memcache.py
MIT
def set(self, key, val, flags=0, expireTime=0): """ Set the given C{key}. @param key: the key to set. @type key: L{bytes} @param val: the value associated with the key. @type val: L{bytes} @param flags: the flags to store with the key. @type flags: L{int} @param expireTime: if different from 0, the relative time in seconds when the key will be deleted from the store. @type expireTime: L{int} @return: a deferred that will fire with C{True} if the operation has succeeded. @rtype: L{Deferred} """ return self._set(b"set", key, val, flags, expireTime, b"")
Set the given C{key}. @param key: the key to set. @type key: L{bytes} @param val: the value associated with the key. @type val: L{bytes} @param flags: the flags to store with the key. @type flags: L{int} @param expireTime: if different from 0, the relative time in seconds when the key will be deleted from the store. @type expireTime: L{int} @return: a deferred that will fire with C{True} if the operation has succeeded. @rtype: L{Deferred}
set
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/memcache.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/memcache.py
MIT
def checkAndSet(self, key, val, cas, flags=0, expireTime=0): """ Change the content of C{key} only if the C{cas} value matches the current one associated with the key. Use this to store a value which hasn't been modified since last time you fetched it. @param key: The key to set. @type key: L{bytes} @param val: The value associated with the key. @type val: L{bytes} @param cas: Unique 64-bit value returned by previous call of C{get}. @type cas: L{bytes} @param flags: The flags to store with the key. @type flags: L{int} @param expireTime: If different from 0, the relative time in seconds when the key will be deleted from the store. @type expireTime: L{int} @return: A deferred that will fire with C{True} if the operation has succeeded, C{False} otherwise. @rtype: L{Deferred} """ return self._set(b"cas", key, val, flags, expireTime, cas)
Change the content of C{key} only if the C{cas} value matches the current one associated with the key. Use this to store a value which hasn't been modified since last time you fetched it. @param key: The key to set. @type key: L{bytes} @param val: The value associated with the key. @type val: L{bytes} @param cas: Unique 64-bit value returned by previous call of C{get}. @type cas: L{bytes} @param flags: The flags to store with the key. @type flags: L{int} @param expireTime: If different from 0, the relative time in seconds when the key will be deleted from the store. @type expireTime: L{int} @return: A deferred that will fire with C{True} if the operation has succeeded, C{False} otherwise. @rtype: L{Deferred}
checkAndSet
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/memcache.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/memcache.py
MIT
def _set(self, cmd, key, val, flags, expireTime, cas): """ Internal wrapper for setting values. """ if self._disconnected: return fail(RuntimeError("not connected")) if not isinstance(key, bytes): return fail(ClientError( "Invalid type for key: %s, expecting bytes" % (type(key),))) if len(key) > self.MAX_KEY_LENGTH: return fail(ClientError("Key too long")) if not isinstance(val, bytes): return fail(ClientError( "Invalid type for value: %s, expecting bytes" % (type(val),))) if cas: cas = b" " + cas length = len(val) fullcmd = b" ".join([ cmd, key, networkString("%d %d %d" % (flags, expireTime, length))]) + cas self.sendLine(fullcmd) self.sendLine(val) cmdObj = Command(cmd, key=key, flags=flags, length=length) self._current.append(cmdObj) return cmdObj._deferred
Internal wrapper for setting values.
_set
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/memcache.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/memcache.py
MIT
def append(self, key, val): """ Append given data to the value of an existing key. @param key: The key to modify. @type key: L{bytes} @param val: The value to append to the current value associated with the key. @type val: L{bytes} @return: A deferred that will fire with C{True} if the operation has succeeded, C{False} otherwise. @rtype: L{Deferred} """ # Even if flags and expTime values are ignored, we have to pass them return self._set(b"append", key, val, 0, 0, b"")
Append given data to the value of an existing key. @param key: The key to modify. @type key: L{bytes} @param val: The value to append to the current value associated with the key. @type val: L{bytes} @return: A deferred that will fire with C{True} if the operation has succeeded, C{False} otherwise. @rtype: L{Deferred}
append
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/memcache.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/memcache.py
MIT
def prepend(self, key, val): """ Prepend given data to the value of an existing key. @param key: The key to modify. @type key: L{bytes} @param val: The value to prepend to the current value associated with the key. @type val: L{bytes} @return: A deferred that will fire with C{True} if the operation has succeeded, C{False} otherwise. @rtype: L{Deferred} """ # Even if flags and expTime values are ignored, we have to pass them return self._set(b"prepend", key, val, 0, 0, b"")
Prepend given data to the value of an existing key. @param key: The key to modify. @type key: L{bytes} @param val: The value to prepend to the current value associated with the key. @type val: L{bytes} @return: A deferred that will fire with C{True} if the operation has succeeded, C{False} otherwise. @rtype: L{Deferred}
prepend
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/memcache.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/memcache.py
MIT
def get(self, key, withIdentifier=False): """ Get the given C{key}. It doesn't support multiple keys. If C{withIdentifier} is set to C{True}, the command issued is a C{gets}, that will return the current identifier associated with the value. This identifier has to be used when issuing C{checkAndSet} update later, using the corresponding method. @param key: The key to retrieve. @type key: L{bytes} @param withIdentifier: If set to C{True}, retrieve the current identifier along with the value and the flags. @type withIdentifier: L{bool} @return: A deferred that will fire with the tuple (flags, value) if C{withIdentifier} is C{False}, or (flags, cas identifier, value) if C{True}. If the server indicates there is no value associated with C{key}, the returned value will be L{None} and the returned flags will be C{0}. @rtype: L{Deferred} """ return self._get([key], withIdentifier, False)
Get the given C{key}. It doesn't support multiple keys. If C{withIdentifier} is set to C{True}, the command issued is a C{gets}, that will return the current identifier associated with the value. This identifier has to be used when issuing C{checkAndSet} update later, using the corresponding method. @param key: The key to retrieve. @type key: L{bytes} @param withIdentifier: If set to C{True}, retrieve the current identifier along with the value and the flags. @type withIdentifier: L{bool} @return: A deferred that will fire with the tuple (flags, value) if C{withIdentifier} is C{False}, or (flags, cas identifier, value) if C{True}. If the server indicates there is no value associated with C{key}, the returned value will be L{None} and the returned flags will be C{0}. @rtype: L{Deferred}
get
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/memcache.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/memcache.py
MIT
def getMultiple(self, keys, withIdentifier=False): """ Get the given list of C{keys}. If C{withIdentifier} is set to C{True}, the command issued is a C{gets}, that will return the identifiers associated with each values. This identifier has to be used when issuing C{checkAndSet} update later, using the corresponding method. @param keys: The keys to retrieve. @type keys: L{list} of L{bytes} @param withIdentifier: If set to C{True}, retrieve the identifiers along with the values and the flags. @type withIdentifier: L{bool} @return: A deferred that will fire with a dictionary with the elements of C{keys} as keys and the tuples (flags, value) as values if C{withIdentifier} is C{False}, or (flags, cas identifier, value) if C{True}. If the server indicates there is no value associated with C{key}, the returned values will be L{None} and the returned flags will be C{0}. @rtype: L{Deferred} @since: 9.0 """ return self._get(keys, withIdentifier, True)
Get the given list of C{keys}. If C{withIdentifier} is set to C{True}, the command issued is a C{gets}, that will return the identifiers associated with each values. This identifier has to be used when issuing C{checkAndSet} update later, using the corresponding method. @param keys: The keys to retrieve. @type keys: L{list} of L{bytes} @param withIdentifier: If set to C{True}, retrieve the identifiers along with the values and the flags. @type withIdentifier: L{bool} @return: A deferred that will fire with a dictionary with the elements of C{keys} as keys and the tuples (flags, value) as values if C{withIdentifier} is C{False}, or (flags, cas identifier, value) if C{True}. If the server indicates there is no value associated with C{key}, the returned values will be L{None} and the returned flags will be C{0}. @rtype: L{Deferred} @since: 9.0
getMultiple
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/memcache.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/memcache.py
MIT
def _get(self, keys, withIdentifier, multiple): """ Helper method for C{get} and C{getMultiple}. """ keys = list(keys) if self._disconnected: return fail(RuntimeError("not connected")) for key in keys: if not isinstance(key, bytes): return fail(ClientError( "Invalid type for key: %s, expecting bytes" % (type(key),))) if len(key) > self.MAX_KEY_LENGTH: return fail(ClientError("Key too long")) if withIdentifier: cmd = b"gets" else: cmd = b"get" fullcmd = b" ".join([cmd] + keys) self.sendLine(fullcmd) if multiple: values = dict([(key, (0, b"", None)) for key in keys]) cmdObj = Command(cmd, keys=keys, values=values, multiple=True) else: cmdObj = Command(cmd, key=keys[0], value=None, flags=0, cas=b"", multiple=False) self._current.append(cmdObj) return cmdObj._deferred
Helper method for C{get} and C{getMultiple}.
_get
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/memcache.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/memcache.py
MIT
def stats(self, arg=None): """ Get some stats from the server. It will be available as a dict. @param arg: An optional additional string which will be sent along with the I{stats} command. The interpretation of this value by the server is left undefined by the memcache protocol specification. @type arg: L{None} or L{bytes} @return: a deferred that will fire with a L{dict} of the available statistics. @rtype: L{Deferred} """ if arg: cmd = b"stats " + arg else: cmd = b"stats" if self._disconnected: return fail(RuntimeError("not connected")) self.sendLine(cmd) cmdObj = Command(b"stats", values={}) self._current.append(cmdObj) return cmdObj._deferred
Get some stats from the server. It will be available as a dict. @param arg: An optional additional string which will be sent along with the I{stats} command. The interpretation of this value by the server is left undefined by the memcache protocol specification. @type arg: L{None} or L{bytes} @return: a deferred that will fire with a L{dict} of the available statistics. @rtype: L{Deferred}
stats
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/memcache.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/memcache.py
MIT
def version(self): """ Get the version of the server. @return: a deferred that will fire with the string value of the version. @rtype: L{Deferred} """ if self._disconnected: return fail(RuntimeError("not connected")) self.sendLine(b"version") cmdObj = Command(b"version") self._current.append(cmdObj) return cmdObj._deferred
Get the version of the server. @return: a deferred that will fire with the string value of the version. @rtype: L{Deferred}
version
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/memcache.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/memcache.py
MIT
def delete(self, key): """ Delete an existing C{key}. @param key: the key to delete. @type key: L{bytes} @return: a deferred that will be called back with C{True} if the key was successfully deleted, or C{False} if not. @rtype: L{Deferred} """ if self._disconnected: return fail(RuntimeError("not connected")) if not isinstance(key, bytes): return fail(ClientError( "Invalid type for key: %s, expecting bytes" % (type(key),))) self.sendLine(b"delete " + key) cmdObj = Command(b"delete", key=key) self._current.append(cmdObj) return cmdObj._deferred
Delete an existing C{key}. @param key: the key to delete. @type key: L{bytes} @return: a deferred that will be called back with C{True} if the key was successfully deleted, or C{False} if not. @rtype: L{Deferred}
delete
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/memcache.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/memcache.py
MIT
def flushAll(self): """ Flush all cached values. @return: a deferred that will be called back with C{True} when the operation has succeeded. @rtype: L{Deferred} """ if self._disconnected: return fail(RuntimeError("not connected")) self.sendLine(b"flush_all") cmdObj = Command(b"flush_all") self._current.append(cmdObj) return cmdObj._deferred
Flush all cached values. @return: a deferred that will be called back with C{True} when the operation has succeeded. @rtype: L{Deferred}
flushAll
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/memcache.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/memcache.py
MIT
def toSegments(cwd, path): """ Normalize a path, as represented by a list of strings each representing one segment of the path. """ if path.startswith('/'): segs = [] else: segs = cwd[:] for s in path.split('/'): if s == '.' or s == '': continue elif s == '..': if segs: segs.pop() else: raise InvalidPath(cwd, path) elif '\0' in s or '/' in s: raise InvalidPath(cwd, path) else: segs.append(s) return segs
Normalize a path, as represented by a list of strings each representing one segment of the path.
toSegments
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
MIT
def errnoToFailure(e, path): """ Map C{OSError} and C{IOError} to standard FTP errors. """ if e == errno.ENOENT: return defer.fail(FileNotFoundError(path)) elif e == errno.EACCES or e == errno.EPERM: return defer.fail(PermissionDeniedError(path)) elif e == errno.ENOTDIR: return defer.fail(IsNotADirectoryError(path)) elif e == errno.EEXIST: return defer.fail(FileExistsError(path)) elif e == errno.EISDIR: return defer.fail(IsADirectoryError(path)) else: return defer.fail()
Map C{OSError} and C{IOError} to standard FTP errors.
errnoToFailure
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
MIT
def _isGlobbingExpression(segments=None): """ Helper for checking if a FTPShell `segments` contains a wildcard Unix expression. Only filename globbing is supported. This means that wildcards can only be presents in the last element of `segments`. @type segments: C{list} @param segments: List of path elements as used by the FTP server protocol. @rtype: Boolean @return: True if `segments` contains a globbing expression. """ if not segments: return False # To check that something is a glob expression, we convert it to # Regular Expression. # We compare it to the translation of a known non-glob expression. # If the result is the same as the original expression then it contains no # globbing expression. globCandidate = segments[-1] globTranslations = fnmatch.translate(globCandidate) nonGlobTranslations = _testTranslation.replace('TEST', globCandidate, 1) if nonGlobTranslations == globTranslations: return False else: return True
Helper for checking if a FTPShell `segments` contains a wildcard Unix expression. Only filename globbing is supported. This means that wildcards can only be presents in the last element of `segments`. @type segments: C{list} @param segments: List of path elements as used by the FTP server protocol. @rtype: Boolean @return: True if `segments` contains a globbing expression.
_isGlobbingExpression
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
MIT
def response(self): """ Generate a FTP response message for this error. """ return RESPONSE[self.errorCode] % self.errorMessage
Generate a FTP response message for this error.
response
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
MIT
def sendLine(self, line): """ Send a line to data channel. @param line: The line to be sent. @type line: L{bytes} """ self.transport.write(line + b'\r\n')
Send a line to data channel. @param line: The line to be sent. @type line: L{bytes}
sendLine
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
MIT
def _formatOneListResponse(self, name, size, directory, permissions, hardlinks, modified, owner, group): """ Helper method to format one entry's info into a text entry like: 'drwxrwxrwx 0 user group 0 Jan 01 1970 filename.txt' @param name: C{bytes} name of the entry (file or directory or link) @param size: C{int} size of the entry @param directory: evals to C{bool} - whether the entry is a directory @param permissions: L{twisted.python.filepath.Permissions} object representing that entry's permissions @param hardlinks: C{int} number of hardlinks @param modified: C{float} - entry's last modified time in seconds since the epoch @param owner: C{str} username of the owner @param group: C{str} group name of the owner @return: C{str} in the requisite format """ def formatDate(mtime): now = time.gmtime() info = { 'month': _months[mtime.tm_mon], 'day': mtime.tm_mday, 'year': mtime.tm_year, 'hour': mtime.tm_hour, 'minute': mtime.tm_min } if now.tm_year != mtime.tm_year: return '%(month)s %(day)02d %(year)5d' % info else: return '%(month)s %(day)02d %(hour)02d:%(minute)02d' % info format = ('%(directory)s%(permissions)s%(hardlinks)4d ' '%(owner)-9s %(group)-9s %(size)15d %(date)12s ' ) msg = (format % { 'directory': directory and 'd' or '-', 'permissions': permissions.shorthand(), 'hardlinks': hardlinks, 'owner': owner[:8], 'group': group[:8], 'size': size, 'date': formatDate(time.gmtime(modified)), }).encode(self._encoding) return msg + name
Helper method to format one entry's info into a text entry like: 'drwxrwxrwx 0 user group 0 Jan 01 1970 filename.txt' @param name: C{bytes} name of the entry (file or directory or link) @param size: C{int} size of the entry @param directory: evals to C{bool} - whether the entry is a directory @param permissions: L{twisted.python.filepath.Permissions} object representing that entry's permissions @param hardlinks: C{int} number of hardlinks @param modified: C{float} - entry's last modified time in seconds since the epoch @param owner: C{str} username of the owner @param group: C{str} group name of the owner @return: C{str} in the requisite format
_formatOneListResponse
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
MIT
def __init__(self, pi, peerHost=None, reactor=None): """ Constructor @param pi: this factory's protocol interpreter @param peerHost: if peerCheck is True, this is the tuple that the generated instance will use to perform security checks """ self.pi = pi # the protocol interpreter that is using this factory self.peerHost = peerHost # the from FTP.transport.peerHost() self.deferred = defer.Deferred() # deferred will fire when instance is connected self.delayedCall = None if reactor is None: from twisted.internet import reactor self._reactor = reactor
Constructor @param pi: this factory's protocol interpreter @param peerHost: if peerCheck is True, this is the tuple that the generated instance will use to perform security checks
__init__
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
MIT
def sendLine(self, line): """ (Private) Encodes and sends a line @param line: L{bytes} or L{unicode} """ if isinstance(line, unicode): line = line.encode(self._encoding) super(FTP, self).sendLine(line)
(Private) Encodes and sends a line @param line: L{bytes} or L{unicode}
sendLine
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
MIT
def getDTPPort(self, factory): """ Return a port for passive access, using C{self.passivePortRange} attribute. """ for portn in self.passivePortRange: try: dtpPort = self.listenFactory(portn, factory) except error.CannotListenError: continue else: return dtpPort raise error.CannotListenError('', portn, "No port available in range %s" % (self.passivePortRange,))
Return a port for passive access, using C{self.passivePortRange} attribute.
getDTPPort
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
MIT
def ftp_USER(self, username): """ First part of login. Get the username the peer wants to authenticate as. """ if not username: return defer.fail(CmdSyntaxError('USER requires an argument')) self._user = username self.state = self.INAUTH if self.factory.allowAnonymous and self._user == self.factory.userAnonymous: return GUEST_NAME_OK_NEED_EMAIL else: return (USR_NAME_OK_NEED_PASS, username)
First part of login. Get the username the peer wants to authenticate as.
ftp_USER
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
MIT
def ftp_PASS(self, password): """ Second part of login. Get the password the peer wants to authenticate with. """ if self.factory.allowAnonymous and self._user == self.factory.userAnonymous: # anonymous login creds = credentials.Anonymous() reply = GUEST_LOGGED_IN_PROCEED else: # user login creds = credentials.UsernamePassword(self._user, password) reply = USR_LOGGED_IN_PROCEED del self._user def _cbLogin(result): (interface, avatar, logout) = result assert interface is IFTPShell, "The realm is busted, jerk." self.shell = avatar self.logout = logout self.workingDirectory = [] self.state = self.AUTHED return reply def _ebLogin(failure): failure.trap(cred_error.UnauthorizedLogin, cred_error.UnhandledCredentials) self.state = self.UNAUTH raise AuthorizationError d = self.portal.login(creds, None, IFTPShell) d.addCallbacks(_cbLogin, _ebLogin) return d
Second part of login. Get the password the peer wants to authenticate with.
ftp_PASS
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
MIT
def ftp_PASV(self): """ Request for a passive connection from the rfc:: This command requests the server-DTP to \"listen\" on a data port (which is not its default data port) and to wait for a connection rather than initiate one upon receipt of a transfer command. The response to this command includes the host and port address this server is listening on. """ # if we have a DTP port set up, lose it. if self.dtpFactory is not None: # cleanupDTP sets dtpFactory to none. Later we'll do # cleanup here or something. self.cleanupDTP() self.dtpFactory = DTPFactory(pi=self) self.dtpFactory.setTimeout(self.dtpTimeout) self.dtpPort = self.getDTPPort(self.dtpFactory) host = self.transport.getHost().host port = self.dtpPort.getHost().port self.reply(ENTERING_PASV_MODE, encodeHostPort(host, port)) return self.dtpFactory.deferred.addCallback(lambda ign: None)
Request for a passive connection from the rfc:: This command requests the server-DTP to \"listen\" on a data port (which is not its default data port) and to wait for a connection rather than initiate one upon receipt of a transfer command. The response to this command includes the host and port address this server is listening on.
ftp_PASV
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
MIT
def _encodeName(self, name): """ Encode C{name} to be sent over the wire. This encodes L{unicode} objects as UTF-8 and leaves L{bytes} as-is. As described by U{RFC 3659 section 2.2<https://tools.ietf.org/html/rfc3659#section-2.2>}:: Various FTP commands take pathnames as arguments, or return pathnames in responses. When the MLST command is supported, as indicated in the response to the FEAT command, pathnames are to be transferred in one of the following two formats. pathname = utf-8-name / raw utf-8-name = <a UTF-8 encoded Unicode string> raw = <any string that is not a valid UTF-8 encoding> Which format is used is at the option of the user-PI or server-PI sending the pathname. @param name: Name to be encoded. @type name: L{bytes} or L{unicode} @return: Wire format of C{name}. @rtype: L{bytes} """ if isinstance(name, unicode): return name.encode('utf-8') return name
Encode C{name} to be sent over the wire. This encodes L{unicode} objects as UTF-8 and leaves L{bytes} as-is. As described by U{RFC 3659 section 2.2<https://tools.ietf.org/html/rfc3659#section-2.2>}:: Various FTP commands take pathnames as arguments, or return pathnames in responses. When the MLST command is supported, as indicated in the response to the FEAT command, pathnames are to be transferred in one of the following two formats. pathname = utf-8-name / raw utf-8-name = <a UTF-8 encoded Unicode string> raw = <any string that is not a valid UTF-8 encoding> Which format is used is at the option of the user-PI or server-PI sending the pathname. @param name: Name to be encoded. @type name: L{bytes} or L{unicode} @return: Wire format of C{name}. @rtype: L{bytes}
_encodeName
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
MIT
def ftp_LIST(self, path=''): """ This command causes a list to be sent from the server to the passive DTP. If the pathname specifies a directory or other group of files, the server should transfer a list of files in the specified directory. If the pathname specifies a file then the server should send current information on the file. A null argument implies the user's current working or default directory. """ # Uh, for now, do this retarded thing. if self.dtpInstance is None or not self.dtpInstance.isConnected: return defer.fail(BadCmdSequenceError('must send PORT or PASV before RETR')) # Various clients send flags like -L or -al etc. We just ignore them. if path.lower() in ['-a', '-l', '-la', '-al']: path = '' def gotListing(results): self.reply(DATA_CNX_ALREADY_OPEN_START_XFR) for (name, attrs) in results: name = self._encodeName(name) self.dtpInstance.sendListResponse(name, attrs) self.dtpInstance.transport.loseConnection() return (TXFR_COMPLETE_OK,) try: segments = toSegments(self.workingDirectory, path) except InvalidPath: return defer.fail(FileNotFoundError(path)) d = self.shell.list( segments, ('size', 'directory', 'permissions', 'hardlinks', 'modified', 'owner', 'group')) d.addCallback(gotListing) return d
This command causes a list to be sent from the server to the passive DTP. If the pathname specifies a directory or other group of files, the server should transfer a list of files in the specified directory. If the pathname specifies a file then the server should send current information on the file. A null argument implies the user's current working or default directory.
ftp_LIST
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
MIT
def cbList(results, glob): """ Send, line by line, each matching file in the directory listing, and then close the connection. @type results: A C{list} of C{tuple}. The first element of each C{tuple} is a C{str} and the second element is a C{list}. @param results: The names of the files in the directory. @param glob: A shell-style glob through which to filter results (see U{http://docs.python.org/2/library/fnmatch.html}), or L{None} for no filtering. @type glob: L{str} or L{None} @return: A C{tuple} containing the status code for a successful transfer. @rtype: C{tuple} """ self.reply(DATA_CNX_ALREADY_OPEN_START_XFR) for (name, ignored) in results: if not glob or (glob and fnmatch.fnmatch(name, glob)): name = self._encodeName(name) self.dtpInstance.sendLine(name) self.dtpInstance.transport.loseConnection() return (TXFR_COMPLETE_OK,)
Send, line by line, each matching file in the directory listing, and then close the connection. @type results: A C{list} of C{tuple}. The first element of each C{tuple} is a C{str} and the second element is a C{list}. @param results: The names of the files in the directory. @param glob: A shell-style glob through which to filter results (see U{http://docs.python.org/2/library/fnmatch.html}), or L{None} for no filtering. @type glob: L{str} or L{None} @return: A C{tuple} containing the status code for a successful transfer. @rtype: C{tuple}
ftp_NLST.cbList
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
MIT
def listErr(results): """ RFC 959 specifies that an NLST request may only return directory listings. Thus, send nothing and just close the connection. @type results: L{Failure} @param results: The L{Failure} wrapping a L{FileNotFoundError} that occurred while trying to list the contents of a nonexistent directory. @returns: A C{tuple} containing the status code for a successful transfer. @rtype: C{tuple} """ self.dtpInstance.transport.loseConnection() return (TXFR_COMPLETE_OK,)
RFC 959 specifies that an NLST request may only return directory listings. Thus, send nothing and just close the connection. @type results: L{Failure} @param results: The L{Failure} wrapping a L{FileNotFoundError} that occurred while trying to list the contents of a nonexistent directory. @returns: A C{tuple} containing the status code for a successful transfer. @rtype: C{tuple}
ftp_NLST.listErr
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
MIT
def ftp_NLST(self, path): """ This command causes a directory listing to be sent from the server to the client. The pathname should specify a directory or other system-specific file group descriptor. An empty path implies the current working directory. If the path is non-existent, send nothing. If the path is to a file, send only the file name. @type path: C{str} @param path: The path for which a directory listing should be returned. @rtype: L{Deferred} @return: a L{Deferred} which will be fired when the listing request is finished. """ # XXX: why is this check different from ftp_RETR/ftp_STOR? See #4180 if self.dtpInstance is None or not self.dtpInstance.isConnected: return defer.fail( BadCmdSequenceError('must send PORT or PASV before RETR')) try: segments = toSegments(self.workingDirectory, path) except InvalidPath: return defer.fail(FileNotFoundError(path)) def cbList(results, glob): """ Send, line by line, each matching file in the directory listing, and then close the connection. @type results: A C{list} of C{tuple}. The first element of each C{tuple} is a C{str} and the second element is a C{list}. @param results: The names of the files in the directory. @param glob: A shell-style glob through which to filter results (see U{http://docs.python.org/2/library/fnmatch.html}), or L{None} for no filtering. @type glob: L{str} or L{None} @return: A C{tuple} containing the status code for a successful transfer. @rtype: C{tuple} """ self.reply(DATA_CNX_ALREADY_OPEN_START_XFR) for (name, ignored) in results: if not glob or (glob and fnmatch.fnmatch(name, glob)): name = self._encodeName(name) self.dtpInstance.sendLine(name) self.dtpInstance.transport.loseConnection() return (TXFR_COMPLETE_OK,) def listErr(results): """ RFC 959 specifies that an NLST request may only return directory listings. Thus, send nothing and just close the connection. @type results: L{Failure} @param results: The L{Failure} wrapping a L{FileNotFoundError} that occurred while trying to list the contents of a nonexistent directory. @returns: A C{tuple} containing the status code for a successful transfer. @rtype: C{tuple} """ self.dtpInstance.transport.loseConnection() return (TXFR_COMPLETE_OK,) if _isGlobbingExpression(segments): # Remove globbing expression from path # and keep to be used for filtering. glob = segments.pop() else: glob = None d = self.shell.list(segments) d.addCallback(cbList, glob) # self.shell.list will generate an error if the path is invalid d.addErrback(listErr) return d
This command causes a directory listing to be sent from the server to the client. The pathname should specify a directory or other system-specific file group descriptor. An empty path implies the current working directory. If the path is non-existent, send nothing. If the path is to a file, send only the file name. @type path: C{str} @param path: The path for which a directory listing should be returned. @rtype: L{Deferred} @return: a L{Deferred} which will be fired when the listing request is finished.
ftp_NLST
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
MIT
def ftp_RETR(self, path): """ This command causes the content of a file to be sent over the data transfer channel. If the path is to a folder, an error will be raised. @type path: C{str} @param path: The path to the file which should be transferred over the data transfer channel. @rtype: L{Deferred} @return: a L{Deferred} which will be fired when the transfer is done. """ if self.dtpInstance is None: raise BadCmdSequenceError('PORT or PASV required before RETR') try: newsegs = toSegments(self.workingDirectory, path) except InvalidPath: return defer.fail(FileNotFoundError(path)) # XXX For now, just disable the timeout. Later we'll want to # leave it active and have the DTP connection reset it # periodically. self.setTimeout(None) # Put it back later def enableTimeout(result): self.setTimeout(self.factory.timeOut) return result # And away she goes if not self.binary: cons = ASCIIConsumerWrapper(self.dtpInstance) else: cons = self.dtpInstance def cbSent(result): return (TXFR_COMPLETE_OK,) def ebSent(err): log.msg("Unexpected error attempting to transmit file to client:") log.err(err) if err.check(FTPCmdError): return err return (CNX_CLOSED_TXFR_ABORTED,) def cbOpened(file): # Tell them what to doooo if self.dtpInstance.isConnected: self.reply(DATA_CNX_ALREADY_OPEN_START_XFR) else: self.reply(FILE_STATUS_OK_OPEN_DATA_CNX) d = file.send(cons) d.addCallbacks(cbSent, ebSent) return d def ebOpened(err): if not err.check(PermissionDeniedError, FileNotFoundError, IsADirectoryError): log.msg("Unexpected error attempting to open file for transmission:") log.err(err) if err.check(FTPCmdError): return (err.value.errorCode, '/'.join(newsegs)) return (FILE_NOT_FOUND, '/'.join(newsegs)) d = self.shell.openForReading(newsegs) d.addCallbacks(cbOpened, ebOpened) d.addBoth(enableTimeout) # Pass back Deferred that fires when the transfer is done return d
This command causes the content of a file to be sent over the data transfer channel. If the path is to a folder, an error will be raised. @type path: C{str} @param path: The path to the file which should be transferred over the data transfer channel. @rtype: L{Deferred} @return: a L{Deferred} which will be fired when the transfer is done.
ftp_RETR
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
MIT
def cbOpened(file): """ File was open for reading. Launch the data transfer channel via the file consumer. """ d = file.receive() d.addCallback(cbConsumer) d.addCallback(lambda ignored: file.close()) d.addCallbacks(cbSent, ebSent) return d
File was open for reading. Launch the data transfer channel via the file consumer.
ftp_STOR.cbOpened
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
MIT
def ebOpened(err): """ Called when failed to open the file for reading. For known errors, return the FTP error code. For all other, return a file not found error. """ if isinstance(err.value, FTPCmdError): return (err.value.errorCode, '/'.join(newsegs)) log.err(err, "Unexpected error received while opening file:") return (FILE_NOT_FOUND, '/'.join(newsegs))
Called when failed to open the file for reading. For known errors, return the FTP error code. For all other, return a file not found error.
ftp_STOR.ebOpened
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
MIT
def cbConsumer(cons): """ Called after the file was opended for reading. Prepare the data transfer channel and send the response to the command channel. """ if not self.binary: cons = ASCIIConsumerWrapper(cons) d = self.dtpInstance.registerConsumer(cons) # Tell them what to doooo if self.dtpInstance.isConnected: self.reply(DATA_CNX_ALREADY_OPEN_START_XFR) else: self.reply(FILE_STATUS_OK_OPEN_DATA_CNX) return d
Called after the file was opended for reading. Prepare the data transfer channel and send the response to the command channel.
ftp_STOR.cbConsumer
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
MIT
def cbSent(result): """ Called from data transport when tranfer is done. """ return (TXFR_COMPLETE_OK,)
Called from data transport when tranfer is done.
ftp_STOR.cbSent
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
MIT
def ebSent(err): """ Called from data transport when there are errors during the transfer. """ log.err(err, "Unexpected error received during transfer:") if err.check(FTPCmdError): return err return (CNX_CLOSED_TXFR_ABORTED,)
Called from data transport when there are errors during the transfer.
ftp_STOR.ebSent
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
MIT
def ftp_STOR(self, path): """ STORE (STOR) This command causes the server-DTP to accept the data transferred via the data connection and to store the data as a file at the server site. If the file specified in the pathname exists at the server site, then its contents shall be replaced by the data being transferred. A new file is created at the server site if the file specified in the pathname does not already exist. """ if self.dtpInstance is None: raise BadCmdSequenceError('PORT or PASV required before STOR') try: newsegs = toSegments(self.workingDirectory, path) except InvalidPath: return defer.fail(FileNotFoundError(path)) # XXX For now, just disable the timeout. Later we'll want to # leave it active and have the DTP connection reset it # periodically. self.setTimeout(None) # Put it back later def enableTimeout(result): self.setTimeout(self.factory.timeOut) return result def cbOpened(file): """ File was open for reading. Launch the data transfer channel via the file consumer. """ d = file.receive() d.addCallback(cbConsumer) d.addCallback(lambda ignored: file.close()) d.addCallbacks(cbSent, ebSent) return d def ebOpened(err): """ Called when failed to open the file for reading. For known errors, return the FTP error code. For all other, return a file not found error. """ if isinstance(err.value, FTPCmdError): return (err.value.errorCode, '/'.join(newsegs)) log.err(err, "Unexpected error received while opening file:") return (FILE_NOT_FOUND, '/'.join(newsegs)) def cbConsumer(cons): """ Called after the file was opended for reading. Prepare the data transfer channel and send the response to the command channel. """ if not self.binary: cons = ASCIIConsumerWrapper(cons) d = self.dtpInstance.registerConsumer(cons) # Tell them what to doooo if self.dtpInstance.isConnected: self.reply(DATA_CNX_ALREADY_OPEN_START_XFR) else: self.reply(FILE_STATUS_OK_OPEN_DATA_CNX) return d def cbSent(result): """ Called from data transport when tranfer is done. """ return (TXFR_COMPLETE_OK,) def ebSent(err): """ Called from data transport when there are errors during the transfer. """ log.err(err, "Unexpected error received during transfer:") if err.check(FTPCmdError): return err return (CNX_CLOSED_TXFR_ABORTED,) d = self.shell.openForWriting(newsegs) d.addCallbacks(cbOpened, ebOpened) d.addBoth(enableTimeout) # Pass back Deferred that fires when the transfer is done return d
STORE (STOR) This command causes the server-DTP to accept the data transferred via the data connection and to store the data as a file at the server site. If the file specified in the pathname exists at the server site, then its contents shall be replaced by the data being transferred. A new file is created at the server site if the file specified in the pathname does not already exist.
ftp_STOR
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
MIT
def ftp_SIZE(self, path): """ File SIZE The FTP command, SIZE OF FILE (SIZE), is used to obtain the transfer size of a file from the server-FTP process. This is the exact number of octets (8 bit bytes) that would be transmitted over the data connection should that file be transmitted. This value will change depending on the current STRUcture, MODE, and TYPE of the data connection or of a data connection that would be created were one created now. Thus, the result of the SIZE command is dependent on the currently established STRU, MODE, and TYPE parameters. The SIZE command returns how many octets would be transferred if the file were to be transferred using the current transfer structure, mode, and type. This command is normally used in conjunction with the RESTART (REST) command when STORing a file to a remote server in STREAM mode, to determine the restart point. The server-PI might need to read the partially transferred file, do any appropriate conversion, and count the number of octets that would be generated when sending the file in order to correctly respond to this command. Estimates of the file transfer size MUST NOT be returned; only precise information is acceptable. http://tools.ietf.org/html/rfc3659 """ try: newsegs = toSegments(self.workingDirectory, path) except InvalidPath: return defer.fail(FileNotFoundError(path)) def cbStat(result): (size,) = result return (FILE_STATUS, str(size)) return self.shell.stat(newsegs, ('size',)).addCallback(cbStat)
File SIZE The FTP command, SIZE OF FILE (SIZE), is used to obtain the transfer size of a file from the server-FTP process. This is the exact number of octets (8 bit bytes) that would be transmitted over the data connection should that file be transmitted. This value will change depending on the current STRUcture, MODE, and TYPE of the data connection or of a data connection that would be created were one created now. Thus, the result of the SIZE command is dependent on the currently established STRU, MODE, and TYPE parameters. The SIZE command returns how many octets would be transferred if the file were to be transferred using the current transfer structure, mode, and type. This command is normally used in conjunction with the RESTART (REST) command when STORing a file to a remote server in STREAM mode, to determine the restart point. The server-PI might need to read the partially transferred file, do any appropriate conversion, and count the number of octets that would be generated when sending the file in order to correctly respond to this command. Estimates of the file transfer size MUST NOT be returned; only precise information is acceptable. http://tools.ietf.org/html/rfc3659
ftp_SIZE
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
MIT
def ftp_MDTM(self, path): """ File Modification Time (MDTM) The FTP command, MODIFICATION TIME (MDTM), can be used to determine when a file in the server NVFS was last modified. This command has existed in many FTP servers for many years, as an adjunct to the REST command for STREAM mode, thus is widely available. However, where supported, the "modify" fact that can be provided in the result from the new MLST command is recommended as a superior alternative. http://tools.ietf.org/html/rfc3659 """ try: newsegs = toSegments(self.workingDirectory, path) except InvalidPath: return defer.fail(FileNotFoundError(path)) def cbStat(result): (modified,) = result return (FILE_STATUS, time.strftime('%Y%m%d%H%M%S', time.gmtime(modified))) return self.shell.stat(newsegs, ('modified',)).addCallback(cbStat)
File Modification Time (MDTM) The FTP command, MODIFICATION TIME (MDTM), can be used to determine when a file in the server NVFS was last modified. This command has existed in many FTP servers for many years, as an adjunct to the REST command for STREAM mode, thus is widely available. However, where supported, the "modify" fact that can be provided in the result from the new MLST command is recommended as a superior alternative. http://tools.ietf.org/html/rfc3659
ftp_MDTM
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
MIT
def ftp_TYPE(self, type): """ REPRESENTATION TYPE (TYPE) The argument specifies the representation type as described in the Section on Data Representation and Storage. Several types take a second parameter. The first parameter is denoted by a single Telnet character, as is the second Format parameter for ASCII and EBCDIC; the second parameter for local byte is a decimal integer to indicate Bytesize. The parameters are separated by a <SP> (Space, ASCII code 32). """ p = type.upper() if p: f = getattr(self, 'type_' + p[0], None) if f is not None: return f(p[1:]) return self.type_UNKNOWN(p) return (SYNTAX_ERR,)
REPRESENTATION TYPE (TYPE) The argument specifies the representation type as described in the Section on Data Representation and Storage. Several types take a second parameter. The first parameter is denoted by a single Telnet character, as is the second Format parameter for ASCII and EBCDIC; the second parameter for local byte is a decimal integer to indicate Bytesize. The parameters are separated by a <SP> (Space, ASCII code 32).
ftp_TYPE
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
MIT
def ftp_FEAT(self): """ Advertise the features supported by the server. http://tools.ietf.org/html/rfc2389 """ self.sendLine(RESPONSE[FEAT_OK][0]) for feature in self.FEATURES: self.sendLine(' ' + feature) self.sendLine(RESPONSE[FEAT_OK][1])
Advertise the features supported by the server. http://tools.ietf.org/html/rfc2389
ftp_FEAT
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
MIT
def ftp_OPTS(self, option): """ Handle OPTS command. http://tools.ietf.org/html/draft-ietf-ftpext-utf-8-option-00 """ return self.reply(OPTS_NOT_IMPLEMENTED, option)
Handle OPTS command. http://tools.ietf.org/html/draft-ietf-ftpext-utf-8-option-00
ftp_OPTS
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
MIT
def cleanupDTP(self): """ Call when DTP connection exits """ log.msg('cleanupDTP', debug=True) log.msg(self.dtpPort) dtpPort, self.dtpPort = self.dtpPort, None if interfaces.IListeningPort.providedBy(dtpPort): dtpPort.stopListening() elif interfaces.IConnector.providedBy(dtpPort): dtpPort.disconnect() else: assert False, "dtpPort should be an IListeningPort or IConnector, instead is %r" % (dtpPort,) self.dtpFactory.stopFactory() self.dtpFactory = None if self.dtpInstance is not None: self.dtpInstance = None
Call when DTP connection exits
cleanupDTP
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
MIT
def makeDirectory(path): """ Create a directory. @param path: The path, as a list of segments, to create @type path: C{list} of C{unicode} @return: A Deferred which fires when the directory has been created, or which fails if the directory cannot be created. """
Create a directory. @param path: The path, as a list of segments, to create @type path: C{list} of C{unicode} @return: A Deferred which fires when the directory has been created, or which fails if the directory cannot be created.
makeDirectory
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
MIT
def removeDirectory(path): """ Remove a directory. @param path: The path, as a list of segments, to remove @type path: C{list} of C{unicode} @return: A Deferred which fires when the directory has been removed, or which fails if the directory cannot be removed. """
Remove a directory. @param path: The path, as a list of segments, to remove @type path: C{list} of C{unicode} @return: A Deferred which fires when the directory has been removed, or which fails if the directory cannot be removed.
removeDirectory
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
MIT
def removeFile(path): """ Remove a file. @param path: The path, as a list of segments, to remove @type path: C{list} of C{unicode} @return: A Deferred which fires when the file has been removed, or which fails if the file cannot be removed. """
Remove a file. @param path: The path, as a list of segments, to remove @type path: C{list} of C{unicode} @return: A Deferred which fires when the file has been removed, or which fails if the file cannot be removed.
removeFile
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
MIT
def rename(fromPath, toPath): """ Rename a file or directory. @param fromPath: The current name of the path. @type fromPath: C{list} of C{unicode} @param toPath: The desired new name of the path. @type toPath: C{list} of C{unicode} @return: A Deferred which fires when the path has been renamed, or which fails if the path cannot be renamed. """
Rename a file or directory. @param fromPath: The current name of the path. @type fromPath: C{list} of C{unicode} @param toPath: The desired new name of the path. @type toPath: C{list} of C{unicode} @return: A Deferred which fires when the path has been renamed, or which fails if the path cannot be renamed.
rename
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
MIT
def access(path): """ Determine whether access to the given path is allowed. @param path: The path, as a list of segments @return: A Deferred which fires with None if access is allowed or which fails with a specific exception type if access is denied. """
Determine whether access to the given path is allowed. @param path: The path, as a list of segments @return: A Deferred which fires with None if access is allowed or which fails with a specific exception type if access is denied.
access
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
MIT
def stat(path, keys=()): """ Retrieve information about the given path. This is like list, except it will never return results about child paths. """
Retrieve information about the given path. This is like list, except it will never return results about child paths.
stat
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
MIT
def list(path, keys=()): """ Retrieve information about the given path. If the path represents a non-directory, the result list should have only one entry with information about that non-directory. Otherwise, the result list should have an element for each child of the directory. @param path: The path, as a list of segments, to list @type path: C{list} of C{unicode} or C{bytes} @param keys: A tuple of keys desired in the resulting dictionaries. @return: A Deferred which fires with a list of (name, list), where the name is the name of the entry as a unicode string or bytes and each list contains values corresponding to the requested keys. The following are possible elements of keys, and the values which should be returned for them: - C{'size'}: size in bytes, as an integer (this is kinda required) - C{'directory'}: boolean indicating the type of this entry - C{'permissions'}: a bitvector (see os.stat(foo).st_mode) - C{'hardlinks'}: Number of hard links to this entry - C{'modified'}: number of seconds since the epoch since entry was modified - C{'owner'}: string indicating the user owner of this entry - C{'group'}: string indicating the group owner of this entry """
Retrieve information about the given path. If the path represents a non-directory, the result list should have only one entry with information about that non-directory. Otherwise, the result list should have an element for each child of the directory. @param path: The path, as a list of segments, to list @type path: C{list} of C{unicode} or C{bytes} @param keys: A tuple of keys desired in the resulting dictionaries. @return: A Deferred which fires with a list of (name, list), where the name is the name of the entry as a unicode string or bytes and each list contains values corresponding to the requested keys. The following are possible elements of keys, and the values which should be returned for them: - C{'size'}: size in bytes, as an integer (this is kinda required) - C{'directory'}: boolean indicating the type of this entry - C{'permissions'}: a bitvector (see os.stat(foo).st_mode) - C{'hardlinks'}: Number of hard links to this entry - C{'modified'}: number of seconds since the epoch since entry was modified - C{'owner'}: string indicating the user owner of this entry - C{'group'}: string indicating the group owner of this entry
list
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
MIT
def openForReading(path): """ @param path: The path, as a list of segments, to open @type path: C{list} of C{unicode} @rtype: C{Deferred} which will fire with L{IReadFile} """
@param path: The path, as a list of segments, to open @type path: C{list} of C{unicode} @rtype: C{Deferred} which will fire with L{IReadFile}
openForReading
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
MIT
def openForWriting(path): """ @param path: The path, as a list of segments, to open @type path: C{list} of C{unicode} @rtype: C{Deferred} which will fire with L{IWriteFile} """
@param path: The path, as a list of segments, to open @type path: C{list} of C{unicode} @rtype: C{Deferred} which will fire with L{IWriteFile}
openForWriting
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
MIT
def send(consumer): """ Produce the contents of the given path to the given consumer. This method may only be invoked once on each provider. @type consumer: C{IConsumer} @return: A Deferred which fires when the file has been consumed completely. """
Produce the contents of the given path to the given consumer. This method may only be invoked once on each provider. @type consumer: C{IConsumer} @return: A Deferred which fires when the file has been consumed completely.
send
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
MIT
def receive(): """ Create a consumer which will write to this file. This method may only be invoked once on each provider. @rtype: C{Deferred} of C{IConsumer} """
Create a consumer which will write to this file. This method may only be invoked once on each provider. @rtype: C{Deferred} of C{IConsumer}
receive
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
MIT
def close(): """ Perform any post-write work that needs to be done. This method may only be invoked once on each provider, and will always be invoked after receive(). @rtype: C{Deferred} of anything: the value is ignored. The FTP client will not see their upload request complete until this Deferred has been fired. """
Perform any post-write work that needs to be done. This method may only be invoked once on each provider, and will always be invoked after receive(). @rtype: C{Deferred} of anything: the value is ignored. The FTP client will not see their upload request complete until this Deferred has been fired.
close
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
MIT
def _getgroups(uid): """ Return the primary and supplementary groups for the given UID. @type uid: C{int} """ result = [] pwent = pwd.getpwuid(uid) result.append(pwent.pw_gid) for grent in grp.getgrall(): if pwent.pw_name in grent.gr_mem: result.append(grent.gr_gid) return result
Return the primary and supplementary groups for the given UID. @type uid: C{int}
_getgroups
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
MIT
def _testPermissions(uid, gid, spath, mode='r'): """ checks to see if uid has proper permissions to access path with mode @type uid: C{int} @param uid: numeric user id @type gid: C{int} @param gid: numeric group id @type spath: C{str} @param spath: the path on the server to test @type mode: C{str} @param mode: 'r' or 'w' (read or write) @rtype: C{bool} @return: True if the given credentials have the specified form of access to the given path """ if mode == 'r': usr = stat.S_IRUSR grp = stat.S_IRGRP oth = stat.S_IROTH amode = os.R_OK elif mode == 'w': usr = stat.S_IWUSR grp = stat.S_IWGRP oth = stat.S_IWOTH amode = os.W_OK else: raise ValueError("Invalid mode %r: must specify 'r' or 'w'" % (mode,)) access = False if os.path.exists(spath): if uid == 0: access = True else: s = os.stat(spath) if usr & s.st_mode and uid == s.st_uid: access = True elif grp & s.st_mode and gid in _getgroups(uid): access = True elif oth & s.st_mode: access = True if access: if not os.access(spath, amode): access = False log.msg("Filesystem grants permission to UID %d but it is inaccessible to me running as UID %d" % ( uid, os.getuid())) return access
checks to see if uid has proper permissions to access path with mode @type uid: C{int} @param uid: numeric user id @type gid: C{int} @param gid: numeric group id @type spath: C{str} @param spath: the path on the server to test @type mode: C{str} @param mode: 'r' or 'w' (read or write) @rtype: C{bool} @return: True if the given credentials have the specified form of access to the given path
_testPermissions
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
MIT
def openForReading(self, path): """ Open C{path} for reading. @param path: The path, as a list of segments, to open. @type path: C{list} of C{unicode} @return: A L{Deferred} is returned that will fire with an object implementing L{IReadFile} if the file is successfully opened. If C{path} is a directory, or if an exception is raised while trying to open the file, the L{Deferred} will fire with an error. """ p = self._path(path) if p.isdir(): # Normally, we would only check for EISDIR in open, but win32 # returns EACCES in this case, so we check before return defer.fail(IsADirectoryError(path)) try: f = p.open('r') except (IOError, OSError) as e: return errnoToFailure(e.errno, path) except: return defer.fail() else: return defer.succeed(_FileReader(f))
Open C{path} for reading. @param path: The path, as a list of segments, to open. @type path: C{list} of C{unicode} @return: A L{Deferred} is returned that will fire with an object implementing L{IReadFile} if the file is successfully opened. If C{path} is a directory, or if an exception is raised while trying to open the file, the L{Deferred} will fire with an error.
openForReading
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
MIT
def openForWriting(self, path): """ Reject write attempts by anonymous users with L{PermissionDeniedError}. """ return defer.fail(PermissionDeniedError("STOR not allowed"))
Reject write attempts by anonymous users with L{PermissionDeniedError}.
openForWriting
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
MIT
def list(self, path, keys=()): """ Return the list of files at given C{path}, adding C{keys} stat informations if specified. @param path: the directory or file to check. @type path: C{str} @param keys: the list of desired metadata @type keys: C{list} of C{str} """ filePath = self._path(path) if filePath.isdir(): entries = filePath.listdir() fileEntries = [filePath.child(p) for p in entries] elif filePath.isfile(): entries = [os.path.join(*filePath.segmentsFrom(self.filesystemRoot))] fileEntries = [filePath] else: return defer.fail(FileNotFoundError(path)) results = [] for fileName, filePath in zip(entries, fileEntries): ent = [] results.append((fileName, ent)) if keys: try: ent.extend(self._statNode(filePath, keys)) except (IOError, OSError) as e: return errnoToFailure(e.errno, fileName) except: return defer.fail() return defer.succeed(results)
Return the list of files at given C{path}, adding C{keys} stat informations if specified. @param path: the directory or file to check. @type path: C{str} @param keys: the list of desired metadata @type keys: C{list} of C{str}
list
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
MIT
def _statNode(self, filePath, keys): """ Shortcut method to get stat info on a node. @param filePath: the node to stat. @type filePath: C{filepath.FilePath} @param keys: the stat keys to get. @type keys: C{iterable} """ filePath.restat() return [getattr(self, '_stat_' + k)(filePath) for k in keys]
Shortcut method to get stat info on a node. @param filePath: the node to stat. @type filePath: C{filepath.FilePath} @param keys: the stat keys to get. @type keys: C{iterable}
_statNode
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
MIT
def _stat_size(self, fp): """ Get the filepath's size as an int @param fp: L{twisted.python.filepath.FilePath} @return: C{int} representing the size """ return fp.getsize()
Get the filepath's size as an int @param fp: L{twisted.python.filepath.FilePath} @return: C{int} representing the size
_stat_size
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
MIT
def _stat_permissions(self, fp): """ Get the filepath's permissions object @param fp: L{twisted.python.filepath.FilePath} @return: L{twisted.python.filepath.Permissions} of C{fp} """ return fp.getPermissions()
Get the filepath's permissions object @param fp: L{twisted.python.filepath.FilePath} @return: L{twisted.python.filepath.Permissions} of C{fp}
_stat_permissions
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
MIT
def _stat_hardlinks(self, fp): """ Get the number of hardlinks for the filepath - if the number of hardlinks is not yet implemented (say in Windows), just return 0 since stat-ing a file in Windows seems to return C{st_nlink=0}. (Reference: U{http://stackoverflow.com/questions/5275731/os-stat-on-windows}) @param fp: L{twisted.python.filepath.FilePath} @return: C{int} representing the number of hardlinks """ try: return fp.getNumberOfHardLinks() except NotImplementedError: return 0
Get the number of hardlinks for the filepath - if the number of hardlinks is not yet implemented (say in Windows), just return 0 since stat-ing a file in Windows seems to return C{st_nlink=0}. (Reference: U{http://stackoverflow.com/questions/5275731/os-stat-on-windows}) @param fp: L{twisted.python.filepath.FilePath} @return: C{int} representing the number of hardlinks
_stat_hardlinks
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
MIT
def _stat_modified(self, fp): """ Get the filepath's last modified date @param fp: L{twisted.python.filepath.FilePath} @return: C{int} as seconds since the epoch """ return fp.getModificationTime()
Get the filepath's last modified date @param fp: L{twisted.python.filepath.FilePath} @return: C{int} as seconds since the epoch
_stat_modified
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
MIT
def _stat_owner(self, fp): """ Get the filepath's owner's username. If this is not implemented (say in Windows) return the string "0" since stat-ing a file in Windows seems to return C{st_uid=0}. (Reference: U{http://stackoverflow.com/questions/5275731/os-stat-on-windows}) @param fp: L{twisted.python.filepath.FilePath} @return: C{str} representing the owner's username """ try: userID = fp.getUserID() except NotImplementedError: return "0" else: if pwd is not None: try: return pwd.getpwuid(userID)[0] except KeyError: pass return str(userID)
Get the filepath's owner's username. If this is not implemented (say in Windows) return the string "0" since stat-ing a file in Windows seems to return C{st_uid=0}. (Reference: U{http://stackoverflow.com/questions/5275731/os-stat-on-windows}) @param fp: L{twisted.python.filepath.FilePath} @return: C{str} representing the owner's username
_stat_owner
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
MIT
def _stat_group(self, fp): """ Get the filepath's owner's group. If this is not implemented (say in Windows) return the string "0" since stat-ing a file in Windows seems to return C{st_gid=0}. (Reference: U{http://stackoverflow.com/questions/5275731/os-stat-on-windows}) @param fp: L{twisted.python.filepath.FilePath} @return: C{str} representing the owner's group """ try: groupID = fp.getGroupID() except NotImplementedError: return "0" else: if grp is not None: try: return grp.getgrgid(groupID)[0] except KeyError: pass return str(groupID)
Get the filepath's owner's group. If this is not implemented (say in Windows) return the string "0" since stat-ing a file in Windows seems to return C{st_gid=0}. (Reference: U{http://stackoverflow.com/questions/5275731/os-stat-on-windows}) @param fp: L{twisted.python.filepath.FilePath} @return: C{str} representing the owner's group
_stat_group
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
MIT
def _stat_directory(self, fp): """ Get whether the filepath is a directory @param fp: L{twisted.python.filepath.FilePath} @return: C{bool} """ return fp.isdir()
Get whether the filepath is a directory @param fp: L{twisted.python.filepath.FilePath} @return: C{bool}
_stat_directory
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
MIT
def openForWriting(self, path): """ Open C{path} for writing. @param path: The path, as a list of segments, to open. @type path: C{list} of C{unicode} @return: A L{Deferred} is returned that will fire with an object implementing L{IWriteFile} if the file is successfully opened. If C{path} is a directory, or if an exception is raised while trying to open the file, the L{Deferred} will fire with an error. """ p = self._path(path) if p.isdir(): # Normally, we would only check for EISDIR in open, but win32 # returns EACCES in this case, so we check before return defer.fail(IsADirectoryError(path)) try: fObj = p.open('w') except (IOError, OSError) as e: return errnoToFailure(e.errno, path) except: return defer.fail() return defer.succeed(_FileWriter(fObj))
Open C{path} for writing. @param path: The path, as a list of segments, to open. @type path: C{list} of C{unicode} @return: A L{Deferred} is returned that will fire with an object implementing L{IWriteFile} if the file is successfully opened. If C{path} is a directory, or if an exception is raised while trying to open the file, the L{Deferred} will fire with an error.
openForWriting
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
MIT
def getHomeDirectory(self, avatarId): """ Return a L{FilePath} representing the home directory of the given avatar. Override this in a subclass. @param avatarId: A user identifier returned from a credentials checker. @type avatarId: C{str} @rtype: L{FilePath} """ raise NotImplementedError( "%r did not override getHomeDirectory" % (self.__class__,))
Return a L{FilePath} representing the home directory of the given avatar. Override this in a subclass. @param avatarId: A user identifier returned from a credentials checker. @type avatarId: C{str} @rtype: L{FilePath}
getHomeDirectory
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
MIT
def getHomeDirectory(self, avatarId): """ Use C{avatarId} as a single path segment to construct a child of C{self.userHome} and return that child. """ return self.userHome.child(avatarId)
Use C{avatarId} as a single path segment to construct a child of C{self.userHome} and return that child.
getHomeDirectory
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
MIT
def getHomeDirectory(self, avatarId): """ Return the system-defined home directory of the system user account with the name C{avatarId}. """ path = os.path.expanduser('~' + avatarId) if path.startswith('~'): raise cred_error.UnauthorizedLogin() return filepath.FilePath(path)
Return the system-defined home directory of the system user account with the name C{avatarId}.
getHomeDirectory
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
MIT
def finish(): """ The producer has finished producing. """
The producer has finished producing.
finish
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
MIT
def registerProducer(self, producer, streaming): """ Register the given producer with our transport. """ self.transport.registerProducer(producer, streaming)
Register the given producer with our transport.
registerProducer
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
MIT
def unregisterProducer(self): """ Unregister the previously registered producer. """ self.transport.unregisterProducer()
Unregister the previously registered producer.
unregisterProducer
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
MIT
def decodeHostPort(line): """ Decode an FTP response specifying a host and port. @return: a 2-tuple of (host, port). """ abcdef = re.sub('[^0-9, ]', '', line) parsed = [int(p.strip()) for p in abcdef.split(',')] for x in parsed: if x < 0 or x > 255: raise ValueError("Out of range", line, x) a, b, c, d, e, f = parsed host = "%s.%s.%s.%s" % (a, b, c, d) port = (int(e) << 8) + int(f) return host, port
Decode an FTP response specifying a host and port. @return: a 2-tuple of (host, port).
decodeHostPort
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
MIT
def fail(self, error): """ Give an error to any queued deferreds. """ self._fail(error)
Give an error to any queued deferreds.
fail
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
MIT
def _fail(self, error): """ Errback all queued deferreds. """ if self._failed: # We're recursing; bail out here for simplicity return error self._failed = 1 if self.nextDeferred: try: self.nextDeferred.errback(failure.Failure(ConnectionLost('FTP connection lost', error))) except defer.AlreadyCalledError: pass for ftpCommand in self.actionQueue: ftpCommand.fail(failure.Failure(ConnectionLost('FTP connection lost', error))) return error
Errback all queued deferreds.
_fail
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
MIT
def sendLine(self, line): """ Sends a line, unless line is None. @param line: Line to send @type line: L{bytes} or L{unicode} """ if line is None: return elif isinstance(line, unicode): line = line.encode(self._encoding) basic.LineReceiver.sendLine(self, line)
Sends a line, unless line is None. @param line: Line to send @type line: L{bytes} or L{unicode}
sendLine
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
MIT
def sendNextCommand(self): """ (Private) Processes the next command in the queue. """ ftpCommand = self.popCommandQueue() if ftpCommand is None: self.nextDeferred = None return if not ftpCommand.ready: self.actionQueue.insert(0, ftpCommand) reactor.callLater(1.0, self.sendNextCommand) self.nextDeferred = None return # FIXME: this if block doesn't belong in FTPClientBasic, it belongs in # FTPClient. if ftpCommand.text == 'PORT': self.generatePortCommand(ftpCommand) if self.debug: log.msg('<-- %s' % ftpCommand.text) self.nextDeferred = ftpCommand.deferred self.sendLine(ftpCommand.text)
(Private) Processes the next command in the queue.
sendNextCommand
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
MIT
def queueCommand(self, ftpCommand): """ Add an FTPCommand object to the queue. If it's the only thing in the queue, and we are connected and we aren't waiting for a response of an earlier command, the command will be sent immediately. @param ftpCommand: an L{FTPCommand} """ self.actionQueue.append(ftpCommand) if (len(self.actionQueue) == 1 and self.transport is not None and self.nextDeferred is None): self.sendNextCommand()
Add an FTPCommand object to the queue. If it's the only thing in the queue, and we are connected and we aren't waiting for a response of an earlier command, the command will be sent immediately. @param ftpCommand: an L{FTPCommand}
queueCommand
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
MIT
def queueStringCommand(self, command, public=1): """ Queues a string to be issued as an FTP command @param command: string of an FTP command to queue @param public: a flag intended for internal use by FTPClient. Don't change it unless you know what you're doing. @return: a L{Deferred} that will be called when the response to the command has been received. """ ftpCommand = FTPCommand(command, public) self.queueCommand(ftpCommand) return ftpCommand.deferred
Queues a string to be issued as an FTP command @param command: string of an FTP command to queue @param public: a flag intended for internal use by FTPClient. Don't change it unless you know what you're doing. @return: a L{Deferred} that will be called when the response to the command has been received.
queueStringCommand
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
MIT