本文整理匯總了Python中twisted.web.server方法的典型用法代碼示例。如果您正苦於以下問題:Python web.server方法的具體用法?Python web.server怎麽用?Python web.server使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類twisted.web
的用法示例。
在下文中一共展示了web.server方法的10個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: handle_time
# 需要導入模塊: from twisted import web [as 別名]
# 或者: from twisted.web import server [as 別名]
def handle_time(self, rows):
rows = json.loads(rows)
if rows:
time_field = rows[0]['TRDTIM_1']
date_field = rows[0]['TRD_DATE']
if time_field == 'Error 17':
# this indicates the $TIME symbol is not found on the server, which is a kludge to determine the login has failed
self.force_disconnect('Gateway reports $TIME symbol unknown; connection has failed')
elif str(time_field).lower().startswith('error'):
self.error_handler(self.id, 'handle_time: time field %s' % time_field)
else:
year, month, day = [int(i) for i in date_field.split('-')[0:3]]
hour, minute, second = [int(i) for i in time_field.split(':')[0:3]]
self.feed_now = datetime.datetime(year,month,day,hour,minute,second) + datetime.timedelta(seconds=self.time_offset)
self.now = self.localize_time(self.feed_now)
# don't add time offset
if minute != self.last_minute:
self.last_minute = minute
self.WriteAllClients('time: %s %s:00' % (self.now.strftime('%Y-%m-%d'), self.now.strftime('%H:%M')))
else:
self.error_handler(self.id, 'handle_time: unexpected null input')
示例2: __init__
# 需要導入模塊: from twisted import web [as 別名]
# 或者: from twisted.web import server [as 別名]
def __init__(self):
if not hasattr(self, '_log_name'):
session_mod.Logger.__init__(name = 'server')
self._log('Initializing BaseServer.')
self.htmls = ['info', '']
self.welcome_message = (
'Hello, this is the REST service of pypath %s. Welcome!\n'
'For the descriptions of pathway resources go to `/info`.\n'
'Available query types: interactions, enz_sub, complexes, \n'
'annotations, intercell'
) % __version__
self.isLeaf = True
twisted.web.resource.Resource.__init__(self)
self._log('Twisted resource initialized.')
示例3: fix_twisted_web_server_addressToTuple
# 需要導入模塊: from twisted import web [as 別名]
# 或者: from twisted.web import server [as 別名]
def fix_twisted_web_server_addressToTuple():
"""Add ipv6 support to t.w.server._addressToTuple()
Return address.IPv6Address where appropriate.
See https://bugs.launchpad.net/ubuntu/+source/twisted/+bug/1604608
"""
import twisted.web.server
from twisted.internet import address
def new_addressToTuple(addr):
if isinstance(addr, address.IPv4Address):
return ("INET", addr.host, addr.port)
elif isinstance(addr, address.IPv6Address):
return ("INET6", addr.host, addr.port)
elif isinstance(addr, address.UNIXAddress):
return ("UNIX", addr.name)
else:
return tuple(addr)
test = address.IPv6Address("TCP", "fe80::1", "80")
try:
twisted.web.server._addressToTuple(test)
except TypeError:
twisted.web.server._addressToTuple = new_addressToTuple
示例4: verifyCallback
# 需要導入模塊: from twisted import web [as 別名]
# 或者: from twisted.web import server [as 別名]
def verifyCallback(connection, x509, errnum, errdepth, ok):
if not ok:
cslog.debug('invalid server cert: %s' % x509.get_subject())
return False
return True
示例5: getContext
# 需要導入模塊: from twisted import web [as 別名]
# 或者: from twisted.web import server [as 別名]
def getContext(self):
ctx = ssl.ClientContextFactory.getContext(self)
#TODO: replace VERIFY_NONE with VERIFY_PEER when we have
#a real server with a valid CA signed cert. If that doesn't
#work it'll be possible to use self-signed certs, if they're distributed,
#by placing the cert.pem file and location in the config and uncommenting
#the ctx.load_verify_locations line.
#As it stands this is using non-authenticated certs, meaning MITM exposed.
ctx.set_verify(SSL.VERIFY_NONE, verifyCallback)
#ctx.load_verify_locations("/path/to/cert.pem")
return ctx
示例6: setupSource
# 需要導入模塊: from twisted import web [as 別名]
# 或者: from twisted.web import server [as 別名]
def setupSource(self):
# Configure data source
# There should be just a single instance of a HTTP server service object
self.source_service = HttpServerService.create(self.settings)
# Wrap source channel settings into address object
self.source_address = ForwarderAddress(self.channel.source)
# Register URI route representing source channel
self.source_service.registerEndpoint(
methods = self.source_address.predicates,
path = self.source_address.uri.path,
callback = self.build)
示例7: dataEnqueued
# 需要導入模塊: from twisted import web [as 別名]
# 或者: from twisted.web import server [as 別名]
def dataEnqueued(self, data):
if data is None:
log.msg('Client disconnecting from server')
self.transport.loseConnection()
else:
log.msg('Queue -> Server: %s' % str(data))
self.transport.write(data)
if not data.endswith(self.delimiter):
self.transport.write(self.delimiter)
self.factory.di.to_server.get().addCallback(self.dataEnqueued)
示例8: start
# 需要導入模塊: from twisted import web [as 別名]
# 或者: from twisted.web import server [as 別名]
def start(self):
self.site = twisted.web.server.Site(self.server)
_log('Site created.')
twisted.internet.reactor.listenTCP(self.port, self.site)
_log('Server going to listen on port %u from now.' % self.port)
twisted.internet.reactor.run()
示例9: update_status
# 需要導入模塊: from twisted import web [as 別名]
# 或者: from twisted.web import server [as 別名]
def update_status(self):
#initialise status variables from config; some are updated dynamically
c = cs_single().config
source_chain = c.get("SERVER", "source_chain")
destination_chain = c.get("SERVER", "destination_chain")
minimum_amount = c.getint("SERVER", "minimum_amount")
maximum_amount = c.getint("SERVER", "maximum_amount")
serverlockrange = c.get("SERVER", "server_locktime_range")
serverlockmin, serverlockmax = [int(x) for x in serverlockrange.split(",")]
clientlockrange = c.get("SERVER", "client_locktime_range")
clientlockmin, clientlockmax = [int(x) for x in clientlockrange.split(",")]
tx01_confirm_range = c.get("SERVER", "tx01_confirm_range")
tx01_confirm_min, tx01_confirm_max = [int(
x) for x in tx01_confirm_range.split(",")]
lock0 = c.getint("TIMEOUT", "lock_client")
status = {}
self.refresh_carols()
if len(self.carols.keys()) >= c.getint("SERVER",
"maximum_concurrent_coinswaps"):
status["busy"] = True
else:
status["busy"] = False
#real-time balance query; we source only from mixdepth 0
available_funds = self.wallet.get_balance_by_mixdepth(verbose=False)[0]
#The conservativeness here (switch off if total avail < max
#is required for privacy (otherwise we leak our wallet balance in
#this costless query). Note that the wallet can be funded while
#the server is running.
if available_funds < maximum_amount:
status["busy"] = True
status["maximum_amount"] = -1
else:
status["maximum_amount"] = maximum_amount
status["minimum_amount"] = minimum_amount
status["source_chain"] = source_chain
status["destination_chain"] = destination_chain
status["cscs_version"] = cs_single().CSCS_VERSION
status["fee_policy"] = self.fee_policy.get_policy()
status["locktimes"] = {"lock_server": {"min": serverlockmin,
"max": serverlockmax},
"lock_client": {"min": clientlockmin,
"max": clientlockmax}}
status["tx01_confirm_wait"] = {"min": tx01_confirm_min,
"max": tx01_confirm_max}
status["testnet"] = True if get_network() else False
return status
示例10: _preprocess_annotations
# 需要導入模塊: from twisted import web [as 別名]
# 或者: from twisted.web import server [as 別名]
def _preprocess_annotations(self):
if 'annotations' not in self.data:
return
renum = re.compile(r'[-\d\.]+')
self._log('Preprocessing annotations.')
values_by_key = collections.defaultdict(set)
# we need to do it this way as we are memory limited on the server
# and pandas groupby is very memory intensive
for row in self.data['annotations'].itertuples():
value = (
'<numeric>'
if (
(
not isinstance(row.value, bool) and
isinstance(row.value, (int, float))
) or
renum.match(row.value)
) else
str(row.value)
)
values_by_key[(row.source, row.label)].add(value)
for vals in values_by_key.values():
if len(vals) > 1:
vals.discard('<numeric>')
vals.discard('')
vals.discard('nan')
self.data['annotations_summary'] = pd.DataFrame(
list(
(source, label, '#'.join(sorted(values)))
for (source, label), values in iteritems(values_by_key)
),
columns = ['source', 'label', 'value'],
)