def unspuninput(page_name, *args, **kwargs): myspinner = web.input('spinner').spinner spinfield = genspinfield(myspinner) mapping = dict((spinfield(x), x) for x in args + tuple(kwargs.keys()) + ('timestamp',)) i = web.input( *[spinfield(x) for x in args], **dict((spinfield(k), v) for k, v in kwargs.iteritems())) for k in ['s', 't']: for n in itertools.count(): fn = 'honeypot_%s%s' % (k, n) if spinfield(fn) not in i: break mapping[spinfield(fn)] = fn newi = web.storage((mapping[k], v) for k, v in i.iteritems() if k in mapping) try: #assert myspinner == spinner(page_name, newi.timestamp) # (not using because we got some odd errors) assert int(newi.timestamp) < time.time() # assert int(i.timestamp) > (time.time() - 3600) # (not using yet because it causes usability loss) del newi['timestamp'] for k in newi.copy(): assert not k.startswith('honeypot_s') if k.startswith('honeypot_t'): assert newi[k] == "" del newi[k] except AssertionError: web.badrequest() raise StopIteration return newi
def PUT(self, id, setting): if setting not in self.Settings: web.notfound() return None try: configData = json.loads(web.data()) id = int(id) vm = model.getVM(web.ctx.veerezoDB, id) if vm['user'] != web.ctx.username: web.forbidden() return None except (ValueError, KeyError): web.notfound() return None fn = '_put' + self.Settings[setting] f = getattr(self, fn) try: f(id, vm, configData) except ValueError as e: web.badrequest() return {'error': 'ValueError: {0}'.format(e.message)} web.nocontent() return None
def _PUT(self, *param, **params): host_id = self.chk_hostby1(param) if host_id is None: return web.notfound() # TODO valid network_name = param[1] if not network_name: return web.notfound() if validates_nw_status(self) is False: return web.badrequest(self.view.alert) status = int(self.input.status) kvc = KaresansuiVirtConnection() try: kvn = kvc.search_kvn_networks(network_name)[0] if status == NETWORK_INACTIVE: # Stop network network_start_stop_job(self, host_id, network_name, 'stop') return web.accepted("/host/%s/network/%s.%s" % (host_id, network_name, self.__template__['media'])) elif status == NETWORK_ACTIVE: # Start network network_start_stop_job(self, host_id, network_name, 'start') return web.accepted("/host/%s/network/%s.%s" % (host_id, network_name, self.__template__['media'])) else: return web.badrequest() finally: kvc.close()
def yzImage ( imageargs, dbcfg ): """Return an xz plane fileobj.read()""" restargs = imageargs.split('/') if len ( restargs ) == 5: [ resstr, xstr, ydimstr, zdimstr, rest ] = restargs globalcoords = False elif len ( restargs ) == 6: [ resstr, xstr, ydimstr, zdimstr, rest, other ] = restargs globalcoords = True else: return web.badrequest() # expecting an argument of the form /resolution/x/y1,y2/z1,z2/ # Check that the arguments are well formatted if not re.match ('[0-9]+$', xstr) or\ not re.match ('[0-9]+,[0-9]+$', ydimstr) or\ not re.match ('[0-9]+,[0-9]+$', zdimstr) or\ not re.match ('[0-9]+$', resstr ): return web.badrequest() y1s,y2s = ydimstr.split(',') z1s,z2s = zdimstr.split(',') x = int(xstr) y1i = int(y1s) y2i = int(y2s) z1i = int(z1s) z2i = int(z2s) resolution = int(resstr) # Convert to local coordinates if global specified if ( globalcoords ): x = int ( float(x) / float( 2**(resolution-dbcfg.baseres))) y1i = int ( float(y1i) / float( 2**(resolution-dbcfg.baseres))) y2i = int ( float(y2i) / float( 2**(resolution-dbcfg.baseres))) #RBTODO need to make a dbconfig object # Check arguments for legal values if not dbcfg.checkCube ( resolution, x, x, y1i, y2i, z1i, z2i )\ or x >= dbcfg.imagesz[resolution][0]: return web.notfound() corner=[x,y1i,z1i-dbcfg.slicerange[0]] dim=[1,y2i-y1i,z2i-z1i ] try: annodb = anndb.AnnotateDB ( dbcfg ) cb = annodb.cutout ( corner, dim, resolution ) fileobj = StringIO.StringIO ( ) cb.yzSlice ( dbcfg.zscale[resolution], fileobj ) except: return web.notfound() web.header('Content-type', 'image/png') fileobj.seek(0) return fileobj.read()
def GET(self,uri): request = uri.split('/') if request == ['']: web.badrequest() return "Incorrect request : /tempoedf/{now | tomorrow}\n" try: format = request[1] except: format = None if request[0] == "now": result = temporequest.TempoToday() if format == "json": web.header('Content-Type', 'application/json') return json.dumps({"tempocolor": result}) else: return result if request[0] == "tomorrow": result = temporequest.TempoTomorrow() if format == "json": web.header('Content-Type', 'application/json') return json.dumps({"tempocolor": result}) else: return result web.badrequest() return "Incorrect request : /tempoedf/{now | tomorrow}\n"
def DELETE(self, resource): """ Try to delete the supplied resource """ if isTestMode(): # check env. if in test mode, import dbconn mock import Shared dbConn = Shared.dbMock else: dbConn = DataAccessLayer.DataAccessLayer() if not isValidKey(resource): logging.info("Item-DELETE: invalid resource key (%s)", resource) web.badrequest() return try: dbConn.delete(resource) except AttributeError: logging.warning("Item-DELETE: unable to delete resource (%s)", resource) web.notfound() return except Exception as e: logging.error("Item-DELETE: Unexpected exception when deleting: %s", e) web.badrequest() return web.ok() return
def POST(self, device_name): args, body = templeton.handlers.get_request_parms() try: assignee = body['assignee'] duration = int(body['duration']) image_name = body['image'] environment = body.get('environment', 'any') except (KeyError, ValueError): raise web.badrequest() try: image = self.db.images.get(image_name) except exceptions.NotFound: raise web.notfound() boot_config = {} for k in image['boot_config_keys']: try: boot_config[k] = body[k] except KeyError: raise web.badrequest() request_id = self.db.requests.add(device_name, environment, assignee, duration, image['id'], boot_config) mozpool.mozpool.driver.handle_event(request_id, 'find_device', None) info = self.db.requests.get_info(request_id) info['url'] = "http://%s/api/request/%d/" % ((config.get('server', 'fqdn'), request_id)) response_data = {'request': info} if self.db.requests.get_machine_state(request_id) == 'closed': raise ConflictJSON(response_data) return response_data
def _POST(self, *param, **params): host_id = self.chk_hostby1(param) if host_id is None: return web.notfound() if not validates_mail(self): self.logger.debug("Update mail setting failed. Did not validate.") return web.badrequest(self.view.alert) hostname = self.input.hostname port = self.input.port if not port: port = "25" if hostname: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.settimeout(5.0) try: sock.connect((hostname, int(port))) except Exception, e: self.logger.error("Could not connect to specified MTA \n%s" % e) """ TRANSLATORS: MTA設定の際に実際に指定したホスト名/ポート番号に接続ができる かチェックし、接続できなかった。 """ return web.badrequest(_("Could not connect to specified MTA \n%s" % e))
def GET(self, resource): """ dejsonize the critieria, get a db connection, search for the criteria, get a list of matching items back, json-ize them, send them back to the client """ if not isValidKey(resource): logging.info("Item-GET: invalid resource key (%s)", resource) web.badrequest() return try: rtn = getByKeys(resource) except: logging.info("Item-GET: invalid resource (%s)", resource) web.badrequest() return if rtn is None: logging.info("Item-GET: resource not found (%s)", resource) web.notfound() return web.header("Content-Type", "text/plain") return json.JSONEncoder().encode(rtn) return rtn
def validate_collection_update(cls, data): d = cls.validate_json(data) if not isinstance(d, list): raise web.badrequest( "Invalid json list" ) q = cls.db.query(Node) for nd in d: if not "mac" in nd and not "id" in nd: raise web.badrequest( "MAC or ID is not specified" ) else: if "mac" in nd: existent_node = q.filter_by(mac=nd["mac"]).first() \ or cls.validate_existent_node_mac(nd) if not existent_node: raise web.badrequest( "Invalid MAC specified" ) if "id" in nd and not q.get(nd["id"]): raise web.badrequest( "Invalid ID specified" ) if 'meta' in nd: MetaValidator.validate(nd['meta']) return d
def POST(self): try: parameters = web.input() if (not parameters.has_key('TM_LOGIN')): return web.badrequest() login = parameters.get('TM_LOGIN') if (not parameters.has_key('TM_PASSWORD')): return web.badrequest() password = parameters.get('TM_PASSWORD') if (not parameters.has_key('to')): return web.badrequest() to = parameters.get('to') if (not parameters.has_key('message')): return web.badrequest() message = parameters.get('message') smsender=APISMS.SMSSenderAPI() response = smsender.sendSMS(login, password, to, message) if response.find('OK')>=0: print "<html><body><span style='font-weight: bold;font-size:11pt;color:#225784;'>SMS sent succesfully!</span></body></html>" return web.ctx.status = "500 Internal Server Error" web.ctx.headers = [('Content-Type', 'text/html')] web.ctx.output = response return except Exception, e: web.ctx.status = "500 Internal Server Error" web.ctx.headers = [('Content-Type', 'text/html')] web.ctx.output = "<html><body>Error: %s.</body></html>" % e
def _PUT(self, *param, **params): tag_id = param[0] if not validates_param_id(self, tag_id): self.logger.debug("Failed to update tag. The value of parameter is invalid.") return web.badrequest(self.view.alert) if not validates_tag(self): self.logger.debug("Failed to update tag. The value of input is invalid.") return web.badrequest(self.view.alert) tag = findby1(self.orm, tag_id) if not tag: self.logger.debug("Failed to update tag. No such tag - id=%s" % tag_id) return web.notfound() cmp_tag = findby1name(self.orm, self.input.name) if not cmp_tag is None: if cmp_tag.id != tag.id: self.logger.debug("Failed to update tag. The same tag already exist - id='%s'" % (cmp_tag.id)) return web.conflict(web.ctx.path) tag.name = self.input.name update(self.orm, tag) return web.seeother(web.ctx.path)
def GET(self): x = web.input(project=0) project = models.Project.get(id=x.project) if not project: raise web.notfound() if x.get('glyph'): if not models.Glyph.exists(name=x.get('glyph'), project_id=project.id): raise web.notfound() project.currentglyph = x.glyph web.ctx.orm.commit() masters = project.get_ordered_masters() masters_list = [] metapost = Metapost(project) for i, master in enumerate(masters): prepare_master_environment(master) glyphs = master.get_glyphs() glyphs = glyphs.filter(models.Glyph.name == project.currentglyph) if not metapost.execute_single(master, glyphs.first()): return web.badrequest() master_instancelog = project.get_instancelog(master.version, 'a') glyphsdata = get_glyph_info_from_log(master_instancelog, master=master) metalabel = get_metapolation_label(chr(models.LABELS[i])) masters_list.append({'glyphs': glyphsdata, 'label': chr(models.LABELS[i]), 'metapolation': metalabel, 'master_id': master.id}) glyphs = masters[0].get_glyphs() glyphs = glyphs.filter(models.Glyph.name == project.currentglyph) if not metapost.execute_interpolated_single(glyphs.first()): return web.badrequest() instancelog = project.get_instancelog(masters[0].version) metaglyphs = get_glyph_info_from_log(instancelog) import operator masters = map(operator.attrgetter('id', 'version'), models.Master.filter(project_id=project.id)) return ujson.dumps({'masters': masters_list, 'versions': project.get_versions(), 'metaglyphs': metaglyphs, 'mode': project.mfparser, 'project_id': project.id})
def _setReturnCode(self, code): """Set the return code :param: code :type code: integer or string returns success: [True|False] """ success = False if code in (200, "200", "ok"): web.ok() success = True elif code in (201, "201", "created"): web.created() success = True elif code in (400, "400", "badrequest"): web.badrequest() elif code in (401, "401", "unauthorized"): web.unauthorized() elif code in (404, "404", "notfound"): web.notfound() elif code in (409, "409", "conflict"): web.conflict() elif code in (500, "500", "internalerror"): web.internalerror() if success: logging.debug("[LayMan][_setReturnCode] Code: '%s'" % code) else: logging.error("[LayMan][_setReturnCode] Code: '%s'" % code) return success
def POST(self, name): _auth_check() variables = web.input() if len(variables) != 1: try: if name is None: raise web.badrequest() raw_state = float(variables.get('state')) boolean_state = None remove_override = False if raw_state in ['on', 'ON', 'On', 'True', 'true', 'TRUE']: boolean_state = True if raw_state in ['off', 'OFF', 'Of', 'False', 'false', 'FALSE']: boolean_state = False if raw_state in ['remove', 'REMOVE', 'Remove']: remove_override = True else: raise web.badrequest() if self._is_heater(name): if remove_override: brew_controller.remove_heater_override() else: brew_controller.set_heater_override(boolean_state) elif self._is_freezer(name): if remove_override: brew_controller.remove_freezer_override() else: brew_controller.set_freezer_override(boolean_state) else: raise web.badrequest() except Exception as e: print 'Error calling device endpoint: ' + str(e) raise web.badrequest() else: raise web.badrequest()
def POST(self, device_name): args, body = templeton.handlers.get_request_parms() try: assignee = body['assignee'] duration = int(body['duration']) image_name = body['image'] environment = body.get('environment', 'any') except (KeyError, ValueError): raise web.badrequest() images = data.dump_images(image_name) if not images: raise web.badrequest() boot_config = {} for k in images[0]['boot_config_keys']: try: boot_config[k] = body[k] except KeyError: raise web.badrequest() request_id = data.create_request(device_name, environment, assignee, duration, images[0]['id'], boot_config) mozpool.mozpool.driver.handle_event(request_id, 'find_device', None) response_data = {'request': data.request_config(request_id)} if data.request_status(request_id)['state'] == 'closed': raise ConflictJSON(response_data) return response_data
def POST(self): try: data = web.input() for field, schema in self.schema.iteritems(): if field not in data: if 'default' in self.schema[field]: data[field] = self.schema[field]['default'] else: web.badrequest() return except AttributeError: pass else: # Process the logfile snapshot = NetworkTrafficSnapshot() snapshot.upload(data['title'], data['description'], data['logfile_name'], data['logfile_content']) snapshot_id = snapshot.save() # Process the statistics snapshot.generate_statistics() # Process the transactions transactions = SipTransactions() transactions.extract(snapshot_id) transactions.save() # Process the dialogs dialogs = SIPDialogs() dialogs.extract(snapshot_id) dialogs.save() return snapshot_id
def _PUT(self, *param, **params): user_id = param[0] if not validates_param_id(self, user_id): self.logger.debug("Failed to update account. the value of parameter is invalid.") return web.notfound(self.view.alert) if not validates_user(self): self.logger.debug("Failed to update account. the value of input is invalid.") return web.badrequest(self.view.alert) user = findby1(self.orm, user_id) if not user: self.logger.debug("Failed to update account. No such account - id=%s" % user_id) return web.notfound() cmp_user = findby1email(self.orm, self.input.email) if not cmp_user is None: if int(user_id) != cmp_user.id: self.logger.debug("Failed to update account. The same mail address '%s' already exist - user='******'" % (self.input.email, cmp_user.nickname)) return web.conflict(web.ctx.path) user.nickname = self.input.nickname user.email = self.input.email user.languages = self.input.languages if not is_empty(self.input.new_password): if compare_password(self, user) == False: return web.badrequest(self.view.alert) (password, salt) = sha1encrypt(self.input.new_password) user.password = password user.salt = salt update(self.orm, user) return web.seeother(web.ctx.path)
def POST(self): web.header('Content-Type', 'text/json') data = web.data() try: data = JSONWrapper(json.loads(data)) except ValueError: data = web.input() timelimit = getattr(data, 'timelimit', straitjacket_settings.MAX_RUNTIME) timelimit = float(timelimit) if timelimit else None if hasattr(data, 'stdin'): stdin = [data.stdin] if not type(data.stdin) == list else data.stdin else: stdin = [None] try: results = wrapper.run(data.language, data.source, stdin, timelimit=timelimit) return json.dumps(results) except straitjacket.InputError as ex: LOGGER.error("Input error: {0}".format(ex)) raise web.badrequest() except AttributeError as ex: LOGGER.error("Attribute error: {0}".format(ex)) raise web.badrequest()
def checked_data(self, validate_method=None, **kwargs): try: data = kwargs.pop('data', web.data()) if validate_method: method = validate_method else: method = self.validator.validate valid_data = method(data, **kwargs) except ( errors.InvalidInterfacesInfo, errors.InvalidMetadata ) as exc: notifier.notify("error", str(exc)) raise web.badrequest(message=str(exc)) except ( errors.AlreadyExists ) as exc: err = web.conflict() err.message = exc.message raise err except ( errors.InvalidData, Exception ) as exc: raise web.badrequest(message=str(exc)) return valid_data
def POST(self): i = web.input(FileData=None, FileName=None, FileSize=None) if i.FileData and i.FileName and i.FileSize: key = str(random.random())[2:] + str(random.random())[2:] + str(random.random())[2:] y = datetime.now().year m = datetime.now().month year_dir = 'static/uploads/' + str(y) month_dir = year_dir + '/' + str(m) if not os.path.exists(year_dir): os.mkdir(year_dir) if not os.path.exists(month_dir): os.mkdir(month_dir) file_path = month_dir + '/' + key + '_' + i.FileName try: f = open(file_path, 'wb') f.write(i.FileData) f.close() return json.dumps({'url': '/' + file_path}) except: if os.path.isfile(file_path): os.remove(file_path) # how to set http status? see web.webapi web.badrequest() else: print i.FileData == {} or i.FileData == None, i.FileName, i.FileSize
def GET(self,user_id_string): """ return back the info for the next set of images expects to receive the user id string can receive the id of the last viewed image """ # make sure we have a user string if not user_id_string: log.warning('ImageDetails GET [%s]: no user id string' % user_id_string) web.badrequest() # find user's last viewed key = '%s:user_details:%s' % (NS, user_id_string) last_viewed_id = rc.hget(key, 'last_viewed_id') if last_viewed_id: # we get back a string last_viewed_id = int(last_viewed_id) # if there is no last viewed, it's 0 else: last_viewed_id = 0 # find the data on the next set of images try: with connect(Images) as c: images = c.get_images_since(image_id=last_viewed_id, timestamp=None, limit=10, offset=0) except io.Exception, ex: log.exception('ImageDetails GET [%s] [%s]: getting images' % (user_id_string,last_viewed_id)) web.internalerror()
def POST(self): """Called when the user uploads a file using POST""" from PIL import Image # get the data from the form x = web.input(myfile=web.Storage(file='')) # check the input file to make sure it's legal if 'myfile' not in x or not x.myfile.file: raise web.badrequest() # create the filename (and containing dir) based on the current time fname = os.path.join(IMAGEDIR, '%d.jpg' % (time.time()*1000)) try: os.makedirs(os.path.dirname(fname)) except OSError: pass # save the image fout = open(fname, 'w') fout.write(x.myfile.file.read()) fout.close() # remove the image from the uploaded params del x['myfile'] try: # if it's a valid image, process it im = Image.open(fname) web.debug('Saved valid image to %s, about to call process() on it' % (fname)) results = process(im, fname, dict(x)) return results except IOError: # if not, delete the image and return bad request try: os.remove(fname) except IOError: pass raise web.badrequest()
def _GET(self, *param, **params): self.__template__.dir = "hostby1logby1appby1" self.__template__.file = "hostby1logby1appby1" self.__template__.media = "part" appname = param[1] filename = param[2] log_config = None if not validates_log(self): self.logger.debug("Get log failed. Did not validate.") return web.badrequest(self.view.alert) config = LogViewConfigParam(LOG_VIEW_XML_FILE) config.load_xml_config() app = config.findby1application(appname) for log in app["logs"]: if log["filename"] == filename: log_config = log lines = [] param_value = {} if is_param(self.input, "k"): param_value["k"] = self.input.k else: param_value["k"] = "" start_day = str2datetime(self.input.s, DEFAULT_LANGS[self.me.languages]["DATE_FORMAT"][0]) end_day = str2datetime(self.input.e, DEFAULT_LANGS[self.me.languages]["DATE_FORMAT"][0]) (start_hour, start_minute) = self.input.st.split(":", 2) (end_hour, end_minute) = self.input.et.split(":", 2) start_time = create_epochsec(start_day.year, start_day.month, start_day.day, int(start_hour), int(start_minute)) end_time = create_epochsec(end_day.year, end_day.month, end_day.day, int(end_hour), int(end_minute)) if int(start_time) > int(end_time): self.logger.error("Getting reports failed. Start time > end time.") return web.badrequest(_("Getting reports failed. Start time > end time.")) param_value["start_datetime"] = "%s %s" % (start_day.strftime("%Y/%m/%d"), self.input.st) param_value["end_datetime"] = "%s %s" % (end_day.strftime("%Y/%m/%d"), self.input.et) if log_config["view_lotatelog"]: try: lines = read_log_with_lotate( filename, self.input.m, log_config, param_value["start_datetime"], param_value["end_datetime"], param_value["k"], ) if lines is False: return web.notfound() except Exception, e: self.logger.warning("log file open error: %s" % e)
def POST(self, owner, repoId): web.header("Content-Type", "text/html") postvars = web.input() if "type" not in postvars: return web.badrequest("Invalid parameters") d = dict(o=owner, i=repoId, u=postvars.get("userid", None)) if postvars.type == "user": if "userid" not in postvars or "access" not in postvars: return web.badrequest("Invalid parameters") if postvars.access not in ["read", "if os.path.exists(repoPath):write", "admin"]: return web.internalerror("Invalid user right") web.config.db.insert( "repo_users", repoid=repoId, repoowner=owner, userid=postvars.userid, access=postvars.access ) elif postvars.type == "info": if "desc" not in postvars or "access" not in postvars: return web.badrequest("Invalid parameters") if postvars.access not in ["public", "private"]: return web.internalerror("Invalid access setting") web.config.db.update( "repositories", where="id=$i and owner=$o", vars=d, description=postvars.desc, access=postvars.access ) elif postvars.type == "remove": if "userid" not in postvars: return web.badrequest("Invalid parameters") web.config.db.delete("repo_users", where="repoid=$i and repoowner=$o and userid=$u", vars=d) elif postvars.type == "rights": if "userid" not in postvars or "access" not in postvars: return web.badrequest("Invalid parameters") if postvars.access not in ["read", "write", "admin"]: return web.internalerror("Invalid user right") web.config.db.update( "repo_users", where="repoid=$i and repoowner=$o and userid=$u", vars=d, access=postvars.access ) elif postvars.type == "delete": if postvars.confirm != "yes, I really want to delete this repository": return web.seeother("/%s/%s/settings" % (owner, repoId)) repoPath = os.path.join("repositories", owner, repoId + ".git") transaction = web.config.db.transaction() try: web.config.db.delete("repo_users", where="repoid=$i and repoowner=$o", vars=d) web.config.db.delete("repositories", where="id=$i and owner=$o", vars=d) if os.path.exists(repoPath): shutil.rmtree(repoPath, True) except Exception, e: transaction.rollback() print e return web.internalerror("Couldn't delete repository") transaction.commit() return web.seeother("/")
def _GET(self, *param, **params): self.__template__.dir = "hostby1logby1appby1" self.__template__.file = "hostby1logby1appby1" self.__template__.media = "part" appname = param[1] log_config = None if not validates_log(self): self.logger.debug("Get log failed. Did not validate.") return web.badrequest(self.view.alert) config = LogViewConfigParam(LOG_VIEW_XML_FILE) config.load_xml_config() app = config.findby1application(appname) lines = [] param_value = {} if self.input.has_key("k"): param_value["k"] = self.input.k else: param_value["k"] = "" start_day = str2datetime(self.input.s, DEFAULT_LANGS[self.me.languages]['DATE_FORMAT'][0]) end_day = str2datetime(self.input.e, DEFAULT_LANGS[self.me.languages]['DATE_FORMAT'][0]) (start_hour, start_minute) = self.input.st.split(':', 2) (end_hour, end_minute) = self.input.et.split(':', 2) start_time = create_epochsec(start_day.year, start_day.month, start_day.day, int(start_hour), int(start_minute), ) end_time = create_epochsec(end_day.year, end_day.month, end_day.day, int(end_hour), int(end_minute), ) if int(start_time) > int(end_time): self.logger.error("Getting reports failed. Start time > end time.") return web.badrequest(_('Getting reports failed. Start time > end time.')) param_value["start_datetime"] = "%s %s" % (start_day.strftime("%Y/%m/%d"), self.input.st) param_value["end_datetime"] = "%s %s" % (end_day.strftime("%Y/%m/%d"), self.input.et) lines = read_all_log(app, int(self.input.m), param_value["start_datetime"], param_value["end_datetime"], param_value["k"]) self.view.log_json = json_dumps(lines) return True
def post(self, *args): " Webpy method receives inputs from uri " errors = [] email_form = self.email_form() if email_form.validates(): campaign_id = email_form['campaign_id'].value status = email_form['status'].value logger.info("changing status of campaign %s to %s" % (campaign_id, status)) connection = self.database.connection() try: if status == 'start': logger.info("Starting email sending for campaign ID %s" % campaign_id) self.start_campaign(connection.cursor(), campaign_id) smtp = self.smtp_connection() contacted_emails = [] while True: cursor = connection.cursor() status, contacts, subject, body = self.retrieve_campaign(cursor, campaign_id) connection.commit() if status != 'started': logger.info("Campaign ID %s stopped, cease email activity" % campaign_id) break logger.info("Retrieved campaign info for campaign ID %s" % campaign_id) contacted_emails = self.send_all_emails(contacts, subject, body, smtp) logger.info("Sent %d emails to users" % len(contacted_emails)) cursor = connection.cursor() self.update_campaign(cursor, campaign_id, contacted_emails) logger.info("Updated campaign ID %s" % campaign_id) connection.commit() smtp.quit() return {"emails": {"campaign_id": campaign_id, "actual_count": len(contacted_emails)}} elif status == 'stop': logger.info("Setting campaign to stopped for campaign ID %s" % campaign_id) cursor = connection.cursor() self.stop_campaign(cursor, campaign_id) connection.commit() else: raise Exception ('unknown status: %s' % s) finally: connection.close() else: web.badrequest() for field in ['campaign_id', 'status']: if email_form[field].note: # Example "product: Required" errors.append("%s: %s" % (field, email_form[field].note)) logger.info("Bad Request. %s" % ', '.join(errors)) return {'message': ', '.join(errors)}
def POST(self): web.header("Access-Control-Allow-Origin", "*") data = json.loads(web.data()) if not "image_id" in data: return web.badrequest("No image given.") if not "collection_id" in data: return web.badrequest("No collection given.") dbId = db.insert("collections_images", image_id=data["image_id"], collection_id=data["collection_id"]) return json.dumps(db.select("collections_images", vars=locals(), where="id = $dbId")[0], cls=DateTimeEncoder)
def POST(self, group): userinfo = web.config.db.select("owners", dict(u=group), where="id=$u").list() if len(userinfo) != 1: raise web.notfound() if userinfo[0].type != "group": raise web.internalerror("Unexpected user type") postvars = web.input() if 'type' not in postvars: return web.badrequest("Invalid parameters") if postvars.type == 'user': if 'userid' not in postvars: return web.badrequest("Invalid parameters") web.config.db.insert('group_users', groupid=group, userid=postvars.userid, role='member') elif postvars.type == 'info': if 'joinable' not in postvars: return web.badrequest("Invalid parameters") if 'desc' not in postvars: postvars.desc = "" if postvars.joinable not in ["yes", "no"]: return web.internalerror("Invalid joinable setting") joinable = 1 if postvars.joinable == "yes" else 0 web.config.db.update('groups', where="id=$g", vars={'g':group}, description=postvars.desc, joinable=joinable) elif postvars.type == 'remove': if 'userid' not in postvars: return web.badrequest("Invalid parameters") web.config.db.delete('group_users', where="groupid=$g and userid=$u", vars={'g':group, 'u':postvars.userid}) elif postvars.type == 'rights': if 'userid' not in postvars or 'access' not in postvars: return web.badrequest("Invalid parameters") if postvars.access not in ["admin"]: return web.internalerror("Invalid user right") web.config.db.update('group_users', where="groupid=$g and userid=$u", vars={'g':group, 'u':postvars.userid}, role='admin') elif postvars.type == 'delete': if postvars.confirm != "yes, I really want to delete this group": return web.seeother("/%s" % owner) transaction = web.config.db.transaction() try: web.config.db.delete('group_users', where="groupid=$g", vars={'g':group}) web.config.db.delete('groups', where="id=$g", vars={'g':group}) except Exception, e: transaction.rollback() print e return web.internalerror("Couldn't delete repository") transaction.commit() return web.seeother("/")
def JsonGET(self): user_data = web.input(q="") if user_data["q"] == "": web.badrequest() return json.dumps([{"Message": "'q' parameter empty"}]) try: r = IPA.simple_search(user_data['q']) return json.dumps(r, cls=indicePA.IpaJsonEncoder, indent=4) except Exception, e: web.internalerror() return json.dumps([{"Message": "Error occured: %s" % e}])
def POST(self): """:returns: JSONized Cluster object. :http: * 201 (cluster successfully created) * 400 (invalid cluster data specified) * 409 (cluster with such parameters already exists) """ # It's used for cluster creating only. data = self.checked_data() cluster = Cluster() cluster.release = db().query(Release).get(data["release"]) # TODO(NAME): use fields for field in ('name', 'mode', 'net_manager'): if data.get(field): setattr(cluster, field, data.get(field)) db().add(cluster) db().commit() attributes = Attributes( editable=cluster.release.attributes_metadata.get("editable"), generated=cluster.release.attributes_metadata.get("generated"), cluster=cluster) attributes.generate_fields() netmanager = NetworkManager() try: netmanager.create_network_groups(cluster.id) cluster.add_pending_changes("attributes") cluster.add_pending_changes("networks") if 'nodes' in data and data['nodes']: nodes = db().query(Node).filter(Node.id.in_( data['nodes'])).all() map(cluster.nodes.append, nodes) db().commit() for node in nodes: netmanager.allow_network_assignment_to_all_interfaces(node) netmanager.assign_networks_to_main_interface(node) raise web.webapi.created( json.dumps(ClusterHandler.render(cluster), indent=4)) except (errors.OutOfVLANs, errors.OutOfIPs, errors.NoSuitableCIDR, errors.InvalidNetworkPool) as e: # Cluster was created in this request, # so we no need to use ClusterDeletionManager. # All relations wiil be cascade deleted automaticly. # TODO(NAME): investigate transactions db().delete(cluster) raise web.badrequest(e.message)
def POST(self, modelName="CioWordFingerprint"): # pylint: disable=R0201,C0103 addStandardHeaders() addCORSHeaders() if modelName not in g_fluent.models: raise web.notfound("%s Model not found" % modelName) response = [] data = web.data() if data: if isinstance(data, basestring): response = g_fluent.query(modelName, data) else: raise web.badrequest( "Invalid Data. Query data must be a string") else: # sample data is missing g_log.error("sample data is missing, raising BadRequest exception") raise web.badrequest("Sample data is missing") return json.dumps(response)
def DELETE(self, key=None): if key is None: raise web.badrequest() else: response = {} db_doc = coll.find_one({'key': key}) if db_doc != None: coll.remove(db_doc) cache.delete(key) response['Status'] = 'OK' else: response['Status'] = 'Not found' raise web.notfound(json.dumps(response)) return json.dumps(response)
def POST(self): i = web.input("name") if len(i.name) < 2: return web.badrequest() key = web.ctx.site.new_key('/type/author') web.ctx.path = key web.ctx.site.save( { 'key': key, 'name': i.name, 'type': dict(key='/type/author') }, comment='New Author') raise web.HTTPError("200 OK", {}, key)
def DELETE(self, task_id): """:returns: JSONized Cluster object. :http: * 204 (task successfully deleted) * 400 (can't delete running task manually) * 404 (task not found in db) """ task = self.get_object_or_404(Task, task_id) if task.status not in ("ready", "error"): raise web.badrequest("You cannot delete running task manually") for subtask in task.subtasks: db().delete(subtask) db().delete(task) db().commit() raise web.webapi.HTTPError(status="204 No Content", data="")
def GET(self, platform, release, arch): """ Download a specific Sandbox Agent, given the OS type :param os: :param agent_ver: :return: """ # Sanitize os and version. if not re.match("^[a-zA-Z0-9\_]+$", platform): raise web.badrequest("Platform value is unsafe and will not be accepted.") if not re.match("^[a-zA-Z0-9\_]+$", release): raise web.badrequest("Release value is unsafe and will not be accepted.") if not re.match("^[a-zA-Z0-9\_]+$", arch): raise web.badrequest("Arch value is unsafe and will not be accepted.") # Calculate the path dest_path = os.path.join(AGENT_CLIENT_DIR, platform, release, arch) if not os.path.isdir(dest_path): os.makedirs(dest_path) # Check if the file exists and serve it back filename = os.path.join(dest_path, "agent.zip") if not os.path.isfile(filename): raise web.notfound("Agent version not found on this sniffer.") stats = os.stat(filename) web.header('Content-Type', 'application/octet-stream') web.header('Content-Disposition', 'attachment; filename="agent.zip"') web.header('Content-Length', '%d' % stats.st_size) web.ctx.status = '200 OK' return open(filename, "rb").read()
def POST(self, device_name): args, body = templeton.handlers.get_request_parms() boot_config = body.get('boot_config', {}) try: assignee = body['assignee'] duration = int(body['duration']) except (KeyError, ValueError): raise web.badrequest() request_id = data.create_request(device_name, assignee, duration, boot_config) mozpool.mozpool.driver.handle_event(request_id, 'find_device', None) response_data = {'request': data.request_config(request_id)} if data.request_status(request_id)['state'] == 'closed': raise ConflictJSON(response_data) return response_data
def PUT(self,noteID): try: ID = int(noteID) lab = 0 dataobject = json.loads(web.data()) titlenew = dataobject['title'] contentnew = dataobject['content'] categorynew = dataobject['category'] labelsnew = dataobject['labels'] labelsSplit = labelsnew.split(',') for i in range(len(labelsSplit)): for j in range(len(labels)): if json.dumps(labels[j]) == json.dumps(labelsSplit[i]): lab = 1 if lab == 0: labels.append(labelsSplit[i]) lab = 0 for index in range(len(notes)): if ID == int(notes[index]["ID"]): notes[index].update(title=titlenew, content=contentnew, category=categorynew, labels=labelsSplit) return json.dumps(notes[index]) except ValueError: web.badrequest() return json.dumps(statement[1])
def POST(self): web.header('Content-type', 'application/json') request_input = web.input(askerUrn='', questionUrn='', actorUrn='') asker_urn = request_input.askerUrn question_urn = request_input.questionUrn actor_urn = request_input.actorUrn if asker_urn == '' or question_urn == '' or actor_urn == '': return web.badrequest() key = StoreUtils.Question.createKey(askerUrn=asker_urn, questionUrn=question_urn) question_data = Store.Question.get(key=key) asker_contact_info = Store.Contact.find({'member_urn': asker_urn}) question_data['asker_name'] = asker_contact_info[0]['name'] if len(asker_contact_info) > 0 else "" reply_key = StoreUtils.Reply.createKey(askerUrn=asker_urn, questionUrn=question_urn, actorUrn=actor_urn) reply_data = Store.Reply.get(key=reply_key) return json.dumps({"question_data": question_data, "reply_data": reply_data})
def _GET(self, *param, **params): tag_id = param[0] if not validates_param_id(self, tag_id): self.logger.debug( "Failed to get tag. The value of parameter is invalid.") return web.badrequest(self.view.alert) tag = findby1(self.orm, tag_id) if not tag: self.logger.debug("Failed to get tag. No such tag - id=%s" % tag_id) return web.notfound() self.view.tag = tag return True
def DELETE(self, path): web.header('Content-Type', 'text; charset=UTF-8') path = str(path) j = web.input() if path == '/': if 'paths' not in j or 'lock_ids' not in j: raise web.badrequest() for path, lock_id in\ zip(j['paths'].split('\n'), j['lock_ids'].split('\n')): if _locks[path].lock_id == int(lock_id): _cancel_lock(path) return 'OK'
def _DELETE(self, *param, **params): tag_id = param[0] if not validates_param_id(self, tag_id): self.logger.debug( "Failed to delete tag. The value of parameter is invalid.") return web.badrequest(self.view.alert) tag = findby1(self.orm, tag_id) if not tag: self.logger.debug("Failed to delete tag. No such tag - id=%s" % tag_id) return web.notfound() delete(self.orm, tag) return web.seeother("/%s.%s" % ("tag", "part"))
def PUT(self, cluster_id): cluster = self.get_object_or_404( Cluster, cluster_id, log_404=("warning", "Error: there is no cluster " "with id '{0}' in DB.".format(cluster_id))) task_manager = DeploymentTaskManager(cluster_id=cluster.id) try: task = task_manager.execute() except Exception as exc: logger.warn(u'ClusterChangesHandler: error while execution' ' deploy task: {0}'.format(exc.message)) raise web.badrequest(exc.message) return TaskHandler.render(task)
def POST(self): """处理 POST 数据 """ querys = web.input(chs='300x300') # 因为 web.input() 的返回的是 unicode 编码的数据, # 所以将数据按 utf8 编码以便用来生成二维码 chl = querys.chl.encode('utf8') chs = querys.chs if chl is None or chs is None: return web.badrequest() chld = querys.chld args = self.handle_parameter(chl, chld, chs) MIME, data = self.show_image(**args) web.header('Content-Type', MIME) return data
def POST_AUTH(self, capsule_id, channel): try: post_data = json.loads(web.data().decode()) except JSONDecodeError: raise web.badrequest() try: c = EditorCapsule.selectBy(id=int(capsule_id), channel=channel).getOne() except SQLObjectNotFound: raise web.notfound() if {'duration', 'template', 'content'} != set(post_data.keys()): raise web.badrequest() try: s = EditorSlide(s_order=c.slides.count(), capsule=c, **post_data) except SQLObjectIntegrityError: raise web.badrequest() EditorSlide.rectify_s_order(c.id) web.header( 'Location', '/channels/{}/api/capsules/{}/slides/{}'.format( channel.id, capsule_id, s.id)) raise web.created()
def checked_data(self, validate_method=None, **kwargs): try: data = kwargs.pop('data', web.data()) method = validate_method or self.validator.validate valid_data = method(data, **kwargs) except ( errors.InvalidInterfacesInfo, errors.InvalidMetadata ) as exc: notifier.notify("error", str(exc)) raise web.badrequest(message=str(exc)) except ( errors.AlreadyExists ) as exc: err = web.conflict() err.message = exc.message raise err except ( errors.InvalidData, Exception ) as exc: raise web.badrequest(message=str(exc)) return valid_data
def exec_query(query, read=False): conn = psycopg2.connect(host='db', user='******', password='******') conn.autocommit = True cur = conn.cursor() try: cur.execute(query) except Exception as e: traceback.print_exc() return web.badrequest(message=str(e)) finally: conn.close() if read: return cur.fetchall() else: return True
def checked_data(self, validate_method=None): try: if validate_method: data = validate_method(web.data()) else: data = self.validator.validate(web.data()) except ( errors.InvalidInterfacesInfo, errors.InvalidMetadata ) as exc: notifier.notify("error", str(exc)) raise web.badrequest(message=str(exc)) except ( errors.AlreadyExists ) as exc: err = web.conflict() err.message = exc.message raise err except ( errors.InvalidData, Exception ) as exc: raise web.badrequest(message=str(exc)) return data
def GET(self): try: data = web.input(tag=[]) if data.tag: tagFilter = data.tag # TODO validate else: tagFilter = None except (ValueError, KeyError): web.badrequest() return None networkIDs = model.getNetworkIDs(web.ctx.veerezoDB, web.ctx.username, tagFilter) result = [] for id in networkIDs: d = {} d['network'] = '/networks/{0}'.format(id) result.append(d) return result
def GET(self, deviceId): """ Get notification settings for device. :: GET /_notifications/{deviceId}/settings Returns: :: { "email_addr": "*****@*****.**", "windowsize": 3600, "sensitivity": 0.99999, "last_timestamp": "2014-02-06 00:00:00", "uid": "9a90eaf2-6374-4230-aa96-0830c0a737fe" } :param email_addr: Target email address associated with device :type email_addr: string :param windowsize: Notification window in seconds during which no other notifications for a given instance should be sent to a given device :type windowsize: int :param sensitivity: Anomaly score threshold that should trigger a notification :type sensitivity: float :param last_timestamp: Last updated timestamp :type last_timestamp: timestamp :param uid: Notification ID :type uid: str """ if deviceId: try: with web.ctx.connFactory() as conn: settingsRow = repository.getDeviceNotificationSettings(conn, deviceId) settingsDict = dict([(col.name, settingsRow[col.name]) for col in schema.notification_settings.c]) self.addStandardHeaders() return utils.jsonEncode(settingsDict) except ObjectNotFoundError: return web.notfound("Notification Settings not found: %s" % deviceId) else: log.error("Missing device ID, raising BadRequest exception") raise web.badrequest("Missing device ID")
def _GET(self, *param, **params): host_id = self.chk_hostby1(param) if host_id is None: return web.notfound() b64name = param[1] if not (b64name and host_id): return web.badrequest() name = base64_decode(str(b64name)) (target, device) = name.split("@") net = NetworkAddress(target) ipaddr = net.ipaddr netmask = net.netmask netlen = net.netlen gateway = _('N/A') flags = _('N/A') ref = _('N/A') use = _('N/A') metric = _('N/A') parser = Parser() status = parser.do_status() for _k,_v in status.iteritems(): for _k2,_v2 in _v.iteritems(): if name == "%s@%s" % (_k2,_k,): gateway = _v2['gateway'] flags = _v2['flags'] ref = _v2['ref'] use = _v2['use'] metric = _v2['metric'] route = dict(name=name, ipaddr=ipaddr, netmask=netmask, netlen=netlen, device=device, gateway=gateway, flags=flags, ref=ref, use=use, metric=metric, ) self.view.route = route return True
def POST(self, key=None): if key is None: raise web.badrequest() else: response = {} obj_data = json.loads(web.data()) db_doc = coll.find_one({'key': key}) if db_doc == None: response['Status'] = 'Created' coll.insert_one({'key': key, 'msg': obj_data['message']}) else: response['Status'] = 'OK' db_doc['msg'] = obj_data['message'] if cache.exists(key): cache.set(key, obj_data['message']) return json.dumps(response)
def PUT(self, key=None): if key is None: raise web.badrequest() else: response = {} obj_data = json.loads(web.data()) db_doc = coll.find_one({'key': key}) if db_doc != None: db_doc['msg'] = obj_data['message'] if cache.exists(key): cache.set(key, obj_data['message']) response['Status'] = 'OK' else: response['Status'] = 'Not found' raise web.notfound(json.dumps(response)) return json.dumps(response)
def _POST(self, *param, **params): if not validates_user(self): return web.badrequest(self.view.alert) engine = get_engine() metadata = get_metadata() session = get_session() try: metadata.drop_all() metadata.tables['machine2jobgroup'].create() metadata.create_all() except Exception, e: traceback.format_exc() raise Exception('Initializing/Updating a database error - %s' % ''.join(e.args))
def UPDATE(directory, add=True): """Add pair of directory/server to the name server.""" web.header('Content-Type', 'text/plain; charset=UTF-8') i = web.input() srv = i['srv'] if directory == '/': if 'dirs' not in i: raise web.badrequest() for directory in i['dirs'].split('\n'): if not directory: UPDATE_PATH(directory, srv, add) else: UPDATE_PATH(directory, srv, add) return 'ok'
def POST(self): web.header('Content-type', 'application/json') request_input = web.input(askerUrn='', questionUrn='') asker_urn = request_input.askerUrn question_urn = request_input.questionUrn if asker_urn == '' or question_urn == '': return web.badrequest() question_key = StoreUtils.Question.createKey(askerUrn=asker_urn, questionUrn=question_urn) question_data = Store.Question.get(key=question_key) reply_data = list(Store.Reply.fetch(askerUrn=asker_urn, questionUrn=question_urn)) for data in reply_data: c_actor = data['actor_urn'] actor_contact_info = Store.Contact.find({'member_urn': c_actor}) data['actor_name'] = actor_contact_info[0]['name'] if len(actor_contact_info) > 0 else "" return json.dumps({'question_data': question_data, 'reply_data': reply_data})
def POST(self, id): id = int(id) i = web.input() code = i.get("code", None) date = i.get("date", None) print code, date if code is None or date is None: raise web.badrequest() return {"error": "wrong parameters"} if tasks.has_key(id): tasks[id] = (code, date) status = "updated" else: raise web.notfound() status = "task not found" return {'status': status}
def _DELETE(self, *param, **params): icon_filename = param[0] if is_path(icon_filename) is True: return web.badrequest("Not to include the path.") icon_realpath = ICON_DIR_TPL % (karesansui.dirname, icon_filename) if not os.path.exists(icon_realpath): return web.notfound("icon not exists") try: remove_file(icon_realpath) except OSError, ose: self.logger.error("Failed to remove icon file. - filename=%s" % icon_filename) raise # return 500(Internal Server Error)
def get_data(name=None, mandatory=[], authorized=[], forbidden=[]): data = web.data() if not data: raise web.badrequest( "You must suply some data. (mandatory: %s, authorized: %s)" % (mandatory, authorized)) if "CONTENT_TYPE" not in web.ctx.env: raise web.badrequest("You must specify a Content-Type.") ctype = web.ctx.env.get("CONTENT_TYPE") try: if "text/xml" in ctype or "application/xml" in ctype: data, dname = pyxml.loads(data, retname=True) print("received \"%s\"" % dname) print(data) if name and dname != name: data = None elif "application/json" in ctype: data = json.loads(data.decode()) if name: data = data.get(name, None) else: raise web.badrequest("Content-type \"%s\" is not allowed." % ctype) except (AttributeError, ValueError): raise web.badrequest("Could not decode input data (%s)." % data) if name and data is None: raise web.badrequest( "The object you are sending does not contain a \"%s\" entry." % name) if not all(x in data for x in mandatory): raise web.badrequest("The following elements are missing, \"%s\"" % [x for x in mandatory if x not in data]) if any(x in data for x in forbidden): raise web.badrequest("You are not allowed to send any of \"%s\"" % [x for x in forbidden if x in data]) if authorized and any(x not in authorized for x in data): raise web.badrequest("You are not allowed to send any of \"%s\"" % ([x for x in data if x not in authorized])) return data
def POST(self, key): entity = ndb.Key(urlsafe=key).get() if not entity: raise web.badrequest() else: form = create_form(entity) name = entity.key.kind() title = 'Update %s' % name if not form.validates(): return render.form(form=form, title=title, mce_elms='content') else: entity = consume_form(entity, form.d) entity.put() return web.seeother('/admin/list/%s' % name.lower())