本文整理汇总了Python中handler.Handler.handle方法的典型用法代码示例。如果您正苦于以下问题:Python Handler.handle方法的具体用法?Python Handler.handle怎么用?Python Handler.handle使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类handler.Handler
的用法示例。
在下文中一共展示了Handler.handle方法的8个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: main
# 需要导入模块: from handler import Handler [as 别名]
# 或者: from handler.Handler import handle [as 别名]
def main():
ops = ['list', 'info', 'create', 'get', 'update', 'create']
def msg(name=None):
return 'help message'
parser = argparse.ArgumentParser(usage=msg())
parser.add_argument('command', type=str, help='lots of help')
parser.add_argument('-f', '--file-name', type=str, help='gist file name', default=None)
parser.add_argument('-d', '--description', type=str, help='description of the gist', default=None)
parser.add_argument('-u', '--user', help='user help', default=None)
args = parser.parse_args()
try:
args.command = args.command.lower()
ops.index(args.command)
except:
didyoumean = difflib.get_close_matches(args.command, ops, 1)
if didyoumean:
print 'Did you mean: ' + didyoumean.pop() + '?'
sys.exit()
h = Handler()
print args
h.handle(args)
示例2: handle
# 需要导入模块: from handler import Handler [as 别名]
# 或者: from handler.Handler import handle [as 别名]
def handle(self):
#得到log
logging.config.fileConfig("log.conf")
log=logging.getLogger("simpleExample")
#初始化处理
cf=ConfigParser.ConfigParser()
cf.read('xb.ini')
root_data=cf.get("path","data_path")
addr=int(cf.get("host","addr"))
log.info("ROOT_DATA is %s"%root_data)
h=Handler(self.request,self.client_address,threading.current_thread(),log,root_data,addr)
log.info("{} New Client!".format(self.client_address))
#主处理程序
h.handle()
示例3: SocketHandler
# 需要导入模块: from handler import Handler [as 别名]
# 或者: from handler.Handler import handle [as 别名]
class SocketHandler(threading.Thread):
'''
Takes a socket request and delegates requests/responses to the base handler.
'''
def __init__(self, request):
self.request = request
self.handler = Handler()
self.running = False
threading.Thread.__init__(self)
def run(self):
self.sockfile = self.request[0].makefile()
self.running = True
while self.running:
json = self.get_input()
response = self.handler.handle(json, self)
self.request[0].send("%s\r\n\r\n"%response)
self.request[0].close()
def get_input(self):
json = ""
for line in self.sockfile:
if line.startswith('\r\n'):
break
json += line
return json.rstrip('\r\n')
示例4: entry
# 需要导入模块: from handler import Handler [as 别名]
# 或者: from handler.Handler import handle [as 别名]
def entry(request):
try:
if request.method == 'GET':
return HttpResponse('dfdfdfdfdf')
if request.method == 'POST':
data = request.raw_post_data
logger.debug("The request data: %s" % data)
header = {}
retCode = Packet.unpackHeader(data, header)
if retCode:
logger.debug("header: %s %s %s %s"% (header['prover'], header['protype'],
header['devicename'], header['valuelen']))
reportDataList = Packet.unpackBody(header['valuelen'], header['value'])
logger.debug("The reportDataList: %s" % reportDataList)
data = Handler.handle(header['devicename'], reportDataList)
return HttpResponse(data)
except Exception, e:
exstr = traceback.format_exc()
logger.critical("%s" % str(exstr))
示例5: entry
# 需要导入模块: from handler import Handler [as 别名]
# 或者: from handler.Handler import handle [as 别名]
def entry(request):
if request.method == 'GET':
return HttpResponse("KAO")
elif request.method == 'POST':
try:
#TODO: check MAC
#logger.info("Remote %s request" % str(request.META['REMOTE_ADDR']))
#get post data
data = request.raw_post_data;
#unpack data
#print "\n#####################\n"
#print data
#print "\n#####################\n"
header={}
retcode = Packet.unpackHeader(data,header)
if retcode:
logger.debug("header: %s %s %s %s" % \
(header['prover'],header['protype'],
header['devicename'],header['valuelen']))
reportDataList = Packet.unpackBody(header['valuelen'],header['value'])
data = Handler.handle(header['devicename'], reportDataList)
return HttpResponse(data)
else:
return HttpResponse("Bad Packet")
except Exception,e:
exstr = traceback.format_exc()
logger.critical("%s" % str(exstr))
示例6: Client
# 需要导入模块: from handler import Handler [as 别名]
# 或者: from handler.Handler import handle [as 别名]
class Client(Query):
def __init__(self):
# init Query
super(Client, self).__init__()
self.token = None
self.server_info = None
self.headers = {}
self.config = Config().get_data()
self.authentication = None
data = 'data' in self.config.keys() and self.config['data'] or None
if data:
self.hostname = 'hostname' in data.keys() and \
data['hostname'] or ''
self.sf_apikey = 'apikey' in data.keys() and \
data['apikey'] or ''
self.username = 'username' in data.keys() and \
data['username'] or ''
self.password = 'password' in data.keys() and \
data['password'] or ''
self.impersonation_username = \
'impersonation_username' in data.keys() and \
data['impersonation_username'] or ''
self.token_life_time = 'token_life_time' in data.keys() and \
data['token_life_time'] or 0
self.handler = Handler(self.config)
self.authentication = Authentication(
hostname=self.hostname,
sf_apikey=self.sf_apikey,
username=self.username,
password=self.password,
impersonation_username=self.impersonation_username)
def is_authenticated(self):
if self.token:
return True
return False
def get_server_info(self):
'''
Server information after an API call with Home as a resource
This resource should return information without extra header settings
'''
return self._get_home('Home')
def get_token(self,
ticket_username='',
resource_id='',
):
'''
Get token if self.authentication is not None, which means that the
configuration file is successfully parsed
@param ticket_username: can be any name - ticket will be issued with
this username attached
@param resource_id: ID of the resource in URL string format
e.g. "21a7a4520b75404dbc1be3b223c6612a1d"
@param minutes_to_live: number of minutes after creation that the
ticket will be valid for
'''
try:
self.token = self.authentication.get_token(
config=self.config,
ticket_username=ticket_username,
resource_id=resource_id,
minutes_to_live=self.token_life_time)
return self.token
except:
self.token = None
return self.token
def do(self, resource='', method='GET', **kwargs):
'''
Checks the availability of a access token and does the request via
the resource_dispatcher to the right resource with the correct
request-headers.
The final goal is something like:
GET /api/v1/Presentations('id1')/Presenters(id2)
@param resource: Resource name as mentioned in the API documentation
http://demo7.mediasite.com/mediasite/api/v1/$metadata
@param **kwargs: Valid keyword arguments are
properties: Properties of the resource
resource_id: resource identifier
link_id: resource_link identifier
link: dictionary, contains resource-specific
options. The resource_link itself is
a dictionary (see: CatalogSettings)
query_options: odata query_options, (e.g. $filter=)
(http://www.odata.org/documentation)
sf_apikey: string, necessary for every request in the
header, comes from the application that
uses this Client class
'''
if self.authentication:
if not self.token:
# create token with Basic access
self.headers = self.authentication.basic_header()
else:
sf_auth_ticket = self.token # authentication.get_token()
self.headers = self.authentication.authorization_ticket_header(
#.........这里部分代码省略.........
示例7: Handler
# 需要导入模块: from handler import Handler [as 别名]
# 或者: from handler.Handler import handle [as 别名]
<<<<<<< HEAD
parser.add_argument('-f', type=str, help='gist file name', default=None)
parser.add_argument('-d', type=str, help='description of the gist', default=None)
=======
parser.add_argument('-f', '--file-name', type=str, help='gist file name', default=None)
parser.add_argument('-d', '--description', type=str, help='description of the gist', default="")
>>>>>>> main/master
parser.add_argument('-u', '--user', help='user help', default=None)
parser.add_argument('-i', '--id', type=str, help='gist id', default=None)
args = parser.parse_args()
try:
args.command = args.command.lower()
ops.index(args.command)
except:
didyoumean = difflib.get_close_matches(args.command, ops, 1)
if didyoumean:
print 'Did you mean: ' + didyoumean.pop() + '?'
sys.exit()
h = Handler()
print args
h.handle(args)
if __name__ == '__main__':
main()
示例8: Bot
# 需要导入模块: from handler import Handler [as 别名]
# 或者: from handler.Handler import handle [as 别名]
class Bot(threading.Thread):
def __init__(self, master, name, conf):
threading.Thread.__init__(self)
self.starttime = time.time()
self.master = master
self.ring = self.master.bots
self.name = name
self.conf = conf
self.data = Dict()
self.log = logging.getLogger(self.name)
self.log.setLevel(logging.INFO)
self.log.addHandler(logging.handlers.RotatingFileHandler(self.name+".log", 'a', 16*1024*1024, 99))
self.log.addHandler(logging.StreamHandler(sys.__stdout__))
self.enabled = not self.conf.get('disabled', False)
self.server = IRCServer(self, self.conf['server'], self.conf['port'], self.conf.get('ssl', False))
self.event = Events(self)
self.handler = Handler(self)
self.sendqueue = queue.Queue()
self.chans = Dict()
self.users = Dict()
self.topics = Dict()
self.plugins = self.loadplugins()
def run(self):
print("Sadaharu! - @"+self.name)
self.server.handshake()
while self.server.isconnected:
try:
line = self.sendqueue.get(False)
self.server.raw(line)
self.sendqueue.task_done()
except queue.Empty:
if self.server.ready():
for line in self.server.recv():
self.handler.handle(line)
def uptime(self):
return time.time() - self.starttime
def uptime_s(self):
return str(datetime.timedelta(seconds=self.uptime()))
def mode(self, targ, *modes):
if not modes:
return
uplist = []
downlist = []
arglist = []
nextlist = []
if isinstance(modes[0], str):
modes = (modes,)
for m in modes:
if isinstance(m, str):
m = (m,)
if len(arglist) > 10:
nextlist.append(m)
continue
args = m[1:]
if len(args) == 0:
sign, cm = m[0]
{'+':uplist, '-':downlist}[sign].append(cm)
else:
for arg in m[1:]:
if len(arglist) > 10:
nextlist.append([m[0], arg])
continue
sign, cm = m[0]
{'+':uplist, '-':downlist}[sign].append(cm)
arglist.append(arg)
line = ""
if len(uplist) > 0:
line += "+%s" %(''.join(uplist),)
if len(downlist) > 0:
line += "-%s" %(''.join(downlist),)
if len(arglist) > 0:
line += " %s" %(' '.join(arglist),)
print("=mode=> "+line)
self.send("MODE", "%s %s" %(targ, line))
self.mode(targ, *nextlist)
def privmsg(self, targ, msg):
for line in str(msg).split('\n'):
self.send("PRIVMSG", "%s :%s" %(targ, line))
def notice(self, targ, msg):
for line in str(msg).split('\n'):
self.send("NOTICE", "%s :%s" %(targ, line))
def reply(self, *args):
if self.conf.get('notice', True):
return self.notice(*args)
else:
return self.privmsg(*args)
def loadplugins(self):
plugins = Dict([(p[:-3],__import__(p[:-3])) for p in os.listdir(self.master.pdir) if p.endswith(".py")])
plugincount = len(plugins)
return plugins
def reloadplugin(self, name):
#.........这里部分代码省略.........