本文整理匯總了Python中router.Router類的典型用法代碼示例。如果您正苦於以下問題:Python Router類的具體用法?Python Router怎麽用?Python Router使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。
在下文中一共展示了Router類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: show
def show(ctx, path, order):
router = Router(open(ctx.obj['CONFIG']))
route = router.match(path)
logging.debug("Matched route: %s" % route)
if not route:
print 'No queries matched'
return
es = Elasticsearch(hosts=route.get('elasticsearch_url'))
request_body = {}
for non_mandatory_key in ['sort', 'query']:
value = route.get(non_mandatory_key)
if value:
request_body[non_mandatory_key] = value
if order == 'asc':
request_body['sort'] = {'@timestamp': 'asc'}
elif order == 'desc':
request_body['sort'] = {'@timestamp': 'desc'}
elif order:
click.echo("Unknown order format: %s" % order, err=True)
return 1
logging.debug("Query: %s" % (request_body,))
result = es.search(index=route.get('index'), doc_type=None, body=request_body)
hits = result['hits']['hits']
template = Template(route.get("format", "{{ __at_timestamp }} {{ message }}"))
for hit in hits:
doc = hit['_source']
doc['__at_timestamp'] = doc.get('@timestamp')
print template.render(doc)
示例2: Executor
class Executor(object):
def __init__(self,cmd,user,proto):
self.argv = shlex.split(cmd)
self.user = user
self.proto = proto
self.router = Router(self.argv[-1])
self.authobj = Authenticator(user,self.argv)
self.envobj = Env(self.user,self.router)
def execute(self):
repostring = self.argv[-1]
self.router.route()
auth_service_deferred = self.router.deferred
auth_service_deferred.addCallback(self.authobj.getRepositoryAccess)
auth_service_deferred.addCallback(self.envobj.setEnv)
# Then the result of auth is passed to execGitCommand to run git-shell
auth_service_deferred.addCallback(self.execGitCommand, self.argv, self.proto)
auth_service_deferred.addErrback(self.errorHandler, self.proto)
def execGitCommand(self, env , argv, proto):
"""After all authentication is done, setup an environment and execute the git-shell commands."""
repopath = self.router.repopath
sh = self.user.shell
command = ' '.join(argv[:-1] + ["'{0}'".format(repopath)])
reactor.spawnProcess(proto, sh, (sh, '-c', command), env=env)
def errorHandler(self, fail, proto):
"""Catch any unhandled errors and send the exception string to the remote client."""
fail.trap(ConchError)
message = fail.value.value
log.err(message)
if proto.connectionMade():
proto.loseConnection()
error_script = self.user.error_script
reactor.spawnProcess(proto, error_script, (error_script, message))
示例3: test_router
def test_router(net, land):
from router import Router
net.init_flows()
print 'edges'
pprint([(edge, str(edge)) for edge in net.edges])
path = Router.find_shortest_path(net, 0, net.nodes[1], net.nodes[6])
print 'path 1 - 6'
pprint(path)
path = Router.find_shortest_path(net, 0, net.nodes[6], net.nodes[1])
print 'path 6 - 1'
pprint(path)
paths = Router.find_shortest_path(net, 0, net.nodes[1])
print 'paths 1 - *'
pprint(paths)
paths = Router.find_shortest_path(net, 0, net.nodes[100])
print 'paths 100 - *'
pprint(paths)
router = Router(net, land)
print 'building shortest paths...'
router.build_shortest_paths()
# logger.debug(pformat(dict(router.paths)))
path = router.get_shortest_path(0, 100, 100)
print 'path 100 - 100'
pprint(path)
path = router.get_shortest_path(0, 100, 200)
print 'path 100 - 200'
pprint(path)
path = router.get_shortest_path(0, 100, 600)
print 'path 100 - 600'
pprint(path)
return router
示例4: test2
def test2(self):
r = Router()
r.route(Rule("/pages/<int:page_id>/"), target="pages")
matches = r.matches("/pages/10/")
m = matches.next()
self.assertEqual(m.param("target"), "pages")
self.assertEqual(m.param("page_id"), 10)
示例5: Handler
class Handler(BaseHTTPServer.BaseHTTPRequestHandler):
def __init__(self, request, client_address, server):
self.router = Router(self)
for key, value in ROUTES.items():
self.router.add(key, value)
BaseHTTPServer.BaseHTTPRequestHandler.__init__(self, request, client_address, server)
def do_HEAD(self):
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers()
def do_GET(self):
if self.path.startswith('/'):
self.path = self.path[1:]
routing_info = self.router.route(self.path)
if routing_info:
func, regex_match = routing_info
content = func(**regex_match)
self.do_HEAD()
self.wfile.write(content)
else:
self.send_error(404)
def do_POST(self):
form = cgi.FieldStorage(
fp=self.rfile,
headers=self.headers,
environ={'REQUEST_METHOD':'POST',
'CONTENT_TYPE':self.headers['Content-Type'],
})
# Begin the response
self.send_response(200)
self.end_headers()
self.wfile.write('Client: %s\n' % str(self.client_address))
self.wfile.write('User-agent: %s\n' % str(self.headers['user-agent']))
self.wfile.write('Path: %s\n' % self.path)
self.wfile.write('Form data:\n')
# Echo back information about what was posted in the form
for field in form.keys():
field_item = form[field]
if field_item.filename:
# The field contains an uploaded file
file_data = field_item.file.read()
file_len = len(file_data)
del file_data
self.wfile.write('\tUploaded %s as "%s" (%d bytes)\n' % \
(field, field_item.filename, file_len))
else:
# Regular form value
self.wfile.write('\t%s=%s\n' % (field, form[field].value))
return
示例6: test_hashing
def test_hashing(self):
router = Router(self.valid_list_file)
router.set('forge', 13)
router.set("spawning_pool", 18)
key_hash, connection_uri = router.continuum.get_server('forge')
self.assertEqual(key_hash, 4113771093)
self.assertEqual(connection_uri, '127.0.0.1:6379')
key_hash, connection_uri = router.continuum.get_server('spawning_pool')
self.assertEqual(key_hash, 1434709819)
self.assertEqual(connection_uri, '127.0.0.1:6380')
示例7: load
def load():
configer = Configer('../config.ini')
log_info = configer.get_configer('LOG','info')
log_path = configer.get_configer('LOG','path')
log_format = '%(asctime)s - %(name)s - %(levelname)s - %(filename)s - %(funcName)s - %(message)s'
logger = Logger(info = log_info,path = log_path,format = log_format)
LOG = logger.get_logger()
router = Router(1,'InterThread')
router.start()
示例8: run
def run(connection, data):
request = RequestBuilder.build(data)
function = Router.get_function(request.path)
static = Router.get_static(request.path)
print request.path
if function is not None:
try:
Processor._send_function_result(connection, request, function)
except Exception as e:
Processor._send_500(connection, str(e))
elif static is not None:
Processor._send_file(connection, request, static)
else:
Processor._send_404(connection)
connection.close()
示例9: __init__
def __init__(self, config):
self.config = config
self.data_port = config['port']
self.command_port = config['commandport']
self.sniff_port = config['sniffport']
self.name = config.get('name', str(self.command_port))
self.refdes = config.get('refdes', config['type'])
self.ttl = config['ttl']
self.data_name = 'port-agent'
self.command_name = 'command-port-agent'
self.sniffer_name = 'sniff-port-agent'
self.data_port_id = '%s-%s' % (self.data_name, self.refdes)
self.command_port_id = '%s-%s' % (self.command_name, self.refdes)
self.sniffer_port_id = '%s-%s' % (self.sniffer_name, self.refdes)
self.router = Router()
self.connections = set()
self.clients = set()
self._register_loggers()
self._create_routes()
self._start_servers()
self._heartbeat()
self.num_connections = 0
log.msg('Base PortAgent initialization complete')
示例10: __init__
def __init__(self,cmd,user,proto):
self.argv = shlex.split(cmd)
self.user = user
self.proto = proto
self.router = Router(self.argv[-1])
self.authobj = Authenticator(user,self.argv)
self.envobj = Env(self.user,self.router)
示例11: main
def main():
"""Runs the gateway"""
loop = asyncio.get_event_loop()
router = Router()
loop.run_until_complete(router.connect_to_message_queue())
initialize_gpio()
radio = Radio()
router.set_send_packet(radio.send_packet)
poll(loop, radio, router)
try:
loop.run_forever()
finally:
loop.close()
示例12: test1
def test1(self):
r = Router()
r.route(Rule("/blaat/"), target="0")
r.route(Rule("/home/"), target="1")
r.route(Rule("/news/"), target="2")
r.route(Rule("/home/"), target="3")
matches = r.matches("/home/")
self.assertEqual(matches.next().param("target"), "1")
self.assertEqual(matches.next().param("target"), "3")
示例13: __init__
def __init__(self, protocols, uri='ws://173.255.213.55:9093/ws?'):
super(ArdyhClient, self).__init__(uri, protocols)
self.ARDYH_URI = uri
self.LOG_DTFORMAT = "%Y-%m-%dT%H:%M:%SZ"
self.channel = settings['bot_name']
self.bot_name = settings['bot_name']
self.bot_roles = settings['bot_roles']
self.router = Router(self)
示例14: __init__
def __init__(self, max_forks=0, prespawn=False, homogeneous=True):
"""
max_forks: The maximum number of forks (default: 0 - unlimited)
prespawn: Spawns and feeds forks before processing begins.
homogeneous: Attempt to keep forks limited to one pattern
"""
Router.__init__(self)
self.max_forks = max_forks
self.prespawn = prespawn
self.homogeneous = homogeneous
self.pattern_assignments = {}
self.forks = []
self.data = {}
self.processing = False
示例15: __init__
def __init__(self, catchall=True, autojson=True, config=None):
self.routes = Router()
self._logger=None
self.mounts = {}
self.error_handler = {}
self.catchall = catchall
self.config = config or {}
self.serve = True
self.castfilter = []
if autojson and dumps:
self.add_filter(dict, dumps)