本文整理汇总了Python中twisted.python.compat.networkString函数的典型用法代码示例。如果您正苦于以下问题:Python networkString函数的具体用法?Python networkString怎么用?Python networkString使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了networkString函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _ebStatus
def _ebStatus(self, reason, requestId, msg = b"request failed"):
code = FX_FAILURE
message = msg
if isinstance(reason.value, (IOError, OSError)):
if reason.value.errno == errno.ENOENT: # no such file
code = FX_NO_SUCH_FILE
message = networkString(reason.value.strerror)
elif reason.value.errno == errno.EACCES: # permission denied
code = FX_PERMISSION_DENIED
message = networkString(reason.value.strerror)
elif reason.value.errno == errno.EEXIST:
code = FX_FILE_ALREADY_EXISTS
else:
log.err(reason)
elif isinstance(reason.value, EOFError): # EOF
code = FX_EOF
if reason.value.args:
message = networkString(reason.value.args[0])
elif isinstance(reason.value, NotImplementedError):
code = FX_OP_UNSUPPORTED
if reason.value.args:
message = networkString(reason.value.args[0])
elif isinstance(reason.value, SFTPError):
code = reason.value.code
message = networkString(reason.value.message)
else:
log.err(reason)
self._sendStatus(requestId, code, message)
示例2: lsLine
def lsLine(name, s):
"""
Build an 'ls' line for a file ('file' in its generic sense, it
can be of any type).
"""
mode = s.st_mode
perms = array.array('B', b'-'*10)
ft = stat.S_IFMT(mode)
if stat.S_ISDIR(ft): perms[0] = ord('d')
elif stat.S_ISCHR(ft): perms[0] = ord('c')
elif stat.S_ISBLK(ft): perms[0] = ord('b')
elif stat.S_ISREG(ft): perms[0] = ord('-')
elif stat.S_ISFIFO(ft): perms[0] = ord('f')
elif stat.S_ISLNK(ft): perms[0] = ord('l')
elif stat.S_ISSOCK(ft): perms[0] = ord('s')
else: perms[0] = ord('!')
# user
if mode&stat.S_IRUSR:perms[1] = ord('r')
if mode&stat.S_IWUSR:perms[2] = ord('w')
if mode&stat.S_IXUSR:perms[3] = ord('x')
# group
if mode&stat.S_IRGRP:perms[4] = ord('r')
if mode&stat.S_IWGRP:perms[5] = ord('w')
if mode&stat.S_IXGRP:perms[6] = ord('x')
# other
if mode&stat.S_IROTH:perms[7] = ord('r')
if mode&stat.S_IWOTH:perms[8] = ord('w')
if mode&stat.S_IXOTH:perms[9] = ord('x')
# suid/sgid
if mode&stat.S_ISUID:
if perms[3] == ord('x'): perms[3] = ord('s')
else: perms[3] = ord('S')
if mode&stat.S_ISGID:
if perms[6] == ord('x'): perms[6] = ord('s')
else: perms[6] = ord('S')
lsresult = [
perms.tostring(),
networkString(str(s.st_nlink)).rjust(5),
b' ',
networkString(str(s.st_uid)).ljust(9),
networkString(str(s.st_gid)).ljust(9),
networkString(str(s.st_size)).rjust(8),
b' ',
]
# need to specify the month manually, as strftime depends on locale
ttup = localtime(s.st_mtime)
sixmonths = 60 * 60 * 24 * 7 * 26
if s.st_mtime + sixmonths < time(): # last edited more than 6mo ago
strtime = strftime("%%s %d %Y ", ttup)
else:
strtime = strftime("%%s %d %H:%M ", ttup)
lsresult.append(networkString(strtime % (_MONTH_NAMES[ttup[1]],)))
lsresult.append(name)
return b''.join(lsresult)
示例3: getRequestHostname
def getRequestHostname(self):
"""
Function overload to fix ipv6 bug:
http://twistedmatrix.com/trac/ticket/6014
"""
host = self.getHeader(b'host')
if host:
if host[0]=='[':
return host.split(']',1)[0] + "]"
return networkString(host.split(':', 1)[0])
return networkString(self.getHost().host)
示例4: proxy
def proxy(self, factory=None):
p = xmlrpc.Proxy(networkString("http://127.0.0.1:%d" % self.port))
if factory is None:
p.queryFactory = self.queryFactory
else:
p.queryFactory = factory
return p
示例5: _writeTest
def _writeTest(self, write):
"""
Helper for testing L{IProcessTransport} write functionality. This
method spawns a child process and gives C{write} a chance to write some
bytes to it. It then verifies that the bytes were actually written to
it (by relying on the child process to echo them back).
@param write: A two-argument callable. This is invoked with a process
transport and some bytes to write to it.
"""
reactor = self.buildReactor()
ended = Deferred()
protocol = _ShutdownCallbackProcessProtocol(ended)
bytesToSend = b"hello, world" + networkString(os.linesep)
program = (
b"import sys\n"
b"sys.stdout.write(sys.stdin.readline())\n"
)
def startup():
transport = reactor.spawnProcess(
protocol, pyExe, [pyExe, b"-c", program])
try:
write(transport, bytesToSend)
except:
err(None, "Unhandled exception while writing")
transport.signalProcess('KILL')
reactor.callWhenRunning(startup)
ended.addCallback(lambda ignored: reactor.stop())
self.runReactor(reactor)
self.assertEqual(bytesToSend, b"".join(protocol.received[1]))
示例6: createServer
def createServer(self, resource):
self.p = reactor.listenTCP(
0, server.Site(resource), interface="127.0.0.1")
self.addCleanup(self.p.stopListening)
self.port = self.p.getHost().port
self.proxy = xmlrpc.Proxy(
networkString('http://127.0.0.1:%d' % self.port))
示例7: render
def render(self, request):
"""
Render me to a web client.
Load my file, execute it in a special namespace (with 'request' and
'__file__' global vars) and finish the request. Output to the web-page
will NOT be handled with print - standard output goes to the log - but
with request.write.
"""
request.setHeader(b"x-powered-by", networkString("Twisted/%s" % copyright.version))
namespace = {'request': request,
'__file__': _coerceToFilesystemEncoding("", self.filename),
'registry': self.registry}
try:
execfile(self.filename, namespace, namespace)
except IOError as e:
if e.errno == 2: #file not found
request.setResponseCode(http.NOT_FOUND)
request.write(resource.NoResource("File not found.").render(request))
except:
io = NativeStringIO()
traceback.print_exc(file=io)
output = util._PRE(io.getvalue())
if _PY3:
output = output.encode("utf8")
request.write(output)
request.finish()
return server.NOT_DONE_YET
示例8: _doSingleRangeRequest
def _doSingleRangeRequest(self, request, startAndEnd):
"""
Set up the response for Range headers that specify a single range.
This method checks if the request is satisfiable and sets the response
code and Content-Range header appropriately. The return value
indicates which part of the resource to return.
@param request: The Request object.
@param startAndEnd: A 2-tuple of start of the byte range as specified by
the header and the end of the byte range as specified by the header.
At most one of the start and end may be C{None}.
@return: A 2-tuple of the offset and size of the range to return.
offset == size == 0 indicates that the request is not satisfiable.
"""
start, end = startAndEnd
offset, size = self._rangeToOffsetAndSize(start, end)
if offset == size == 0:
# This range doesn't overlap with any of this resource, so the
# request is unsatisfiable.
request.setResponseCode(http.REQUESTED_RANGE_NOT_SATISFIABLE)
request.setHeader(
b'content-range', networkString('bytes */%d' % (self.getFileSize(),)))
else:
request.setResponseCode(http.PARTIAL_CONTENT)
request.setHeader(
b'content-range', self._contentRange(offset, size))
return offset, size
示例9: welcomeMessage
def welcomeMessage(self):
"""Override me to return a string which will be sent to the client
before login."""
x = self.factory.__class__
return networkString("\r\n" + x.__module__ + '.' + x.__name__ +
'\r\nTwisted %s\r\n' % copyright.version
)
示例10: processEnded
def processEnded(self, reason=None):
"""
When we are told the process ended, try to notify the other side about
how the process ended using the exit-signal or exit-status requests.
Also, close the channel.
"""
if reason is not None:
err = reason.value
if err.signal is not None:
signame = self._getSignalName(err.signal)
if (getattr(os, 'WCOREDUMP', None) is not None and
os.WCOREDUMP(err.status)):
log.msg('exitSignal: %s (core dumped)' % (signame,))
coreDumped = 1
else:
log.msg('exitSignal: %s' % (signame,))
coreDumped = 0
self.session.conn.sendRequest(self.session, b'exit-signal',
common.NS(networkString(signame[3:])) +
chr(coreDumped) + common.NS(b'') + common.NS(b''))
elif err.exitCode is not None:
log.msg('exitCode: %r' % (err.exitCode,))
self.session.conn.sendRequest(self.session, b'exit-status',
struct.pack('>L', err.exitCode))
self.session.loseConnection()
示例11: _packAttributes
def _packAttributes(self, attrs):
flags = 0
data = b''
if 'size' in attrs:
data += struct.pack('!Q', attrs['size'])
flags |= FILEXFER_ATTR_SIZE
if 'uid' in attrs and 'gid' in attrs:
data += struct.pack('!2L', attrs['uid'], attrs['gid'])
flags |= FILEXFER_ATTR_OWNERGROUP
if 'permissions' in attrs:
data += struct.pack('!L', attrs['permissions'])
flags |= FILEXFER_ATTR_PERMISSIONS
if 'atime' in attrs and 'mtime' in attrs:
data += struct.pack('!2L', attrs['atime'], attrs['mtime'])
flags |= FILEXFER_ATTR_ACMODTIME
extended = []
for k in attrs:
if k.startswith('ext_'):
ext_type = NS(networkString(k[4:]))
ext_data = NS(attrs[k])
extended.append(ext_type+ext_data)
if extended:
data += struct.pack('!L', len(extended))
data += b''.join(extended)
flags |= FILEXFER_ATTR_EXTENDED
return struct.pack('!L', flags) + data
示例12: test_authInfoInURL
def test_authInfoInURL(self):
url = "http://%s:%[email protected]:%d/" % (
nativeString(self.user), nativeString(self.password), self.port)
p = xmlrpc.Proxy(networkString(url))
d = p.callRemote("authinfo")
d.addCallback(self.assertEqual, [self.user, self.password])
return d
示例13: render_GET
def render_GET(self, request):
data = json.dumps(request.args)
request.setHeader(b"content-type", networkString("application/json"))
request.setHeader(b"content-length", intToBytes(len(data)))
if request.method == b"HEAD":
return b""
return data
示例14: render_GET
def render_GET(self, request):
data = json.dumps(request.args)
request.setHeader(b'content-type', networkString('application/json'))
request.setHeader(b'content-length', intToBytes(len(data)))
if request.method == b'HEAD':
return b''
return data
示例15: _set
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