def POST(self, service): username = authenticate_user(web) # If username is None: return wsse_auth error for DIR in [RAWPOSTDATA_DIR, CACHE_DIR]: if os.path.isdir(DIR) == False: os.makedirs(DIR) post_file = shareonline._save_post_data(web.data(), RAWPOSTDATA_DIR, username + '-request') contentfile_name = os.path.basename(post_file) #contentfile_body = os.path.splitext(post_file)[0] data = shareonline._parse_request_xml(web.data()) if 'filedata' in data: if 'filetype' in data: content_filepath = get_filename(post_file, data) with open(content_filepath, 'wb') as f: f.write(data['filedata']) del data['filedata'] print data else: # read original post print data post = os.path.join(RAWPOSTDATA_DIR, data['uid']) with open(post, 'rb') as f: postdata = f.read() data = shareonline._parse_request_xml(postdata) del data['filedata'] web.header('Content-Type', 'application/atom+xml; charset=UTF-8') data['id'] = contentfile_name data['link'] = "/entry/" + contentfile_name #print data entry_xml = shareonline.create_entry(data) #print entry_xml web.Created() shareonline._save_post_data(entry_xml, RAWPOSTDATA_DIR, username + '-response') return entry_xml
def default_post(self, name): # default name is 'timedata' #result = {} print 'name:', name print web.ctx.query, '4444444444' print web.data(), '3eeeeeeeeeee' querydata = self.query_to_value() postdata = self.json_loads(web.data()) print querydata, postdata, '111111111111' a = time.localtime(time.time()) hour, minute, second = a[3], a[4], a[5] currentsecond = '%02d:%02d:%02d' % (hour, minute, second) #currentsecond = 'test' if self._citydict.get(currentsecond, ' ') == ' ': self._citydict[currentsecond] = {} for each in postdata: if self._citydict[currentsecond].get(each, ' ') == ' ': self._citydict[currentsecond][each] = postdata[each] else: self._citydict[currentsecond][each] += postdata[each] print self._citydict, '5555555555555' #if name != 'otherspost': # for each in self._totalservicelist: # post_service_data(each['host'], each['port'], 'otherspost', web.data()) return {'result' : '0'}
def POST(self): print web.input() print web.data() params=web.input() openid=params.openid if hasattr(params, "openid") else "" data=web.data() root = xml.etree.ElementTree.XML(data) toUserName= root.findall("ToUserName") fromUserName= root.findall("FromUserName") content= root.findall("Content") retXml=u""" <xml> <ToUserName><![CDATA[%s]]></ToUserName> <FromUserName><![CDATA[%s]]></FromUserName> <CreateTime>%d</CreateTime> <MsgType><![CDATA[text]]></MsgType> <Content><![CDATA[%s]]></Content> </xml> """ retXml=retXml % (fromUserName[0].text,toUserName[0].text,int(round(time.time())),content[0].text) print retXml.encode("utf-8") return retXml
def POST(self): if not web.data(): raise web.BadRequest global scheduler data = json.loads(web.data()) function = None date = datetime.strptime(data["date"], "%d/%m/%Y %H:%M:%S") task_type = data["task_type"] if task_type == TaskType.ARM_ALARM: function = arm_alarm elif task_type == TaskType.DISARM_ALARM: function = disarm_alarm elif task_type == TaskType.TURN_ON_HEATING: function = turn_on_heating elif task_type == TaskType.TURN_OFF_HEATING: function = turn_off_heating # if the date has already occurred or no function has been selected if date <= datetime.now() or function is None: return web.badrequest() else: scheduler.add_task(function, date, task_type)
def parse_action_impl(self, action, table, db): if action == 'add_user_message': user_id = self.qs_dict.get('user_id') if not user_id: set_status_code(web, 400) return result_template('''Illegal parameters: no "user_id"''') user_id = ''.join(user_id) if debug: web.debug('DB action=add_user_message, user_id=%s' % (user_id)) data = web.data() db.add_user_message(user_id, data) return '' elif action == 'get_user_message': user_id = self.qs_dict.get('user_id') if not user_id: set_status_code(web, 400) return result_template('''Illegal parameters: no "user_id"''') user_id = ''.join(user_id) if debug: web.debug('DB action=get_user_message, user_id=%s' % (user_id)) data = db.get_user_message(user_id) return message_template(user_id, data) elif action == 'remove_user_message': user_id = self.qs_dict.get('user_id') if not user_id: set_status_code(web, 400) return result_template('''Illegal parameters: no "user_id"''') user_id = ''.join(user_id) if debug: web.debug('DB action=get_user_message, user_id=%s' % (user_id)) data = web.data() list1 = json.loads(data); db.remove_user_message(user_id, list1, web) return ''
def POST(self): try: rawdata = json.loads(web.data()) except ValueError as e: raise self.error("Unparseable JSON input \n %s"%web.data()) # step 1: prepare the data data = self.prepare_input_data(rawdata) # step 2: search matches = self.search(data) # step 3: Check auth try: auth_header = http_basic_auth() self.login(auth_header) except accounts.ClientException: raise self.auth_failed("Invalid credentials") # step 4: create if logged in keys = [] if auth_header: keys = self.create(matches) # step 4: format the result d = self.format_result(matches, auth_header, keys) return json.dumps(d)
def POST(self, name): """Add titles to an existing work""" logger.debug("Data: %s" % (web.data())) data = json.loads(web.data()) title = data.get('title') work_id = data.get('UUID') or data.get('uuid') try: titles = strtolist(title) assert titles and work_id except AssertionError as error: logger.debug(error) raise Error(BADPARAMS, msg="You must provide a (work) UUID" + " and at least a title") try: work = Work(work_id, titles=titles) assert work.exists() except: raise Error(BADPARAMS, msg="Unknown work '%s'" % (work_id)) work.save() work.load_titles() work.load_identifiers() return [work.__dict__]
def POST(self): request = None config.read(config_file) try: dpctl_command = config.get("main", "dpctl_command") except Exception as e: pass try: request = cjson.decode(web.data()) except Exception as e: logger.debug("PROBLEM: %s: %s" % (e.__str__(), web.data())) return "PROBLEM: ", e.__str__() try: result = OSCARSRequestHandler(None, request).handle() except Exception as e: logger.error(e.__str__()) return e.__str__() web.header('Content-Type', 'application/json') return result
def POST(self, name, ext): if not corpora.has_key(name): yield web.notfound() return try: c = corpora[name]['reader'] params = web.input() offset = int(params.get('start', '0')) # Do we want to highlight something? if params.has_key('markerQuery') and params.has_key('markerAttr') and params.has_key('markerValue'): markerQueries = [alpinocorpus.MarkerQuery(params['markerQuery'].encode('utf-8'), params['markerAttr'], params['markerValue'])] else: markerQueries = [] # Was a query provided? if params.has_key('query'): gen = c.queryWithStylesheet(params['query'].encode('utf-8'), web.data(), markerQueries, _timeout) else: gen = c.entriesWithStylesheet(web.data(), markerQueries, _timeout) for i in self.run(gen, ext, True, offset): yield i except: print sys.exc_info() yield web.internalerror()
def POST(self): try: tid_value = web.input()['tid'] except KeyError: return web.BadRequest() try: team_id = cfg['TEAM_ID_DICT'][tid_value.upper()] except KeyError: return web.Unauthorized() if len(web.data()) == 0: return web.BadRequest() data = simplejson.loads(web.data()) # json validation good, errors = IssueValidator().validate(data) if not good: return errors r = requests.post(''.join(['http://', cfg['REMOTE_HOST'], '/pp']), data=simplejson.dumps({'tid': str(team_id), 'iid': data['ID']})) if r.status_code != 200: print 'Call remote server failed...' print r.text api = WxApi(cfg['CORP_ID'], cfg['SECRET']) api.send_text(self.build_msg(data), team_id, 0, '@all') return web.OK('ok')
def POST(self): fromNum=re.findall('(?<=From=%2B1)(.*)(?=&ApiVersion=)', web.data())[0] verification_code=db.query('SELECT verification_code FROM users WHERE id=' + str(session.get('id')))[0]['verification_code'] if not verification_code==1: message = client.messages.create(body="Sorry bud, you haven't verified this number yet!", to="+1" + fromNum, # Replace with your phone number from_="+16103475899") # Replace with your Twilio number else: response = twiml.Response() #body = request.form['Body'] msg=re.findall('(?<=&Body=)(.*)(?=&FromCountry)', web.data())[0] account_sid="" auth_token="" client = TwilioRestClient(account_sid, auth_token) #from http://stackoverflow.com/a/8768241 regex_date='^(?:(?:(?:0?[13578]|1[02])(\/|-|\.)31)\1|(?:(?:0?[1,3-9]|1[0-2])(\/|-|\.)(?:29|30)\2))(?:(?:1[6-9]|[2-9]\d)?\d{2})$|^(?:0?2(\/|-|\.)29\3(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00))))$|^(?:(?:0?[1-9])|(?:1[0-2]))(\/|-|\.)(?:0?[1-9]|1\d|2[0-8])\4(?:(?:1[6-9]|[2-9]\d)?\d{2})' #from http://stackoverflow.com/a/7536768 regex_time='([0-9]|0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]' msg_date=re.findall(regex_date, msg)[0] msg_time=re.findall(regex_time, msg)[0] msg_description=re.findall("(?<=[0-9]:[0-9][0-9] )(.*)", msg)[0] message = client.messages.create(body="I've set your schedule for " + msg_date + " at " + msg_time + " for " + msg_description, to="+1" + fromNum, # Replace with your phone number from_="+") # Replace with your Twilio number print message.sid
def POST(self): options = web.input(_method='get') options = {'semantics' : 'drg'} drg, _ = run(web.data(), ['tokenizer', 'soap_client', 'boxer'], options) png(drg.split('\n')[:-2], TMPPNG) log.info('[drg] {}'.format(web.data())) return open(TMPPNG,"rb").read()
def POST(self): ops = json.loads(web.data()) if web.data() == "-1": web.header('Content-Type', 'application/json') return json.dumps(list(DBA.getAllItems())) else: web.header('Content-Type', 'application/json') return json.dumps(DBA.getItem(web.data()))
def POST(self): import logging logger = logging.getLogger() logger.debug(str(web.data())) from application.msgservice import MsgService msgservice = MsgService() msgservice.sendMessage(str(web.data())) return ""
def POST(self): data = web.data() data = json.loads(web.data()) print "New commit by: {}".format(data['commits'][0]['author']['name']) print "Time: {}".format(data['commits'][0]['timestamp']) print "Message: {}".format(data['commits'][0]['message']) print data['ref'] return 'OK'
def POST(self): if len(web.data()) == 0: raise Exception('No data') req = web.data() color = _color_from_hex(req) action.add(color) return {}
def POST(self): if not web.data(): raise web.BadRequest data = json.loads(web.data()) if "heating_on" in data: global heating_on heating_on = data["heating_on"]
def PUT(self, game_id): game_id = int(game_id) if (len(web.data()) > 0): # TODO(david): parse based on Content-Type req = json.loads(web.data()) if ('cube' in req): # TODO(david): validate that the new cube state is legal games.game(game_id)['cube'] = req['cube'] return { RESULT: games.game(game_id) }
def _POST(self, key, forceful=False): if forceful: self.datastore.set_value_in_all(str(key), web.data()) else: self.datastore.set_value(str(key), web.data()) web.created() location = "".join([web.ctx.home, _url_formatter(str(key))]) web.header("Location", location) return {"message": location}
def POST(self, params): try: if params.startswith('statuses/update.'): web.ctx.data = self.update_filter(web.data()) return BaseProxy.POST(self, params) except Exception, why: import traceback logger.error("%s %s %s" % (params, str(why), web.data())) logger.error(traceback.format_exc()) web.internalerror()
def request(self, isPost): print("visit:" + web.ctx.path) print("req param:" + web.data()) get_input = web.ctx.query print("raw get input:"+get_input) path = web.ctx.path data = web.data() print("rawData:"+data) web.header('Content-Type', mimetypes.guess_type(path)[0]) return self.serveLocal(path)
def POST(self): cookie = web.cookies() print cookie.get("name") print cookie.get("age") print cookie.get("gendor") print "this is a POST response for /test" print web.data() print web.input().get("name") print web.input().get("age") return 200, "ok"
def POST(self): web.header('Content-Type', 'application/json') data = web.input() data["contentType"] = web.ctx.env["CONTENT_TYPE"] if data["contentType"] == "application/json": data["json"] = json.loads(web.data()) else: data["pars"] = web.data() data["method"] = "POST" return json.dumps(data)
def PUT(self): global current_command, last_result HIGH='[1;31m' LOW='[0;32m' NORMAL='[0;30m' i = web.data() pl = readPlistFromString(i) # print i print "%sReceived %4d bytes: %s" % (HIGH, len(web.data()), NORMAL), if pl.get('Status') == 'Idle': print HIGH + "Idle Status" + NORMAL rd = current_command print "%sSent: %s%s" % (HIGH, rd['Command']['RequestType'], NORMAL) # print HIGH, rd, NORMAL elif pl.get('MessageType') == 'TokenUpdate': print HIGH+"Token Update"+NORMAL rd = do_TokenUpdate(pl) print HIGH+"Device Enrolled!"+NORMAL elif pl.get('Status') == 'Acknowledged': print HIGH+"Acknowledged"+NORMAL rd = dict() else: rd = dict() if pl.get('MessageType') == 'Authenticate': print HIGH+"Authenticate"+NORMAL elif pl.get('MessageType') == 'CheckOut': print HIGH+"Device leaving MDM"+ NORMAL else: print HIGH+"(other)"+NORMAL print HIGH, pl, NORMAL log_data(pl) log_data(rd) out = writePlistToString(rd) # print LOW, out, NORMAL q = pl.get('QueryResponses') if q: redact_list = ('UDID', 'BluetoothMAC', 'SerialNumber', 'WiFiMAC', 'IMEI', 'ICCID', 'SerialNumber') for resp in redact_list: if q.get(resp): pl['QueryResponses'][resp] = '--redacted--' for top in ('UDID', 'Token', 'PushMagic', 'UnlockToken'): if pl.get(top): pl[top] = '--redacted--' last_result = pprint.pformat(pl) return out
def POST(self): if not self.auth_check(): return self.render().login() web.header("Content-Type", "application/json") try: pass post = json.loads(web.data()) return json2db.insertbodymass(session.uid, web.data()) except: return '{"error": 1}'
def POST(self): form=self.flow_form() data=process_webdata(web.data()) save_data("FlowCurve",data) print web.data();print data #debugging line if data["Submit"]=="home": raise web.seeother("/home") elif not form.validates(): return render.flow(form) elif data["Submit"]=="submit": return render.flow(form)
def input(*requireds, **defaults): i = web.input(*requireds, **defaults) content_type = web.ctx.env.get('CONTENT_TYPE') if web.data(): if content_type is None or content_type.find('json') != -1: try: json_input = json.loads(web.data()) except ValueError: raise web.NotAcceptable() i.update(json_input) return i
def put_task(self): parameters = web.input(_method='GET') if not "id" in parameters or not web.data(): raise web.BadRequest() # Find out username username = None try: if re.search("^[-_a-zA-Z0-9]{3,30}$", parameters["username"]): username = parameters["username"] except KeyError: pass data = db.select("task, service", what="username, service_id, name", where="task.id = $id and service.id = service_id", vars={"id": parameters["id"]})[0] # Create output file path = os.path.join(data_directory, data["name"]) mkdirp(path) fileobj = tempfile.NamedTemporaryFile(dir=path, delete=False) fileobj.write(web.data()) fileobj.close() data_file = os.path.relpath(fileobj.name, data_directory) # Mark task as finished t = db.transaction() count = db.update("task", "id = $id AND status = 'assigned' AND ip_address = $ip", vars = {"id": parameters["id"], "ip": web.ctx.ip}, status="finished", timestamp=int(time.time()), ip_address=None, username=username, data_file=data_file ) # If task was not properly assigned, we get 0 changed rows if count != 1: t.rollback() raise web.Conflict() # Update statistics if username: count = db.update("statistics", "username = $username AND service_id = $service_id", data, count=web.SQLLiteral("count + 1")) if count == 0: db.insert("statistics", username=data["username"], service_id=data["service_id"], count=1) db.update("service", "id = $service_id", data, finished_tasks_count = web.SQLLiteral("finished_tasks_count + 1")) t.commit() return ""
def LOG(method,message = None,_myuuid = uuid.uuid1()): if method == "info": data = web.ctx http_method = data["method"] + " " http_method = http_method[0:6] message = " %s %s %s %s%s" % (_myuuid,http_method,data["ip"],data["realhome"],data["fullpath"]) logger.info(message) if web.data(): message = "%s DATA %s" % (_myuuid,web.data()) logger.debug(message) elif method == "return": message = "%s RETURN %s" % (_myuuid,message) logger.debug(message)
def default_post(self, name): print web.data(), '111111111111111111111111111111111', web.data()[0], web.data()[1] tempdata = json.loads(web.data()) print tempdata, 'bbbbbbbbbbbbbbb' info = {} info['host'] = web.ctx.environ['REMOTE_ADDR'] info['port'] = tempdata[1] if info['host'] + '_' + info['port'] not in self._serviceset: self._servicelist.append(info) self._serviceset.add(info['host'] + '_' + info['port']) print self._servicelist, '222222222222222222222222222222222' return {'result' : '0'}
def get_post(web): rawdata = str(web.data())[2:-1] return parse_qs(rawdata)
def POST(self, name): web.header('Access-Control-Allow-Origin', '*') web.header('Access-Control-Allow-Credentials', 'true') data = web.data() return {'message': "POST OK! %s" % data}
def POST(self): """ List all replicas for data identifiers. HTTP Success: 200 OK HTTP Error: 401 Unauthorized 406 Not Acceptable 500 InternalError :returns: A dictionary containing all replicas information, either as JSON stream or metalink4. """ metalink = False if ctx.env.get('HTTP_ACCEPT') is not None: tmp = ctx.env.get('HTTP_ACCEPT').split(',') if 'application/metalink4+xml' in tmp: metalink = True client_ip = ctx.env.get('HTTP_X_FORWARDED_FOR') if client_ip is None: client_ip = ctx.ip dids, schemes, select, unavailable, limit = [], None, None, False, None ignore_availability, rse_expression, all_states, domain = False, None, False, None signature_lifetime, resolve_archives, resolve_parents = None, True, False client_location = {} json_data = data() try: params = parse_response(json_data) if 'dids' in params: dids = params['dids'] if 'schemes' in params: schemes = params['schemes'] if 'unavailable' in params: unavailable = params['unavailable'] ignore_availability = True if 'all_states' in params: all_states = params['all_states'] if 'rse_expression' in params: rse_expression = params['rse_expression'] if 'client_location' in params: client_location = params['client_location'] client_location['ip'] = params['client_location'].get( 'ip', client_ip) if 'sort' in params: select = params['sort'] if 'domain' in params: domain = params['domain'] if 'resolve_archives' in params: resolve_archives = params['resolve_archives'] if 'resolve_parents' in params: resolve_parents = params['resolve_parents'] if 'signature_lifetime' in params: signature_lifetime = params['signature_lifetime'] else: # hardcoded default of 10 minutes if config is not parseable signature_lifetime = config_get('credentials', 'signature_lifetime', raise_exception=False, default=600) except ValueError: raise generate_http_error(400, 'ValueError', 'Cannot decode json parameter list') if ctx.query: params = parse_qs(ctx.query[1:]) if 'select' in params: select = params['select'][0] if 'limit' in params: limit = params['limit'][0] if 'sort' in params: select = params['sort'] # Resolve all reasonable protocols when doing metalink for maximum access possibilities if metalink and schemes is None: schemes = supported_protocols try: # we need to call list_replicas before starting to reply # otherwise the exceptions won't be propagated correctly __first = True # then, stream the replica information for rfile in list_replicas(dids=dids, schemes=schemes, unavailable=unavailable, request_id=ctx.env.get('request_id'), ignore_availability=ignore_availability, all_states=all_states, rse_expression=rse_expression, client_location=client_location, domain=domain, signature_lifetime=signature_lifetime, resolve_archives=resolve_archives, resolve_parents=resolve_parents, issuer=ctx.env.get('issuer')): # in first round, set the appropriate content type, and stream the header if __first: if not metalink: header('Content-Type', 'application/x-json-stream') else: header('Content-Type', 'application/metalink4+xml') yield '<?xml version="1.0" encoding="UTF-8"?>\n<metalink xmlns="urn:ietf:params:xml:ns:metalink">\n' __first = False if not metalink: yield dumps(rfile, cls=APIEncoder) + '\n' else: replicas = [] dictreplica = {} for replica in rfile['pfns'].keys(): replicas.append(replica) dictreplica[replica] = ( rfile['pfns'][replica]['domain'], rfile['pfns'][replica]['priority'], rfile['pfns'][replica]['rse'], rfile['pfns'][replica]['client_extract']) yield ' <file name="' + rfile['name'] + '">\n' if 'parents' in rfile and rfile['parents']: yield ' <parents>\n' for parent in rfile['parents']: yield ' <did>' + parent + '</did>\n' yield ' </parents>\n' yield ' <identity>' + rfile['scope'] + ':' + rfile[ 'name'] + '</identity>\n' if rfile['adler32'] is not None: yield ' <hash type="adler32">' + rfile[ 'adler32'] + '</hash>\n' if rfile['md5'] is not None: yield ' <hash type="md5">' + rfile['md5'] + '</hash>\n' yield ' <size>' + str(rfile['bytes']) + '</size>\n' yield ' <glfn name="/%s/rucio/%s:%s"></glfn>\n' % ( config_get( 'policy', 'schema', raise_exception=False, default='generic'), rfile['scope'], rfile['name']) # TODO: deprecate this if select == 'geoip': replicas = sort_geoip(dictreplica, client_location['ip']) elif select == 'closeness': replicas = sort_closeness(dictreplica, client_location) elif select == 'dynamic': replicas = sort_dynamic(dictreplica, client_location) elif select == 'ranking': replicas = sort_ranking(dictreplica, client_location) elif select == 'random': replicas = sort_random(dictreplica) else: replicas = sorted(dictreplica, key=dictreplica.get) idx = 0 for replica in replicas: yield ' <url location="' + str(dictreplica[replica][2]) \ + '" domain="' + str(dictreplica[replica][0]) \ + '" priority="' + str(dictreplica[replica][1]) \ + '" client_extract="' + str(dictreplica[replica][3]).lower() \ + '">' + replica + '</url>\n' idx += 1 if limit and limit == idx: break yield ' </file>\n' # don't forget to send the metalink footer if metalink: yield '</metalink>\n' except DataIdentifierNotFound as error: raise generate_http_error(404, 'DataIdentifierNotFound', error.args[0]) except RucioException as error: raise generate_http_error(500, error.__class__.__name__, error.args[0]) except Exception as error: print(format_exc()) raise InternalError(error)
def POST(self): plugin_manager = PluginManager() task = plugin_manager.add_install_plugin_task(json.loads(web.data())) return TaskHandler.render(task)
def POST(self,*args,**kwargs): data = web.data().decode('gbk') print(data)
def POST(self, name=None): """Create a new event""" data = json.loads(web.data()) return save_event(data)
def POST(self, param): str = web.data().decode() print(str) data = json.loads(str) web.model.test_single_image(args, data) return '200 OK'
def POST(): """ Send a POST request with id/nic/interval/filter/iters and it will start a container for collection with those specifications """ web.header('Content-Type', 'application/json') # verify payload is in the correct format data = web.data() payload = {} try: payload = ast.literal_eval(data) except Exception as e: # pragma: no cover # !! TODO parse out url parms... return 'malformed payload: ' + str(e) # payload should have the following fields: # - id # - nic # - interval # - filter # - iters # should spin up a tcpdump container that writes out pcap files based # on the filter needs to be attached to the nic specified, if iters is # -1 then loops until killed, otherwise completes iters number of # captures (and creates that many pcap files) should keep track of # container id, container name, and id of filter and filter + whatever # else is in payload in redis # verify payload has necessary information if 'nic' not in payload: return 'payload missing nic' if 'id' not in payload: return 'payload missing id' if 'interval' not in payload: return 'payload missing interval' if 'filter' not in payload: return 'payload missing filter' if 'iters' not in payload: return 'payload missing iters' # connect to redis if 'metadata' in payload: r = None try: r = redis.StrictRedis(host='redis', port=6379, db=0) except Exception as e: # pragma: no cover return (False, 'unable to connect to redis because: ' + str(e)) if r: r.hmset(payload['id'], ast.literal_eval(payload['metadata'])) # connect to docker c = None try: c = docker.from_env() except Exception as e: # pragma: no cover return (False, 'unable to connect to docker because: ' + str(e)) # spin up container with payload specifications if c: tool_d = { "network_mode": "host", "volumes_from": [socket.gethostname()] } cmd = '/tmp/run.sh ' + payload['nic'] + ' ' + payload['interval'] cmd += ' ' + payload['id'] + ' ' + payload['iters'] + ' ' cmd += payload['filter'] try: container_id = c.containers.run( image='cyberreboot/vent-ncapture:master', command=cmd, detach=True, **tool_d) except Exception as e: # pragma: no cover return (False, 'unable to start container because: ' + str(e)) return (True, 'successfully created and started filter ' + str(payload['id']) + ' on container: ' + str(container_id))
def POST(self): print web.data() no_data = [] plt.clf() data = web.data() query_data = json.loads(data) start_time = query_data["start_time"] end_time = query_data["end_time"] if query_data["ct_id"] is not None: ct_ids = [int(x) for x in query_data["ct_id"]] else: ct_ids = [] if query_data["node_id"] is not None: node_ids = [int(x) for x in query_data["node_id"]] else: node_ids = [] if query_data["jplug_id"] is not None: jplug_ids = query_data["jplug_id"] else: jplug_ids = [] idx_smart = (smart_meter_data.index > start_time) & (smart_meter_data.index < end_time) smart_meter_power = smart_meter_data[idx_smart] x_smart_meter = [ datetime.datetime.fromtimestamp(x - OFFSET) for x in smart_meter_data.index[idx_smart] ] y_smart_meter = smart_meter_power.values count = 0 with lock: fig = plt.gcf() # get current figure ax1 = plt.subplot(1, 1, 1) ax1.set_title('Electricity meter') ax1.set_ylabel('Real power (W)') ax1.plot(x_smart_meter, y_smart_meter) count = 1 for ct_id in ct_ids: ct_required = ct_data[ct_data.id == ct_id].current idx_ct = (ct_required.index > start_time) & (ct_required.index < end_time) ct_current = ct_required[idx_ct] x_ct = [ datetime.datetime.fromtimestamp(x - OFFSET) for x in ct_current.index ] y_ct = ct_current.values if len(y_ct) == 0: no_data.append("ct%d" % ct_id) else: with lock: n = len(fig.axes) for i in range(n): fig.axes[i].change_geometry(n + 1, 1, i + 1) ax = fig.add_subplot(n + 1, 1, n + 1, sharex=ax1) ax.set_title('MCB # %d' % ct_id) ax.set_ylabel('Current (A)') ax.plot(x_ct, y_ct) '''Light''' for node_id in node_ids: idx_light_temp = (light_temp_data.index > start_time) & (light_temp_data.index < end_time) df = light_temp_data[idx_light_temp] y_light = df[df["node"] == node_id].light.values idx = y_light > 0 y_light = y_light[idx] x_light = [ datetime.datetime.fromtimestamp(x - OFFSET) for x in df[df["node"] == node_id][idx].index ] if len(y_light) == 0: no_data.append("light%d" % node_id) else: with lock: n = len(fig.axes) for i in range(n): fig.axes[i].change_geometry(n + 1, 1, i + 1) ax = fig.add_subplot(n + 1, 1, n + 1, sharex=ax1) ax.plot(x_light, y_light) ax.set_ylabel('Light') ax.set_title('Light node #%d' % node_id) '''Temp''' for node_id in node_ids: y_temp = df[df["node"] == node_id].temp.values idx = y_temp > 0 y_temp = y_temp[idx] x_temp = [ datetime.datetime.fromtimestamp(x - OFFSET) for x in df[df["node"] == node_id][idx].index ] if len(y_temp) == 0: no_data.append("temp%d" % node_id) else: with lock: n = len(fig.axes) for i in range(n): fig.axes[i].change_geometry(n + 1, 1, i + 1) ax = fig.add_subplot(n + 1, 1, n + 1, sharex=ax1) ax.plot(x_temp, y_temp) ax.set_ylabel('Temperature (F)') ax.set_title('Temperature node #%d' % node_id) '''Presence''' for node_id in node_ids: idx_pir = (pir_data.index > start_time) & (pir_data.index < end_time) df_pir = pir_data[idx_pir] df_pir = df_pir[df_pir["node"] == node_id] y_pir = [1] * len(df_pir.index.values) x_pir = [ datetime.datetime.fromtimestamp(x - OFFSET) for x in df_pir.index.values ] if len(x_pir) == 0: no_data.append("pir%d" % node_id) else: with lock: n = len(fig.axes) for i in range(n): fig.axes[i].change_geometry(n + 1, 1, i + 1) ax = fig.add_subplot(n + 1, 1, n + 1, sharex=ax1) ax.plot(x_pir, y_pir, 'o') ax.set_ylabel('Presence') ax.set_title('PIR node #%d' % node_id) '''jplug''' for jplug_id in jplug_ids: idx_jplug = (jplug_data.index > start_time) & (jplug_data.index < end_time) df = jplug_data[idx_jplug] y_jplug = df[df["jplug_id"] == jplug_id]["real"].values x_jplug = [ datetime.datetime.fromtimestamp(x - OFFSET) for x in df[df["jplug_id"] == jplug_id].index.values ] if len(y_jplug) == 0: no_data.append("jplug %s" % jplug_id) else: with lock: n = len(fig.axes) for i in range(n): fig.axes[i].change_geometry(n + 1, 1, i + 1) ax = fig.add_subplot(n + 1, 1, n + 1, sharex=ax1) ax.plot(x_jplug, y_jplug) ax.set_title('jPlug Power consumption for %s' % jplug_id) ax.set_ylabel('Power (W)') with lock: filename = randomword(12) + ".jpg" figure = plt.gcf() figure.autofmt_xdate() figure.set_size_inches(6, len(fig.axes) * 2) plt.tight_layout() plt.savefig("static/images/" + filename, bbox_inches=0, dpi=100) plt.close() web.header('Content-Type', 'application/json') return json.dumps({"filename": filename, "no_data": no_data})
def restore_main(tenant_id, job_id): ''' Process a RESTORE command ''' data = {} if "no data" in job_id: data['status'] = 'error_msg: no job_id given' elif not isPosInt(job_id): data['status'] = 'error_msg: job_id ' + job_id + ' is not valid' else: cmd_str = "snappy_db_utils/does_snappy_jobid_exist " + job_id job_exists_str = subprocess.check_output(cmd_str.split()).strip() if len(job_exists_str) > 0: cmd_str = "snappy_db_utils/get_jobtype_from_jobid " + job_id jobtype = subprocess.check_output(cmd_str.split()).strip() if "export" in jobtype: cmd_str = "snappy_db_utils/get_src_image_from_jobid " + job_id image_id = subprocess.check_output(cmd_str.split()).strip() ### Restore to a diffrent volume if (len(web.data()) > 0): is_valid, restore_type, restore_id = verify_restore_data() # print("is_valid = " + is_valid) # print("restore_type = " + restore_type) # print("restore_id = " + restore_id) if ("input valid" not in is_valid): return is_valid return_str = '{"status":"restore to a different volume"}' # check to see if this restore_type is supported cmd_str = "builder_utils/get_src_id_from_sp_name " + restore_type restore_type_valid = subprocess.check_output( cmd_str.split()).strip() # print("restore_type_valid = " + restore_type_valid) # print("len = " + str(len(restore_type_valid))) if (len(restore_type_valid) == 0): return '{"status":"error: restore_type <' + restore_type + '> is not supported"}' # check to see if Authorization is needed # and if so, if the creditials are correct auth = web.ctx.env.get('HTTP_AUTHORIZATION') if is_authorized_basic(tenant_id, auth) is False: web.header('WWW-Authenticate', 'Basic realm="Snappy Frontend"') web.ctx.status = '401 Unauthorized' return '{"status":"ERROR: Authentication failed for tenant <' + tenant_id + '>"}' # check that the volume <restore_id> exists (the volume we are restoring to) cmd_str = "openstack_db_utils/does_rbd_volume_exist.py " + restore_id id_exists = subprocess.check_output(cmd_str.split()) if (id_exists.strip() == "false"): return_txt = '{"status":"ERROR: Cannot restore to ' + restore_type return_txt += ' volume <' + restore_id + '> since it does not exist"}' return return_txt # get the size of <restore_id> (the volume we are restoring to) cmd_str = "openstack_db_utils/get_rbd_size_in_bytes.py " + restore_id restore_volume_size = subprocess.check_output( cmd_str.split()).strip() # print("restore_volume_size = " + restore_volume_size) # get the allocated size of the backed up volume cmd_str = "snappy_db_utils/get_alloc_size_from_jobid " + job_id alloc_size = subprocess.check_output( cmd_str.split()).strip() # print("alloc_size = " + alloc_size) # check that the size <restore_id> is >= allocated size if int(restore_volume_size) < int(alloc_size): return_str = '{"status":"ERROR: Not enough space. Backup is ' + alloc_size return_str += ' bytes but volume to restore to is only ' + restore_volume_size + ' bytes."}' return return_str data['restore_to_volume_id'] = restore_id # Restore to a volume that is not the original one cmd_str = "./restore_to_different_volume " cmd_str += restore_id + " " cmd_str += job_id + " " cmd_str += restore_type # print("cmd_str = " + cmd_str) new_job_id_str = subprocess.check_output(cmd_str.split()) else: # TODO: first make sure that the original volume still exists cmd_str = "openstack_db_utils/does_rbd_volume_exist.py " + image_id rbd_vol_exists = subprocess.check_output(cmd_str.split()) if "true" in rbd_vol_exists: # Restore back to the original volume cmd_str = "./restore_to_original_volume " + image_id + " " + job_id new_job_id_str = subprocess.check_output( cmd_str.split()) else: return_str = '{"status":"ERROR: Request to restore job <' + job_id return_str += '> to the orignal RBD volume <' + image_id return_str += '>, but it does not exist"}' return return_str status_str = 'error_msg: the RBD volume to restore to <' status_str += image_id + '> does not exist' data['status'] = status_str # clean up the output new_job_id_str = new_job_id_str.split("\n", 1)[-1].strip("\n") data['status'] = 'Restore submitted' data['restore_from_job_id'] = job_id data['image_id'] = image_id data['job_id'] = new_job_id_str else: status_str = 'error_msg: job ' + job_id status_str += ' is type ' + jobtype status_str += '. It must be an export.' data['status'] = status_str else: data['status'] = 'error_msg: job ' + job_id + ' does not exist' return_txt = json.dumps(data) return return_txt
def verify_add_data(): ''' Make sure than the POST data was passed in as valid JSON and the required data is included: (full_interval, count) ''' # default values count = "1" full_interval = "604800" # 1 week delta_interval = "0" sourcetype = "rbd" sourceid = "123456789" result = '{"status":"input valid"}' # If there's no data passed into this command, we'll catch it here. # This can happen if a Restore command was sent but there was # no job_id given in the URL, since it'll be interpreted as an Add if (len(web.data()) == 0): return_str = '{"status":"ERROR: Data has length 0"}' return return_str, "-1", "-1", "-1", "-1", "-1" # The data was not in JSON format try: item_dict = json.loads(web.data()) except: return_str = '{"status":"ERROR: valid JSON not found in POST data"}' return return_str, sourcetype, sourceid, count, full_interval, delta_interval # Get the full_interval info try: full_interval = item_dict["full_interval"] except KeyError: return_str = '{"status":"ERROR: field <full_interval> not found in POST data"}' return return_str, sourcetype, sourceid, count, full_interval, delta_interval if is_int(full_interval) is False or int(full_interval) < 1: return_str = '{"status":"ERROR: <full_interval> is not a positive integer (' + full_interval + ')"}' return return_str, sourcetype, sourceid, count, full_interval, delta_interval # Get the delta_interval info (this field is not required) try: delta_interval = item_dict["delta_interval"] if is_int(delta_interval) is False or int(delta_interval) < 1: return_str = '{"status":"ERROR: <delta_interval> is not a positive integer (' + delta_interval + ')"}' return return_str, sourcetype, sourceid, count, full_interval, delta_interval except KeyError: pass # Get the count info try: count = item_dict["count"] except KeyError: return_str = '{"status":"ERROR: <count> not found in POST data"}' return return_str, sourcetype, sourceid, count, full_interval, delta_interval if is_int(count) is False or int(count) < 1: return_str = '{"status":"ERROR: <count> is not a positive integer (' + count + ')"}' return return_str, sourcetype, sourceid, count, full_interval, delta_interval try: sourcetype = item_dict["source_type"] except KeyError: return_str = '{"status":"ERROR: <source_type> not found in POST data"}' return return_str, sourcetype, sourceid, count, full_interval, delta_interval try: sourceid = item_dict["source_id"] except KeyError: return_str = '{"status":"ERROR: <source_id> not found in POST data"}' return return_str, sourcetype, sourceid, count, full_interval, delta_interval return result, sourcetype, sourceid, count, full_interval, delta_interval
def POST(self): print("Reporting Parameters") raw_data = web.data() data = json.loads(raw_data) server.db.SaveParameters(data)
def POST(self): data = web.data() print data r = json.loads(data) if r['req_str'].find("spam")>=0: return "spam" return "ok"
def POST(self, account): """ create account with given account name. HTTP Success: 201 Created HTTP Error: 400 Bad Reqeust 401 Unauthorized 409 Conflict 500 Internal Error :param Rucio-Account: Account identifier. :param Rucio-Auth-Token: as an 32 character hex string. :params Rucio-Type: the type of the new account. """ json_data = data().decode() try: parameter = loads(json_data) except ValueError: raise generate_http_error( 400, 'ValueError', 'cannot decode json parameter dictionary') type, email = None, None try: type = parameter['type'] except KeyError as error: if error.args[0] == 'type': raise generate_http_error(400, 'KeyError', '%s not defined' % str(error)) except TypeError: raise generate_http_error(400, 'TypeError', 'body must be a json dictionary') try: email = parameter['email'] except KeyError as error: if error.args[0] == 'email': raise generate_http_error(400, 'KeyError', '%s not defined' % str(error)) except TypeError: raise generate_http_error(400, 'TypeError', 'body must be a json dictionary') try: add_account(account, type, email, issuer=ctx.env.get('issuer'), vo=ctx.env.get('vo')) except Duplicate as error: raise generate_http_error(409, 'Duplicate', error.args[0]) except AccessDenied as error: raise generate_http_error(401, 'AccessDenied', error.args[0]) except RucioException as error: raise generate_http_error(500, error.__class__.__name__, error.args[0]) except Exception as error: print(format_exc()) raise InternalError(error) raise Created()
def POST(self): try: webData = web.data() print "Handle Post webdata is ", webData #后台打日志 recMsg = receive.parse_xml(webData) # accessToken = self.basic.get_access_token() # print accessToken if isinstance(recMsg, receive.Msg) and recMsg.MsgType == 'text': toUser = recMsg.FromUserName fromUser = recMsg.ToUserName content = recMsg.Content print content reString = r' ' results = re.split(re.compile(reString), content) if results[0] == "歌曲": if len(results) == 2 and results[1]: muiscName = results[1] if isinstance(muiscName, unicode): muiscName = muiscName.encode('utf-8') print muiscName sql = "select * from music where `musicName` like %s limit 5;" args = ('%s%%' % muiscName) musicList = self.dao.launchSQL(sql, args) content = "" i = 0 if musicList: for row in musicList: i = i + 1 musicName = row[2] artist = row[3] url = row[4] pwd = row[5] try: content = content + "歌曲名:%s\n歌手:%s\n百度云盘下载地址:\n%s\n密码:%s\n\n" % (musicName.encode("utf-8"), artist.encode("utf-8"), url.encode("utf-8"), pwd.encode("utf-8")) except Exception as e: print e if i == 0: content = "不好意思程序员有点菜,没找到这首歌!" replyMsg = reply.TextMsg(toUser, fromUser, content) return replyMsg.send() else: print content replyMsg = reply.TextMsg(toUser, fromUser, content) return replyMsg.send() elif results[0] == "歌手": if len(results) >= 2 and results[1]: artist = results[1] if len(results) == 3 and results[2]: try: page = int(results[2]) start = (page-1)*5+1 end = 5 sql = "select * from music where `artist` like '%s%%' "; sql = sql % artist sql = sql + "limit %d, %d;" % (start, end) return self.getMusic(toUser, fromUser,sql) except Exception as e: print e musicName = results[2] sql = "select * from music where `artist` like '%s%%' "; sql = sql % artist sql = sql + "and `musicName` like '%s%%';" % musicName return self.getMusic(toUser, fromUser,sql) if len(results) == 4 and results[2] == "歌曲" and results[3]: musicName = results[3] sql = "select * from music where `artist` like '%s%%' "; sql = sql % artist sql = sql + "and `musicName` like '%s%%';" % musicName return self.getMusic(toUser, fromUser,sql) else: sql = "select * from music where `artist` like %s limit 5;" args = ('%s%%' % artist) return self.getMusic(toUser, fromUser,sql, args) else: reString = r'https' results = re.match(re.compile(reString), content) if results: page = self.spider.GET(content) #print page results = self.spider.getInstagramAsset(page) i = 0 content = "" for m in results: content = content + m.group(1) + "\n" i = i + 1 reString = r'<meta property="og:video" content="(.*?)" />' results = self.spider.getInstagramAsset(page, None, reString) for m in results: content = content + m.group(1) + "\n" i = i + 1 if i == 0: content = "对不起,程序猿比较菜,没有找到该资源!" print content else: print content replyMsg = reply.TextMsg(toUser, fromUser, content) return replyMsg.send() else: content = self.robot.getRobotReply(fromUser, content) print content #content = "嗨,这么巧的!" replyMsg = reply.TextMsg(toUser, fromUser, content) return replyMsg.send() elif isinstance(recMsg, receive.Msg) and recMsg.MsgType == 'image': toUser = recMsg.FromUserName fromUser = recMsg.ToUserName mediaId = recMsg.MediaId replyMsg = reply.ImageMsg(toUser, fromUser, mediaId) return replyMsg.send() else: print "暂且不处理" return "success" except Exception, Argment: return Argment
def POST(self): global g_listPlayers, g_stFansNumber, g_dictOrderToPlayer, g_stAdminNumber try: webData = web.data() print "Handle Post webdata is ", webData # 后台打日志 recMsg = receive.parse_xml(webData) if isinstance(recMsg, receive.Msg) and recMsg.MsgType == 'text': # 默认最后的文本需要编码 boolNeedEncode = True strShow = u"" strToUser = recMsg.FromUserName strFromUser = recMsg.ToUserName strUserWord = recMsg.Content if (strUserWord == 'Leo'): strShow = u"Leo 超帅" ''' # revote boolEnable 指令可以让发送者成为管理员 if strUserWord == "revote boolEnable": admin_number_set.add(strToUser) strShow = u"Revote Enable" # revote disable 指令可以让发送者的管理员身份失效 elif strUserWord == "revote disable": if strToUser in admin_number_set: admin_number_set.remove(strToUser) strShow = u"Rovote Disable" ''' # 检测是否为管理员 if strToUser in g_stAdminNumber: # 修改选手名字:alter [strOrderNum] [strName] if strUserWord.startswith("alter"): strShow = u"alter\n" listProcess = strUserWord.split() # 获取要更改的 player ,将其对应的 strName 改变 strOrderNum = listProcess[1] strName = listProcess[2] player = g_dictOrderToPlayer[strOrderNum] # 更新 数据 player.strName = strName # 增加选手:add [strOrderNum] [strName] elif strUserWord.startswith("add"): strShow = u"add\n" listProcess = strUserWord.split() # 获取要添加的 player 和对应的 strOrderNum strOrderNum = listProcess[1] strName = listProcess[2] # 更新 数据 if strOrderNum not in g_listOrderNums: g_listOrderNums.append(strOrderNum) newPlayer = Player() newPlayer.strName = strName newPlayer.intVotes = 0 g_listPlayers.append(newPlayer) g_dictOrderToPlayer[strOrderNum] = newPlayer else: strShow = u"该号数已经存在" # 删除选手:del [strOrderNum] elif strUserWord.startswith("del"): strShow = u"del\n" listProcess = strUserWord.split() # 获取要删除的 nickname strOrderNum = listProcess[1] if strOrderNum in g_listOrderNums: g_listOrderNums.remove(strOrderNum) strName = g_dictOrderToPlayer[strOrderNum] g_listPlayers.remove(strName) del g_dictOrderToPlayer[strOrderNum] # 修改票数:votec [order_name] [intVotes] elif strUserWord.startswith("votec"): strShow = u"votec\n" listProcess = strUserWord.split() # 获取要修改票数的 nickname 和对应的 intVotes strOrderNum = listProcess[1] intVotes = int(listProcess[2]) # 更新 数据 player = g_dictOrderToPlayer[strOrderNum] player.intVotes = intVotes # 复位票数和已投票粉丝: elif strUserWord.startswith("reset"): init_all_data() # 立即存储数据 elif strUserWord.startswith("saveall"): save_data() # 投票检验 # elif strUserWord.startswith("toupiao"): # strOrderNum = strUserWord[8:] # if strOrderNum in g_listOrderNums: elif re_all_num.search(strUserWord): if strUserWord in g_listOrderNums: player = g_dictOrderToPlayer[strUserWord] player.intVotes += 1 strShow = u"已经成功投给%s号选手%s!\n" % (strUserWord, player.strName) else: strShow = u"没有这个号数的选手哦(⊙□⊙)\n" # 展示投票结果 for strOrderNum in g_listOrderNums: player = g_dictOrderToPlayer[strOrderNum] strShow += u"%s号,%s得票数为:%d" % ( strOrderNum, player.strName, player.intVotes) if g_listOrderNums[-1] != strOrderNum: strShow += "\n" # 其他文本交给机器人 else: strShow = robot_talk(strUserWord, strFromUser[0:15]) boolNeedEncode = False # 非管理员处理 else: # 投票处理 if re_all_num.search(strUserWord): # 检测该非管理员人员是否已经投票 if strToUser in g_stFansNumber: strShow = u"您已经投过票,谢谢参与!(*´▽`* )\n" # 投票检验 else: if strUserWord in g_listOrderNums: g_stFansNumber.add(strToUser) player = g_dictOrderToPlayer[strUserWord] player.intVotes += 1 strShow = u"已经成功投给%s号选手%s!\n" % ( strUserWord, player.strName) else: strShow = u"没有这个号数的选手哦(⊙□⊙)\n" # 展示投票结果 for strOrderNum in g_listOrderNums: player = g_dictOrderToPlayer[strOrderNum] strShow += u"%s号,%s得票数为:%d" % ( strOrderNum, player.strName, player.intVotes) if g_listOrderNums[-1] != strOrderNum: strShow += "\n" # 其他文本交给机器人 else: strShow = robot_talk(strUserWord, strFromUser[0:15]) boolNeedEncode = False if len(strShow) == 0: return "" # 格式化最终字符串 if boolNeedEncode: strContent = strShow.encode('utf-8') else: strContent = strShow replyMsg = reply.TextMsg(strToUser, strFromUser, strContent) # save_data() return replyMsg.send() elif isinstance(recMsg, receive.EventMsg): if recMsg.Event == 'CLICK': if recMsg.Eventkey == 'mpGuide': content = u"编写中,尚未完成".encode('utf-8') # replyMsg = reply.TextMsg(toUser, fromUser, content) # return replyMsg.send() else: print "暂且不处理" return "" except Exception, Argment: # return Argment return ""
def fuckpost(): return web.data()
def POST(self): print("Reporting data 203") raw_data=web.data() data=json.loads(raw_data) cloudserver.db.ReportOSData(data) return "203 OK"
def POST(self): try: webData = web.data() print "Handle Post webdata is ", webData recMsg = receive.parse_xml(webData) if isinstance(recMsg, receive.Msg): toUser = recMsg.FromUserName fromUser = recMsg.ToUserName if recMsg.MsgType == 'event': event = recMsg.Event if event == 'subscribe': replyMsg = reply.TextMsg( toUser, fromUser, '欢迎订阅【在路上随风走】,回复“功能介绍”可查看功能简介噢,对了,在这还可以和机器人语音聊天呢,更多精彩就等你自己探索啦!' ) return replyMsg.send() if recMsg.MsgType == 'text': content = recMsg.Content if content == '电台' or content == 'fm' or content == 'Fm' or content == 'FM': replyMsg = reply.FmMsg(toUser, fromUser) return replyMsg.send() if content == '糗百' or content == '糗事百科' or content == '臭事百科' or content == '丑事百科': word = joke.Joke() replyMsg = reply.TextMsg(toUser, fromUser, word) return replyMsg.send() if content == '段子' or content == '内涵段子' or content == '内涵段子手': word = joke.Duanzi() replyMsg = reply.TextMsg(toUser, fromUser, word) return replyMsg.send() if content == '搞笑图片' or content == '内涵图片' or content == '内涵图': word = joke.Pic() replyMsg = reply.TextMsg(toUser, fromUser, word) return replyMsg.send() if content == '成绩单' or content == '成绩' or content == '查成绩' or content == '成绩查询': word = '把链接复制到浏览器中查询速度更快(⊙o⊙)哦'+'\n' + \ 'http://sundae.applinzi.com/signin' replyMsg = reply.TextMsg(toUser, fromUser, word) return replyMsg.send() if content == '动机院公告' or content == '动机院' or content == '武大动机' or content == '动力与机械学院': word = joke.WhuPmc() replyMsg = reply.TextMsg(toUser, fromUser, word) return replyMsg.send() if content == '机电学院' or content == '北理机电' or content == '机电学院公告': word = joke.BitSmen() replyMsg = reply.TextMsg(toUser, fromUser, word) return replyMsg.send() if content[0:4] == 'send' or content[0:4] == 'Send': txt = content[5:-1] + content[-1] word = qqzone.Send(txt) replyMsg = reply.TextMsg(toUser, fromUser, word) return replyMsg.send() if content[0:5] == 'train' or content[0:5] == 'Train': txt = content[6:-1] + content[-1] word = train.train(txt) replyMsg = reply.TextMsg(toUser, fromUser, word) return replyMsg.send() if content[0:5] == 'morse' or content[ 0:5] == 'Morse' or content[0:5] == 'MORSE': txt = content[6:-1] + content[-1] word = morse.morse(txt) replyMsg = reply.TextMsg(toUser, fromUser, word) return replyMsg.send() if content[0:2] == 'm0' or content[0:2] == 'M0': txt = content[3:-1] + content[-1] word = morse.morse(txt) replyMsg = reply.TextMsg(toUser, fromUser, word) return replyMsg.send() if content[0:6] == 'umorse' or content[ 0:6] == 'Umorse' or content[0:6] == 'UMORSE': txt = content[7:-1] + content[-1] word = morse.umorse(txt) replyMsg = reply.TextMsg(toUser, fromUser, word) return replyMsg.send() if content[0:3] == 'um0' or content[ 0:3] == 'Um0' or content[0:2] == 'UM0': txt = content[4:-1] + content[-1] word = morse.umorse(txt) replyMsg = reply.TextMsg(toUser, fromUser, word) return replyMsg.send() if content[0:2] == 'm1' or content[0:2] == 'M1': txt = content[3:-1] + content[-1] word = morse.morse1(txt) replyMsg = reply.TextMsg(toUser, fromUser, word) return replyMsg.send() if content[0:3] == 'um1' or content[0:3] == 'UM1': txt = content[4:-1] + content[-1] word = morse.umorse1(txt) replyMsg = reply.TextMsg(toUser, fromUser, word) return replyMsg.send() if content[0:2] == 'ip' or content[0:2] == 'Ip' or content[ 0:2] == 'IP': txt = content[3:-1] + content[-1] word = ip.target(txt) replyMsg = reply.TextMsg(toUser, fromUser, word) return replyMsg.send() if content[0:2] == 'hp' or content[0:2] == 'Hp' or content[ 0:2] == 'HP': txt = content[3:-1] + content[-1] word = free.freestyle(txt) replyMsg = reply.TextMsg(toUser, fromUser, word) return replyMsg.send() if content == '余额' or content == '校园卡余额': word = '把链接复制到浏览器中查询速度更快(⊙o⊙)哦'+'\n' + \ 'http://sundae.applinzi.com/signin' replyMsg = reply.TextMsg(toUser, fromUser, word) return replyMsg.send() if content == '关机': word = smtp.smtp() replyMsg = reply.TextMsg(toUser, fromUser, word) return replyMsg.send() if content == '监控' or content == '远程监控': word = smtp.control() replyMsg = reply.TextMsg(toUser, fromUser, word) return replyMsg.send() if content == 'html' or content == '源代码': word = '欢迎使用网页源代码查询功能' + '\n' + 'http://sundae.applinzi.com/html' replyMsg = reply.TextMsg(toUser, fromUser, word) return replyMsg.send() if content == '主页' or content == 'Sundae' or content == '网站' or content == 'sundae': word = '欢迎访问 Sundae『在路上随风走』个人网站' + '\n' + 'http://sundae.applinzi.com/home' replyMsg = reply.TextMsg(toUser, fromUser, word) return replyMsg.send() if content == '博客': word = '欢迎访问 Sundae『在路上随风走』个人博客' + '\n' + 'http://sundae.applinzi.com/blog' replyMsg = reply.TextMsg(toUser, fromUser, word) return replyMsg.send() if content == '骑行日记': word = '欢迎访问 Sundae『在路上随风走』个人博客——骑行日记' + '\n' + 'http://sundae.applinzi.com/diary' replyMsg = reply.TextMsg(toUser, fromUser, word) return replyMsg.send() if content[0:2] == 'QR' or content[0:2] == 'qr' or content[ 0:2] == 'Qr': txt = content[3:-1] + content[-1] sinastorage.setDefaultAppInfo( 'w5il63SKTaSzZlCvuy8l', 'ae6523ffe7531606e34a6285fd3554f9203e2a2e') s = SCSBucket('sundae') url = s.make_url_authed('picture/whubj.jpg') qrurl = 'http://qr.topscan.com/api.php?text=' + txt replyMsg = reply.QrMsg(toUser, fromUser, url, qrurl) return replyMsg.send() if content == '功能介绍' or content == '功能' or content == '功能简介': word = ''' 功能简介: 1.聊天机器人,支持文字聊天和语音聊天。 2.电台,收听电台,关键字:电台。 3.成绩查询,查询所有成绩,关键字:成绩查询、成绩单等。 4.糗事百科,后台爬虫爬取糗百官网最新最热段子,关键字:糗百等。 5.内涵段子,后台爬虫爬取内涵段子官网最新段子,关键字:段子。 6.搞笑图片,后台爬虫爬取内涵段子官网内涵图,关键字:内涵图、搞笑图片等。 7.武汉大学动机院公告,爬取了官网抓了同步更新的公告,关键字:动机院等。 8.北京理工大学机电学院公告,爬取了官网同步更新的公告,关键字:机电学院等。 9.网站,我的个人网站,关键字:网站等。 10.博客,我的个人博客,关键字:博客等。 11.网页源代码,在手机上也可以查看指定网站的源代码,关键字:源代码等。 12.Python,介绍Python语言,毕竟我后台就是用Python写的,关键字:Python。 13.火车车次,输入“train 车次”直接查询列车时刻表,关键字:Train 车次。 14.二维码,输入“QR 文字”可将文字转变为二维码,关键字:Qr、QR等。 15.摩斯密码,可以进行摩斯密码加解密,关键字:Morse、Umorse、m1、um1等。 16.IP地址,输入“ip xx.xx.xx.xx”可以查询指定IP的地址,关键字:IP、ip等。 17.有freestyle吗,输入“hp 词语”可查询相关的押韵词语,关键字:hp、Hp等。 所有关键字都支持模糊匹配,比如动机院公告、武大动机、动机院等都是同一个关键字。 剩下的都是我的个人功能就不告诉大家了哈~~~ ''' replyMsg = reply.TextMsg(toUser, fromUser, word) return replyMsg.send() if content == 'import this' or content == '后台' or content == 'Python' or content == 'python': word = ''' The Zen of Python, by Tim Peters Beautiful is better than ugly. Explicit is better than implicit. Simple is better than complex. Complex is better than complicated. Flat is better than nested. Sparse is better than dense. Readability counts. Special cases aren't special enough to break the rules. Although practicality beats purity. Errors should never pass silently. Unless explicitly silenced. In the face of ambiguity, refuse the temptation to guess. There should be one-- and preferably only one --obvious way to do it. Although that way may not be obvious at first unless you're Dutch. Now is better than never. Although never is often better than *right* now. If the implementation is hard to explain, it's a bad idea. If the implementation is easy to explain, it may be a good idea. Namespaces are one honking great idea -- let's do more of those! ''' replyMsg = reply.TextMsg(toUser, fromUser, word) return replyMsg.send() word = robot.Robot(content, toUser) replyMsg = reply.TextMsg(toUser, fromUser, word) return replyMsg.send() if recMsg.MsgType == 'image': mediaId = recMsg.MediaId replyMsg = reply.ImageMsg(toUser, fromUser, mediaId) return replyMsg.send() if recMsg.MsgType == 'voice': content = recMsg.Recognition word = robot.Robot(content, toUser) replyMsg = reply.TextMsg(toUser, fromUser, word) return replyMsg.send() else: return reply.Msg().send() else: print "Wait..." return 'success' except Exception, Argument: return Argument
def POST(self): data = json.load(StringIO(web.data())) addVideos(data) web.seeother('/playlist')
def POST(self): """ List all replicas for data identifiers. HTTP Success: 200 OK HTTP Error: 401 Unauthorized 500 InternalError :returns: A dictionary containing all replicas information. :returns: A metalink description of replicas if metalink(4)+xml is specified in Accept: """ metalink = None if ctx.env.get('HTTP_ACCEPT') is not None: tmp = ctx.env.get('HTTP_ACCEPT').split(',') # first check if client accepts metalink if 'application/metalink+xml' in tmp: metalink = 3 # but prefer metalink4 if the client has support for it # (clients can put both in their ACCEPT header!) if 'application/metalink4+xml' in tmp: metalink = 4 dids, schemes, select, unavailable, limit = [], None, None, False, None ignore_availability, rse_expression, all_states = False, None, False json_data = data() try: params = parse_response(json_data) if 'dids' in params: dids = params['dids'] if 'schemes' in params: schemes = params['schemes'] if 'unavailable' in params: unavailable = params['unavailable'] ignore_availability = True if 'all_states' in params: all_states = params['all_states'] if 'rse_expression' in params: rse_expression = params['rse_expression'] except ValueError: raise generate_http_error(400, 'ValueError', 'Cannot decode json parameter list') if ctx.query: params = parse_qs(ctx.query[1:]) if 'select' in params: select = params['select'][0] if 'limit' in params: limit = params['limit'][0] try: # first, set the APPropriate content type, and stream the header if metalink is None: header('Content-Type', 'application/x-json-stream') elif metalink == 3: header('Content-Type', 'application/metalink+xml') yield '<?xml version="1.0" encoding="UTF-8"?>\n<metalink version="3.0" xmlns="http://www.metalinker.org/">\n<files>\n' elif metalink == 4: header('Content-Type', 'application/metalink4+xml') yield '<?xml version="1.0" encoding="UTF-8"?>\n<metalink xmlns="urn:ietf:params:xml:ns:metalink">\n' # then, stream the replica information for rfile in list_replicas(dids=dids, schemes=schemes, unavailable=unavailable, request_id=ctx.env.get('request_id'), ignore_availability=ignore_availability, all_states=all_states, rse_expression=rse_expression): client_ip = ctx.env.get('HTTP_X_FORWARDED_FOR') if client_ip is None: client_ip = ctx.ip replicas = [] dictreplica = {} for rse in rfile['rses']: for replica in rfile['rses'][rse]: replicas.append(replica) dictreplica[replica] = rse if select == 'geoip': replicas = geoIP_order(dictreplica, client_ip) else: replicas = random_order(dictreplica, client_ip) if metalink is None: yield dumps(rfile, cls=APIEncoder) + '\n' elif metalink == 3: idx = 0 yield ' <file name="' + rfile[ 'name'] + '">\n <resources>\n' for replica in replicas: yield ' <url type="http" preference="' + str( idx) + '">' + replica + '</url>\n' idx += 1 if limit and limit == idx: break yield ' </resources>\n </file>\n' elif metalink == 4: yield ' <file name="' + rfile['name'] + '">\n' yield ' <identity>' + rfile['scope'] + ':' + rfile[ 'name'] + '</identity>\n' if rfile['adler32'] is not None: yield ' <hash type="adler32">' + rfile[ 'adler32'] + '</hash>\n' if rfile['md5'] is not None: yield ' <hash type="md5">' + rfile['md5'] + '</hash>\n' yield ' <size>' + str(rfile['bytes']) + '</size>\n' idx = 0 for replica in replicas: yield ' <url location="' + str( dictreplica[replica]) + '" priority="' + str( idx + 1) + '">' + replica + '</url>\n' idx += 1 if limit and limit == idx: break yield ' </file>\n' # don't forget to send the metalink footer if metalink: if metalink == 3: yield '</files>\n</metalink>\n' elif metalink == 4: yield '</metalink>\n' except DataIdentifierNotFound, e: raise generate_http_error(404, 'DataIdentifierNotFound', e.args[0][0])
def DELETE(self): data = json.load(StringIO(web.data())) removeVideo(data['id']) web.seeother('/playlist')
def POST(self): session_args = web.data() print session_args
def POST(self, name): webData = json.loads(web.data()) action = webData["action"] if "token" in webData: token = webData["token"] if checkSession(token) == False: return packOutput({}, "401", "Tocken authority failed") if action == "getList": list = self.getList(webData) num = len(list) resultJson = {"workerNum": num, "workerList": []} for item in list: worker = item.copy() del worker["callerList"] resultJson["workerList"].append(worker) return packOutput(resultJson) elif action == "getInfo": worker = self.getInfo(webData) return packOutput(worker) elif action == "import": self.imports(webData) return packOutput({}) elif action == "add": id = self.addWorker(webData) return packOutput({}) elif action == "del": ret = self.delWorker(webData) if ret == -1: resultJson = {"result": "failed"} else: resultJson = {"result": "success"} return packOutput(resultJson) elif action == "edit": id = self.editWorker(webData) return packOutput({}) elif action == "testSource": ret = self.testImportSource(webData) if ret: resultJson = {"result": "success"} else: resultJson = {"result": "failed"} return packOutput(resultJson) elif action == "testSourceConfig": ret = self.testImportSourceConfig(webData) sql = self.getAliasSql(webData) if ret: resultJson = {"result": "success", "sql": sql} else: resultJson = {"result": "failed", "sql": sql} return packOutput(resultJson) elif action == "checkID": ret = self.checkConflict(webData) resultJson = {"conflict": ret} return packOutput(resultJson) else: return packOutput({}, "500", "unsupport action")
def POST(self): try: webData = web.data() print "Handle Post webdata is ", webData # 后台打日志 recMsg = receive.parse_xml(webData) if isinstance(recMsg, receive.Msg): toUser = recMsg.FromUserName fromUser = recMsg.ToUserName print recMsg.MsgType if recMsg.MsgType == 'text': #文字类型返回 content = recMsg.Content print content unicode_str = unicode(content, "utf-8") #有待改进的算法 #如果满足是用户自定义的单词就选择图灵机器人 cmp1_val = compare.compare_to_list(unicode_str, openlight_list) cmp2_val = compare.compare_to_list(unicode_str, closlight_lis) cmp3_val = compare.compare_to_list(unicode_str, homeweather_list) cmp4_val = compare.compare_to_list(unicode_str, outdorweather_list) cmp5_val = compare.compare_to_list(unicode_str, map_list) rand_val = compare.compare_to_list(unicode_str, music_rand_list) jay_val = compare.compare_to_list(unicode_str, music_jay_list) andy_val = compare.compare_to_list(unicode_str, music_andy_list) stop_val = compare.compare_to_list(unicode_str, music_stop_list) video_val = compare.compare_to_list( unicode_str, video_list) if cmp1_val is True: print cmp1_val pub.pub_msg("{\"ctr_light\":1}", "cmd") tl_reply = u"好的,打开灯" print tl_reply print type(tl_reply) elif cmp2_val is True: print cmp2_val pub.pub_msg("{\"ctr_light\":0}", "cmd") tl_reply = u"好的,关闭灯" print tl_reply elif cmp3_val is True: print cmp3_val #加入读取json文件代码 air_t, air_h, air_l = do_json.process_get_json_val( "data_out.json") tl_reply = u"当前,温度:%.1f℃,湿度:%.1f%%, 光照:%dlux" % ( air_t, air_h, air_l) #tl_reply = u"家里面温度12℃,湿度34%,光照123lux" print tl_reply elif cmp4_val is True: #从阿里云获取天气预报 tl_reply = outdoorweather.get_outdoor_weather() elif cmp5_val is True: #发送地图 tl_reply = u"下面链接可以找到我哦\r\n" + u"" #tl_reply = u"北京的现在的温度-1℃,天气重度雾霾" #if cmp1_val is not True and cmp2_val is not True and cmp3_val is not True and cmp4_val is not True: #需要unicode变量,如果不是以上信息,就交给图灵机器人吧 elif rand_val is True: pub.pub_msg("{\"music_id\":3}", "music") tl_reply = u"好的,随便来一首啦" elif jay_val is True: pub.pub_msg("{\"music_id\":1}", "music") tl_reply = u"好的,播放周杰伦的歌曲哟" elif andy_val is True: pub.pub_msg("{\"music_id\":2}", "music") tl_reply = u"好的,播放华仔的歌曲哟" elif stop_val is True: pub.pub_msg("{\"music_id\":4}", "music") tl_reply = u"啧啧啧,不播了" elif video_val is True: tl_reply = u"下面链接可以看到我哦\r\n" + u"" else: tl_reply = tl_auto_reply.reply(unicode_str) print tl_reply #需要str变量 replyMsg = reply.TextMsg(toUser, fromUser, tl_reply.encode("utf-8")) return replyMsg.send() elif recMsg.MsgType == 'image': mediaId = recMsg.MediaId replyMsg = reply.ImageMsg(toUser, fromUser, mediaId) return replyMsg.send() elif recMsg.MsgType == 'voice': #语音类型,开启语音识别功能 voice_content = recMsg.Recognition #他居然是unicode类型 print voice_content #如果满足是用户自定义的单词就选择图灵机器人 cmp1_val = compare.compare_to_list(voice_content, openlight_list) cmp2_val = compare.compare_to_list(voice_content, closlight_lis) cmp3_val = compare.compare_to_list(voice_content, homeweather_list) cmp4_val = compare.compare_to_list(voice_content, outdorweather_list) cmp5_val = compare.compare_to_list(voice_content, map_list) rand_val = compare.compare_to_list(voice_content, music_rand_list) jay_val = compare.compare_to_list(voice_content, music_jay_list) andy_val = compare.compare_to_list(voice_content, music_andy_list) stop_val = compare.compare_to_list(voice_content, music_stop_list) video_val = compare.compare_to_list( voice_content, video_list) if cmp1_val is True: print cmp1_val pub.pub_msg("{\"ctr_light\":1}", "cmd") tl_reply = u"好的,打开灯" print tl_reply print type(tl_reply) elif cmp2_val is True: print cmp2_val pub.pub_msg("{\"ctr_light\":0}", "cmd") tl_reply = u"好的,关闭灯" print tl_reply elif cmp3_val is True: print cmp3_val #加入读取json文件代码 air_t, air_h, air_l = do_json.process_get_json_val( "data_out.json") tl_reply = u"当前,温度:%.1f℃,湿度:%.1f%%, 光照:%dlux" % ( air_t, air_h, air_l) #tl_reply = u"家里面温度12℃,湿度34%,光照123lux" print tl_reply elif cmp4_val is True: #从阿里云获取天气预报 tl_reply = outdoorweather.get_outdoor_weather() elif cmp5_val is True: #发送地图 tl_reply = u"下面链接可以找到我哦\r\n" + u"" #tl_reply = u"北京的现在的温度-1℃,天气重度雾霾" #if cmp1_val is not True and cmp2_val is not True and cmp3_val is not True and cmp4_val is not True: #需要unicode变量,如果不是以上信息,就交给图灵机器人吧 elif rand_val is True: pub.pub_msg("{\"music_id\":3}", "music") tl_reply = u"好的,随便来一首啦" elif jay_val is True: pub.pub_msg("{\"music_id\":1}", "music") tl_reply = u"好的,播放周杰伦的歌曲哟" elif andy_val is True: pub.pub_msg("{\"music_id\":2}", "music") tl_reply = u"好的,播放华仔的歌曲哟" elif stop_val is True: pub.pub_msg("{\"music_id\":4}", "music") tl_reply = u"啧啧啧,不播了" elif video_val is True: tl_reply = u"下面链接可以看到我哦\r\n" + u"" else: tl_reply = tl_auto_reply.reply(voice_content) print tl_reply #print type(voice_content) #unicode_str = unicode(voice_content, "utf-8") #需要unicode变量 #tl_reply = tl_auto_reply.reply(voice_content) #print tl_reply #需要str变量,语音识别后的,返回文字式对白,未认证公众号无法返回语音 replyMsg = reply.TextMsg(toUser, fromUser, tl_reply.encode("utf-8")) return replyMsg.send() else: return reply.Msg().send() else: print "暂且不处理" return reply.Msg().send() except Exception, Argment: return Argment
def POST(self): params = web.input(facilitycode="", form="", district="", msisdn="", raw_msg="", report_type="", facility="", reporter_type="", uuid="", reporter_name="") extras = {'reporter_type': params.reporter_type} # values = json.loads(params['values']) # only way we can get out Rapidpro values in webpy if PREFERED_DHIS2_CONTENT_TYPE == 'json': dataValues = [] else: dataValues = "" print("FACILITYCODE:", params.facilitycode, "==>", params.facility, "UUID:", params.uuid) if params.facilitycode: if not USE_OLD_WEBHOOKS: values = json.loads(web.data()) results = values.get('results', {}) thresholds_list = [] for key, v in results.iteritems(): val = v.get('value') try: val = int(float(val)) except: pass label = v.get('name') slug = "%s_%s" % (params.form, label) if val.__str__().isdigit() or slug in TEXT_INDICATORS: if not (val) and params.form in [ 'cases', 'death', 'epc', 'epd' ]: if label not in params.raw_msg.lower(): continue # skip zero values for cases, death, epc and epd if slug not in IndicatorMapping: continue # XXX check thresholds here if IndicatorMapping[slug]['threshold']: try: threshold = int( float(IndicatorMapping[slug]['threshold'])) if val > threshold: thresholds_list.append('{} {}'.format( val, IndicatorMapping[slug]['descr'])) except: pass print("%s=>%s" % (slug, val), IndicatorMapping[slug]) if PREFERED_DHIS2_CONTENT_TYPE == 'json': dataValues.append({ 'dataElement': IndicatorMapping[slug]['dhis2_id'], 'categoryOptionCombo': IndicatorMapping[slug]['dhis2_combo_id'], 'value': val }) else: dataValues += ( "<dataValue dataElement='%s' categoryOptionCombo=" "'%s' value='%s' />\n" % (IndicatorMapping[slug]['dhis2_id'], IndicatorMapping[slug]['dhis2_combo_id'], val)) # Build alert message and send it alert_message = "Thresholds alert: {0} ({1}) of {2} - {3} district reported:\n".format( params.reporter_name, params.msisdn, params.facility, params.district) alert_message += '\n'.join(thresholds_list) send_threshold_alert(alert_message, params.district) print(alert_message) else: values = json.loads( params['values'] ) # only way we can get out Rapidpro values in webpy thresholds_list = [] for v in values: val = v.get('value') try: val = int(float(val)) except: pass label = v.get('label') slug = "%s_%s" % (params.form, label) if val.__str__().isdigit() or slug in TEXT_INDICATORS: if not (val) and params.form in ['cases', 'death']: if label not in params.raw_msg.lower(): continue # skip zero values for cases and death if slug not in IndicatorMapping: continue # XXX check thresholds here if IndicatorMapping[slug]['threshold']: try: threshold = int( float(IndicatorMapping[slug]['threshold'])) if val > threshold: thresholds_list.append('{} {}'.format( val, IndicatorMapping[slug]['descr'])) except: pass print("%s=>%s" % (slug, val), IndicatorMapping[slug]) if PREFERED_DHIS2_CONTENT_TYPE == 'json': dataValues.append({ 'dataElement': IndicatorMapping[slug]['dhis2_id'], 'categoryOptionCombo': IndicatorMapping[slug]['dhis2_combo_id'], 'value': val }) else: dataValues += ( "<dataValue dataElement='%s' categoryOptionCombo=" "'%s' value='%s' />\n" % (IndicatorMapping[slug]['dhis2_id'], IndicatorMapping[slug]['dhis2_combo_id'], val)) # Build alert message and send it alert_message = "Thresholds alert: {0} ({1}) of {2} - {3} district reported:\n".format( params.reporter_name, params.msisdn, params.facility, params.district) alert_message += '\n'.join(thresholds_list) send_threshold_alert(alert_message, params.district) print(alert_message) if not dataValues and params.form in ('cases', 'death'): if PREFERED_DHIS2_CONTENT_TYPE == 'json': dataValues = [] else: dataValues = DEFAULT_DATA_VALUES[params.form] if dataValues: args_dict = { 'completeDate': datetime.datetime.now().strftime("%Y-%m-%d"), 'period': get_reporting_week(datetime.datetime.now()), 'orgUnit': params.facilitycode, 'dataValues': dataValues } if PREFERED_DHIS2_CONTENT_TYPE == 'json': args_dict['dataSet'] = HMIS_033B_DATASET args_dict[ 'attributeOptionCombo'] = HMIS_033B_DATASET_ATTR_OPT_COMBO payload = json.dumps(args_dict) else: payload = XML_TEMPLATE % args_dict year, week = tuple(args_dict['period'].split('W')) print(payload) extra_params = { 'week': week, 'year': year, 'msisdn': params.msisdn, 'facility': params.facilitycode, 'raw_msg': params.raw_msg, 'district': params.district, 'report_type': params.report_type, # 'source': config['dispatcher2_source'], # 'destination': config['dispatcher2_destination'], 'source': serversByName[config['dispatcher2_source']], 'destination': serversByName[config['dispatcher2_destination']], 'extras': json.dumps(extras), 'response': self.get_last_response_message(params.uuid), 'status': config.get('default-queue-status', 'pending') } # now ready to queue to DB for pushing to DHIS2 # resp = queue_submission(serverid, post_xml, year, week) print(extra_params) if PREFERED_DHIS2_CONTENT_TYPE == 'json': extra_params['ctype'] = 'json' # resp = post_request_to_dispatcher2( # payload, params=extra_params, ctype='json') extra_params['body'] = payload queue_rejected_reports(db, extra_params) else: extra_params['ctype'] = 'xml' # resp = post_request_to_dispatcher2(payload, params=extra_params) extra_params['body'] = payload queue_rejected_reports(db, extra_params) # print "Resp:", resp return json.dumps({"status": "success"})
def POST(self): result = {METRICS: None, LOGGING: []} try: url_param = [ i for i in web.ctx['path'].split('/') if i not in ['', 'api', 'config'] ] except: error_msg = "URl not Found" raise web.notfound(error_msg) if len(url_param) != 0: error_msg = "URl not Found" raise web.notfound(error_msg) try: data = json.loads(web.data()) except: error_msg = "Data is not in Json format" raise web.badrequest(error_msg) metrics = data.get(METRICS, {}) logging = data.get(LOGGING, {}) targets = data.get(TARGETS, {}) hostname = data.get("name") nodeId = data.get(NODEID) if not (metrics or logging): result[METRICS] = configurator.set_collectd_config(metrics) result[LOGGING] = configurator.set_fluentd_config(logging) elif metrics and not (metrics.get(PLUGINS, []) and metrics.get(TARGETS, [])): error_msg = "Invalid metrics config" raise web.badrequest(error_msg) elif logging and not (logging.get(PLUGINS, []) and logging.get(TARGETS, [])): error_msg = "Invalid logging config" raise web.badrequest(error_msg) if metrics: metrics = configurator.map_local_targets(targets, metrics) metrics["custom_hostname"] = hostname if nodeId: metrics[NODEID] = nodeId result[METRICS] = configurator.set_collectd_config(metrics) else: result[METRICS] = configurator.set_collectd_config(metrics) if logging: logging = configurator.map_local_targets(targets, logging) result[LOGGING] = configurator.set_fluentd_config(logging) else: result[LOGGING] = configurator.set_fluentd_config(logging) if data.get(HEARTBEAT, False): es_config = dict() for target in targets: if target[TYPE] == ELASTICSEARCH: es_config = target break if configurator.timer: try: configurator.timer.cancel() configurator.timer = None except: pass h_interval = data.get(HEARTBEAT_INTERVAL, configurator.CONFIG_WRITE_INTERVAL) configurator.write_config_to_target(es_config, h_interval) return json.dumps(result)
def POST(self): i = web.data() return "==> POST method , data : ", str(i)
def POST(self, method=None): ''' '/demo','/demo/(.+)' ''' data = web.data() return 'OK, data: %s' % str(data)
cmd_data['CommandUUID'] = str(uuid.uuid4()) current_command = cmd_data last_sent = pprint.pformat(current_command) wrapper = APNSNotificationWrapper('PlainCert.pem', False) message = APNSNotification() message.token(my_DeviceToken) message.appendProperty(APNSProperty('mdm', my_PushMagic)) wrapper.append(message) wrapper.notify() return home_page() class do_mdm: global last_result def PUT(self): global current_command, last_result i = web.data() pl = readPlistFromString(i) if pl.get('Status') == 'Idle': rd = current_command elif pl.get('MessageType') == 'TokenUpdate': rd = do_TokenUpdate(pl) elif pl.get('Status') == 'Acknowledged': rd = dict() else: rd = dict() out = writePlistToString(rd) if pl.get('UDID'): pl['UDID'] = '--redacted--' q = pl.get('QueryResponses') if q: redact_list = ('UDID', 'BluetoothMAC', 'SerialNumber', 'WiFiMAC', 'IMEI', 'ICCID', 'SerialNumber')