本文整理汇总了Python中twisted.python.compat.networkString函数的典型用法代码示例。如果您正苦于以下问题:Python networkString函数的具体用法?Python networkString怎么用?Python networkString使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了networkString函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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)
开发者ID:alfonsjose,项目名称:international-orders-app,代码行数:28,代码来源:filetransfer.py
示例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)
开发者ID:alfonsjose,项目名称:international-orders-app,代码行数:57,代码来源:ls.py
示例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)
开发者ID:Acidburn0zzz,项目名称:Tor2web-3.0,代码行数:11,代码来源:t2w.py
示例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
开发者ID:Architektor,项目名称:PySnip,代码行数:7,代码来源:test_xmlrpc.py
示例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]))
开发者ID:esabelhaus,项目名称:secret-octo-dubstep,代码行数:35,代码来源:test_process.py
示例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))
开发者ID:Architektor,项目名称:PySnip,代码行数:7,代码来源:test_xmlrpc.py
示例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
开发者ID:Architektor,项目名称:PySnip,代码行数:28,代码来源:script.py
示例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
开发者ID:Architektor,项目名称:PySnip,代码行数:28,代码来源:static.py
示例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
)
开发者ID:Architektor,项目名称:PySnip,代码行数:7,代码来源:telnet.py
示例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()
开发者ID:JohnDoes95,项目名称:project_parser,代码行数:25,代码来源:session.py
示例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
开发者ID:alfonsjose,项目名称:international-orders-app,代码行数:26,代码来源:filetransfer.py
示例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
开发者ID:Architektor,项目名称:PySnip,代码行数:7,代码来源:test_xmlrpc.py
示例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
开发者ID:Cray,项目名称:buildbot,代码行数:7,代码来源:test_util_httpclientservice.py
示例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
开发者ID:nand0p,项目名称:buildbot,代码行数:7,代码来源:test_util_httpclientservice.py
示例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
开发者ID:JohnDoes95,项目名称:project_parser,代码行数:26,代码来源:memcache.py
示例16: receivedHeader
def receivedHeader(self, helo, origin, recipients):
"""
Generate a received header string for a message.
@type helo: 2-L{tuple} of (L{bytes}, L{bytes})
@param helo: The client's identity as sent in the HELO command and its
IP address.
@type origin: L{Address}
@param origin: The origination address of the message.
@type recipients: L{list} of L{User}
@param recipients: The destination addresses for the message.
@rtype: L{bytes}
@return: A received header string.
"""
authStr = heloStr = b""
if self.user:
authStr = b" auth=" + self.user.encode('xtext')
if helo[0]:
heloStr = b" helo=" + helo[0]
fromUser = (b"from " + helo[0] + b" ([" + helo[1] + b"]" +
heloStr + authStr)
by = (b"by " + self.host + b" with " + self.protocolName +
b" (" + networkString(longversion) + b")")
forUser = (b"for <" + b' '.join(map(bytes, recipients)) + b"> " +
smtp.rfc822date())
return (b"Received: " + fromUser + b"\n\t" + by +
b"\n\t" + forUser)
开发者ID:dansgithubuser,项目名称:constructicon,代码行数:30,代码来源:protocols.py
示例17: packet_EXTENDED
def packet_EXTENDED(self, data):
requestId = data[:4]
data = data[4:]
extName, extData = getNS(data)
d = defer.maybeDeferred(self.client.extendedRequest, extName, extData)
d.addCallback(self._cbExtended, requestId)
d.addErrback(self._ebStatus, requestId, networkString(
'extended %s failed' % extName))
开发者ID:alfonsjose,项目名称:international-orders-app,代码行数:8,代码来源:filetransfer.py
示例18: _realPath
def _realPath(_):
d = self.client.realPath(b'testLink')
self._emptyBuffers()
d.addCallback(
self.assertEqual,
os.path.join(
networkString(os.getcwd()), self.testDir, b'testfile1'))
return d
开发者ID:alfonsjose,项目名称:international-orders-app,代码行数:8,代码来源:test_filetransfer.py
示例19: selectGraphicRendition
def selectGraphicRendition(self, *attributes):
# each member of attributes must be a native string
attrs = []
for a in attributes:
attrs.append(networkString(a))
self.write(b'\x1b[' +
b';'.join(attrs) +
b'm')
开发者ID:JohnDoes95,项目名称:project_parser,代码行数:8,代码来源:insults.py
示例20: test_erroneousResponse
def test_erroneousResponse(self):
"""
Test that calling the xmlrpc client on a static http server raises
an exception.
"""
proxy = xmlrpc.Proxy(networkString("http://127.0.0.1:%d/" %
(self.port.getHost().port,)))
return self.assertFailure(proxy.callRemote("someMethod"), ValueError)
开发者ID:Architektor,项目名称:PySnip,代码行数:8,代码来源:test_xmlrpc.py
注:本文中的twisted.python.compat.networkString函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论