def POST(self, courseid): """ GET request """ course, _ = self.get_course_and_check_rights(courseid) user_input = web.input(tasks=[], classrooms=[], users=[]) if "filter_type" not in user_input or "type" not in user_input or "format" not in user_input or user_input.format not in self.valid_formats: raise web.notfound() tasks = course.get_tasks().keys() for i in user_input.tasks: if i not in tasks: raise web.notfound() if user_input.filter_type == "users": self._validate_list(user_input.users) classrooms = list(self.database.classrooms.find({"courseid": courseid, "students": {"$in": user_input.users}})) else: self._validate_list(user_input.classrooms) classrooms = list(self.database.classrooms.find({"_id": {"$in": [ObjectId(cid) for cid in user_input.classrooms]}})) classrooms = dict([(username, classroom) for classroom in classrooms for username in classroom["students"]]) submissions = list(self.database.submissions.find({"username": {"$in": classrooms.keys()}, "taskid": {"$in": user_input.tasks}, "courseid": course.get_id(), "status": {"$in": ["done", "error"]}})) if user_input.type == "single": submissions = self.submission_manager.keep_best_submission(submissions) web.header('Content-Type', 'application/x-gzip', unique=True) web.header('Content-Disposition', 'attachment; filename="submissions.tgz"', unique=True) return self.submission_manager.get_submission_archive(submissions, list(reversed(user_input.format.split('/'))), classrooms)
def GET(self, name=None): """ Get the static content of relative path "name" """ if not name: # If simply /index.py/ is specified, load the main front-end page: #name = 'softchordweb.html' # Modified version of PyJamas-generated softchordweb.html that has # the title changed to "softChord Web": name = 'softchordweb-custom.html' ext = name.split(".")[-1] # Figure out what is the type of this static file: cType = { "js":"application/x-javascript", "txt":"text/plain", "css":"text/css", "html":"text/html", "png":"images/png", "jpg":"image/jpeg", "gif":"image/gif", "ico":"image/x-icon" } # If this file is in static/output, then it's a PyJamas-generated file: if name in os.listdir('static/output'): path = 'static/output/%s' % name #return "ATTEMPTING TO READ: %s" % path web.header("Content-Type", cType[ext]) return open(path, "rb").read() else: # If the static contents was not found web.notfound() return "NOT FOUND: %s" % name
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 _GET(self, *param, **params): _prep_console() (host_id, guest_id) = self.chk_guestby1(param) if guest_id is None: return web.notfound() model = findbyguest1(self.orm, guest_id) kvc = KaresansuiVirtConnection() try: domname = kvc.uuid_to_domname(model.uniq_key) if not domname: return web.notfound() dom = kvc.search_guests(domname)[0] document = XMLParse(dom.XMLDesc(1)) self.view.graphics_port = XMLXpath(document, '/domain/devices/graphics/@port') self.view.xenname = XMLXpath(document, '/domain/name/text()') finally: kvc.close() h_model = findbyhost1(self.orm, host_id) try: from karesansui.lib.utils import get_ifconfig_info device = KVM_BRIDGE_PREFIX + "0" self.view.host_ipaddr = get_ifconfig_info(device)[device]["ipaddr"] except: try: self.view.host_ipaddr = h_model.hostname.split(":")[0].strip() except: self.view.host_ipaddr = socket.gethostbyname(socket.gethostname()) return True
def delete(self, uuid): """ ### Request `DELETE /birds/{id}` Empty body ### Response Valid status codes: - `200 OK` if the bird has been removed - `404 Not found` if the bird didn't exist Empty body expected. """ try: bird = Bird.objects.get(id=uuid) except mongoengine.DoesNotExist: raise web.notfound() except mongoengine.ValidationError: raise web.notfound() bird.delete()
def get_course_and_check_rights(self, courseid, taskid=None, allow_all_staff=True): """ Returns the course with id ```courseid``` and the task with id ```taskid```, and verify the rights of the user. Raise web.notfound() when there is no such course of if the users has not enough rights. :param courseid: the course on which to check rights :param taskid: If not None, returns also the task with id ```taskid``` :param allow_all_staff: allow admins AND tutors to see the page. If false, all only admins. :returns (Course, Task) """ try: if self.user_manager.session_logged_in(): course = self.course_factory.get_course(courseid) if allow_all_staff: if not self.user_manager.has_staff_rights_on_course(course): raise web.notfound() else: if not self.user_manager.has_admin_rights_on_course(course): raise web.notfound() if taskid is None: return (course, None) else: return (course, course.get_task(taskid)) else: raise web.notfound() except: raise web.notfound()
def GET(self, catrel_name, arch_name, osrel_name, catalogname): """Get a srv4 reference by catalog ane catalogname.""" web.header('Access-Control-Allow-Origin', '*') try: sqo_osrel, sqo_arch, sqo_catrel = models.GetSqoTriad( osrel_name, arch_name, catrel_name) except sqlobject.main.SQLObjectNotFound: raise web.notfound( cjson.encode({'message': 'catalog %s %s %s not found' % (osrel_name, arch_name, catrel_name)})) join = [ sqlbuilder.INNERJOINOn(None, models.Srv4FileInCatalog, models.Srv4FileInCatalog.q.srv4file==models.Srv4FileStats.q.id), ] res = models.Srv4FileStats.select( sqlobject.AND( models.Srv4FileInCatalog.q.osrel==sqo_osrel, models.Srv4FileInCatalog.q.arch==sqo_arch, models.Srv4FileInCatalog.q.catrel==sqo_catrel, models.Srv4FileStats.q.catalogname==catalogname, models.Srv4FileStats.q.use_to_generate_catalogs==True), join=join, ) try: srv4 = res.getOne() mimetype, data = srv4.GetRestRepr(quick=True) web.header('Content-type', mimetype) return cjson.encode(data) except sqlobject.main.SQLObjectNotFound: data = {'message': 'no %s %s %s %s packages found' % (catrel_name, arch_name, osrel_name, catalogname)} raise web.notfound(cjson.encode(data)) except sqlobject.dberrors.OperationalError as exc: raise web.internalerror(exc)
def POST(self): http_input = web.input(tournament_id=None) tournament_id = http_input.tournament_id if tournament_id is None: raise web.notfound() tournament = Tournament.get(int(tournament_id), joined_attrs=["results"]) if tournament is None: raise web.notfound() results_grid = tournament_forms.EditResultsGrid().bind(tournament.results, data=http_input) if results_grid.validate(): # If the form was properly filled, updates the model and returns the standard table # Besides, we sort the results "from the outside" since they are directly returned (commit & no load) results_grid.sync() tournament.sort_results() results = config.views.results(tournament) statistics = config.views.statistics(tournament) else: # Otherwise, returns the editing grid results = config.views.results_admin(tournament, results_grid) statistics = None # Returns the dictionary return dict(results=results, statistics=statistics)
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, courseid, taskid, path): """ GET request """ if self.user_manager.session_logged_in(): try: course = self.course_factory.get_course(courseid) if not self.user_manager.course_is_open_to_user(course): return self.template_helper.get_renderer().course_unavailable() task = course.get_task(taskid) if not self.user_manager.task_is_visible_by_user(task): return self.template_helper.get_renderer().task_unavailable() path_norm = posixpath.normpath(urllib.unquote(path)) public_folder_path = os.path.normpath(os.path.realpath(os.path.join(task.get_directory_path(), "public"))) file_path = os.path.normpath(os.path.realpath(os.path.join(public_folder_path, path_norm))) # Verify that we are still inside the public directory if os.path.normpath(os.path.commonprefix([public_folder_path, file_path])) != public_folder_path: raise web.notfound() if os.path.isfile(file_path): mimetypes.init() mime_type = mimetypes.guess_type(file_path) web.header('Content-Type', mime_type[0]) with open(file_path) as static_file: return static_file.read() else: raise web.notfound() except: if web.config.debug: raise else: raise web.notfound() else: return self.template_helper.get_renderer().index(self.user_manager.get_auth_methods_fields(), False)
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, name, glyphid): if not is_loggedin(): return web.notfound() master = models.Master.get(fontname=name) if not master: return web.notfound() x = web.input(pointnr='', source='', x='', y='') query = models.GlyphOutline.filter(idmaster=master.idmaster, fontsource=x.source.upper(), glyphname=glyphid, pointnr=x.pointnr) query.update(dict(x=x.x, y=x.y)) web.ctx.orm.commit() writeGlyphlist(master, glyphid) glyphA = models.Glyph.get(idmaster=master.idmaster, fontsource='A', name=glyphid) glyphB = models.Glyph.get(idmaster=master.idmaster, fontsource='A', name=glyphid) import xmltomf xmltomf.xmltomf1(master, glyphA, glyphB) makefont(working_dir(), master) M_glyphjson = get_edges_json(u'%s.log' % master.fontname, glyphid) if x.source.upper() == 'A': glyphjson = get_edges_json(u'%sA.log' % master.fontname, glyphid) else: glyphjson = get_edges_json(u'%sB.log' % master.fontname, glyphid) return simplejson.dumps({'M': M_glyphjson, 'R': glyphjson})
def GET(self, name, glyphid): """ View single post """ if not is_loggedin(): raise seeother('/login') master = models.Master.get(fontname=name) if not master: return web.notfound() if not models.GlyphOutline.exists(idmaster=master.idmaster, glyphname=glyphid): return web.notfound() A_glyphjson = get_edges_json(u'%sA.log' % master.fontname, glyphid) B_glyphjson = get_edges_json(u'%sB.log' % master.fontname, glyphid) M_glyphjson = get_edges_json(u'%s.log' % master.fontname, glyphid) localparametersA = models.LocalParam.get(idlocal=master.idlocala) localparametersB = models.LocalParam.get(idlocal=master.idlocalb) globalparams = models.GlobalParam.get(idglobal=master.idglobal) a_original_glyphjson = get_edges_json_from_db(master, glyphid, 'A') b_original_glyphjson = get_edges_json_from_db(master, glyphid, 'B') return render.view(master, glyphid, A_glyphjson, B_glyphjson, M_glyphjson, localparametersA, localparametersB, globalparams, origins={'a': a_original_glyphjson, 'b': b_original_glyphjson})
def _DELETE(self, *param, **params): (host_id, guest_id) = self.chk_guestby1(param) if guest_id is None: return web.notfound() if is_int(param[2]) is False: return web.notfound() nic_id = int(param[2]) model = findbyguest1(self.orm, guest_id) # virt kvc = KaresansuiVirtConnection() try: domname = kvc.uuid_to_domname(model.uniq_key) if not domname: return web.conflict(web.ctx.path) virt = kvc.search_kvg_guests(domname)[0] guest = MergeGuest(model, virt) nic_info = virt.get_interface_info()[nic_id] finally: kvc.close() mac = nic_info["mac"]["address"] self.logger.debug('spinning off delete_nic_job dom=%s, mac=%s' % (domname, mac)) if delete_nic_job(self,model,domname,mac) is True: return web.accepted() else: return False
def _GET(self, *param, **params): (host_id, guest_id) = self.chk_guestby1(param) if guest_id is None: return web.notfound() model = findbyguest1(self.orm, guest_id) # virt kvc = KaresansuiVirtConnection() try: domname = kvc.uuid_to_domname(model.uniq_key) if not domname: return web.notfound() virt = kvc.search_kvg_guests(domname)[0] vcpus_info = virt.get_vcpus_info() self.view.max_vcpus_limit = kvc.get_max_vcpus() self.view.max_vcpus = vcpus_info['bootup_vcpus'] self.view.vcpus_limit = vcpus_info['max_vcpus'] self.view.vcpus = vcpus_info['vcpus'] self.view.cpuTime = virt.get_info()['cpuTime'] self.view.hypervisor = virt.get_info()['hypervisor'] self.view.guest = model finally: kvc.close() return True
def get_context(self, repo, sha): d = self.get_base_context(repo, sha, "") try: commit = self.repo.get_object(sha) except KeyError: raise web.notfound("No such commit") if commit.__class__.__name__ != "Commit": raise web.notfound("Not a valid commit") files = [] for change in git.get_changes(self.repo, commit): if change.type == 'delete': files.append((ACTION_ICONS.get('delete'), change.old.path, commit.parents[0], 'Deleted')) else: diff = git.unified_diff(self.repo, change.old, change.new) html = renderer.render_diff(diff) files.append((ACTION_ICONS.get(change.type, 'fire'), change.new.path, commit.id, html)) d['inline_style'] = renderer.get_style() d['files'] = files d['branch'] = commit.id d['commit'] = commit d['branch_name'] = commit.id[:10] return d
def _GET(self, *param, **params): (host_id, guest_id) = self.chk_guestby1(param) if guest_id is None: return web.notfound() if is_int(param[2]) is False: return web.badrequest() disk_id = int(param[2]) model = findbyguest1(self.orm, guest_id) # virt kvc = KaresansuiVirtConnection() try: domname = kvc.uuid_to_domname(model.uniq_key) if not domname: return web.notfound() virt = kvc.search_kvg_guests(domname)[0] guest = MergeGuest(model, virt) self.view.guest = guest self.view.disk_info = virt.get_disk_info()[disk_id] finally: kvc.close() return True
def _GET(self, *param, **params): host_id = self.chk_hostby1(param) if host_id is None: return web.notfound() network_name = param[1] if not (network_name and host_id): return web.badrequest() kvc = KaresansuiVirtConnection() try: try: network = kvc.search_kvn_networks(network_name)[0] # throws KaresansuiVirtException info = network.get_info() except KaresansuiVirtException, e: # network not found self.logger.debug("Network not found. name=%s" % network_name) return web.notfound() finally: kvc.close() cidr = '%s/%s' % (info['ip']['address'], info['ip']['netmask']) network = dict(name=info['name'], cidr=cidr, dhcp_start=info['dhcp']['start'], dhcp_end=info['dhcp']['end'], forward_dev=info['forward']['dev'], forward_mode=info['forward']['mode'], bridge=info['bridge']['name'], ) self.view.info = info self.view.network = network return True
def GET(self, uri): dirs = uri.split('/') if dirs[0] in ['', 'js', 'css', 'img', 'favicon.ico']: filename = uri if dirs[0] == '': filename = 'index.html' try: with open(filename) as staticfile: filecontent = staticfile.read() files[filename] = filecontent return filecontent except IOError, e: if e.errno == 2: raise web.notfound() if files.has_key(filename): return files[filename] else: try: with open(filename) as staticfile: filecontent = staticfile.read() files[filename] = filecontent return filecontent except IOError, e: if e.errno == 2: raise web.notfound()
def GET(self, table, what): try: table = table_map[table] except KeyError: raise web.notfound() if not r_safeproperty.match(what): raise web.notfound() #if `what` is not there in the `table` (provide available options rather than 404???) try: maxnum = float(db.select(table, what='max(%s) as m' % what, vars=locals())[0].m) except: raise web.notfound() items = db.select(table, what="*, 100*(%s/$maxnum) as pct" % what, order='%s desc' % what, where='%s is not null' % what, vars=locals()).list() for item in items: if table == 'district': item.id = 'd' + item.name item.path = '/us/' + item.name.lower() elif table == 'politician': state = '-'+item.district_id.split('-')[0] if item.district_id else '' item.name = '%s %s (%s%s)' % (item.firstname, item.lastname, (item.party or 'I')[0], state) item.path = '/p/' + item.id return render.dproperty(items, what, namesmap().get(what))
def GET(self, catrel_name, arch_name, osrel_name, catalogname): """Get a srv4 reference by catalog ane catalogname.""" configuration.SetUpSqlobjectConnection() try: sqo_osrel, sqo_arch, sqo_catrel = pkgdb.GetSqoTriad( osrel_name, arch_name, catrel_name) except sqlobject.main.SQLObjectNotFound: raise web.notfound() join = [ sqlbuilder.INNERJOINOn(None, models.Srv4FileInCatalog, models.Srv4FileInCatalog.q.srv4file==models.Srv4FileStats.q.id), ] res = models.Srv4FileStats.select( sqlobject.AND( models.Srv4FileInCatalog.q.osrel==sqo_osrel, models.Srv4FileInCatalog.q.arch==sqo_arch, models.Srv4FileInCatalog.q.catrel==sqo_catrel, models.Srv4FileStats.q.catalogname==catalogname, models.Srv4FileStats.q.use_to_generate_catalogs==True), join=join, ) try: srv4 = res.getOne() mimetype, data = srv4.GetRestRepr() web.header('Content-type', mimetype) web.header('Access-Control-Allow-Origin', '*') return cjson.encode(data) except sqlobject.main.SQLObjectNotFound: raise web.notfound() except sqlobject.dberrors.OperationalError, e: raise web.internalerror(e)
def GET(self, courseid, taskid, path): """ GET request """ if User.is_logged_in(): try: course = FrontendCourse(courseid) if not course.is_open_to_user(User.get_username()): return renderer.course_unavailable() task = course.get_task(taskid) if not task.is_visible_by_user(User.get_username()): return renderer.task_unavailable() path_norm = posixpath.normpath(urllib.unquote(path)) public_folder_path = os.path.normpath(os.path.realpath(os.path.join(INGIniousConfiguration["tasks_directory"], courseid, taskid, "public"))) file_path = os.path.normpath(os.path.realpath(os.path.join(public_folder_path, path_norm))) # Verify that we are still inside the public directory if os.path.normpath(os.path.commonprefix([public_folder_path, file_path])) != public_folder_path: raise web.notfound() if os.path.isfile(file_path): mimetypes.init() mime_type = mimetypes.guess_type(file_path) web.header('Content-Type', mime_type[0]) with open(file_path) as static_file: return static_file.read() else: raise web.notfound() except: if web.config.debug: raise else: raise web.notfound() else: return renderer.index(False)
def _locate(self, id): """ See what we know about this uri... uri is in fact a SHA-1 hash of the uri """ def ithas(key, cache): if key in cache: return cache[key] return None unknown = get_unknown() known = get_known() u = ithas(id, unknown) if u: web.notfound() return None u = ithas(id, known) if not u: u = get_manager().load(id) if not u: unknown[id] = True web.notfound() return None known[id] = u return u
def GET(self, deviceId, notificationId): """ Get single notification :: GET /_notifications/{deviceId}/{notificationId} Returns: :: { "uid": "e78599c4-758b-4c6e-87b1-daabaccff798", "timestamp": "2014-02-07 16:26:44", "metric": "e5511f295a474037a75bc966d02b67d2", "acknowledged": 0, "seen": 0, "windowsize": 3600, "device": "9a90eaf2-6374-4230-aa96-0830c0a737fe" } :param uid: Notification ID :type uid: str :param timestamp: Notification timestamp :type timestamp: timestamp :param metric: Metric that triggered notification :type metric: str :param acknowledged: Acknowledged status :type acknowledged: int :param seen: Seen status :type seen: int :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 device: Device ID :type device: str """ # Update the last_timestamp for the notification device. try: with web.ctx.connFactory() as conn: repository.updateNotificationDeviceTimestamp(conn, deviceId) except ObjectNotFoundError: return web.notfound("Notification device not found: %s" % deviceId) try: with web.ctx.connFactory() as conn: notificationRow = repository.getNotification(conn, notificationId, NotificationHandler.fields) notificationDict = dict([(col, notificationRow[col]) for col in NotificationHandler.fields]) if notificationRow["device"] != deviceId: return web.notfound("Device not found: %s" % deviceId) self.addStandardHeaders() return utils.jsonEncode(notificationDict) except ObjectNotFoundError: return web.notfound("Notification not found: %s" % notificationId)
def get(self, uuid): """ ### Request `GET /birds/{id}` Empty body. ### Response Valid status codes: - `200 OK` if the bird exists - `404 Not found` if the bird does not exist A `404 Not found` is expected when the bird does not exist, but not for birds with `visible` set to `false`. The response body for a `200 OK` request can be found in `get-birds-id-response.json`. """ try: bird = Bird.objects.get(id=uuid) return self.format_bird(bird) except mongoengine.DoesNotExist: raise web.notfound() except mongoengine.ValidationError: raise web.notfound()
def POST(self): import datetime from dateutil import relativedelta table = 'cloud_host' data = _web.input() try: uuid = data.uuid duration = data.duration except AttributeError: raise _web.internalerror() if duration: try: duration = int(duration) except: raise _web.notfound() else: raise _web.notfound() try: old_duration = db.select('cloud_host',where="`uuid`='%s'" % uuid).list()[0]['expired_time'] #如果已经存在duration if old_duration: old_year,old_month,old_day = map(int,(old_duration[:4],old_duration[4:6],old_duration[6:8])) old_date = datetime.date(year=old_year,month=old_month,day=old_day) next_month = old_date + relativedelta.relativedelta(months=duration) next_month = next_month.strftime("%Y%m%d") db.update(table,where="`uuid`='%s'" % uuid,enable=1,expired_time = next_month) return {'message':'success'} #如果无duration,设置enable=1,和expired_time else: nextmonth = datetime.date.today() + relativedelta.relativedelta(months=duration) nextmonth = nextmonth.strftime("%Y%m%d") db.update(table,where="`uuid`='%s'" % uuid,enable=1,expired_time = nextmonth) return {'message':'success'} except Exception,e: raise _web.notfound(message=e)
def _DELETE(self, *param, **params): host_id = self.chk_hostby1(param) if host_id is None: return web.notfound() device = param[1] if device is None: return web.notfound() cmdname = u"Delete Bonding Setting" cmd = BONDING_COMMAND_DELETE options = {} options['dev'] = device options["succession"] = None _cmd = dict2command( "%s/%s" % (karesansui.config['application.bin.dir'], cmd), options) _jobgroup = JobGroup(cmdname, karesansui.sheconf['env.uniqkey']) _job = Job('%s command' % cmdname, 0, _cmd) _jobgroup.jobs.append(_job) host = findbyhost1(self.orm, host_id) _machine2jobgroup = m2j_new(machine=host, jobgroup_id=-1, uniq_key=karesansui.sheconf['env.uniqkey'], created_user=self.me, modified_user=self.me, ) save_job_collaboration(self.orm, self.pysilhouette.orm, _machine2jobgroup, _jobgroup, ) return web.accepted()
def deleteModel(metricId): try: with web.ctx.connFactory() as conn: metricRow = repository.getMetric(conn, metricId) except app_exceptions.ObjectNotFoundError: raise web.notfound("ObjectNotFoundError Metric not found: Metric ID: %s" % metricId) if metricRow.datasource == "autostack": raise NotAllowedResponse( {"result": ("Not a standalone model=%s; datasource=%s. Unable" " to DELETE from this endpoint") % (metricId, metricRow.datasource,) }) log.debug("Deleting model for %s metric=%s", metricRow.datasource, metricId) with web.ctx.connFactory() as conn: repository.deleteModel(conn, metricId) # NOTE: this is the new way using datasource adapters try: createDatasourceAdapter(metricRow.datasource).unmonitorMetric(metricId) except app_exceptions.ObjectNotFoundError: raise web.notfound( "ObjectNotFoundError Metric not found: Metric ID: %s" % (metricId,)) return utils.jsonEncode({'result': 'success'})
def POST(self): x = web.input(master_id='', project_id='', task_id='') project = models.Project.get(id=x.project_id) if not project: raise web.notfound() master = models.Master.get(id=x.master_id) if not master: return web.notfound() if x.task_id: from celery.result import AsyncResult from metapolator.config import celery res = AsyncResult(x.task_id, backend=celery.backend) if res.ready(): master.task_completed = True web.ctx.orm.commit() return ujson.dumps({'done': True}) else: master.task_updated = datetime.datetime.now() web.ctx.orm.commit() return ujson.dumps({'done': False, 'task_id': x.task_id}) master.task_completed = True web.ctx.orm.commit() return ujson.dumps({'done': True})
def GET(self, name): if not is_coordinator(): raise web.notfound() if name == "contacts.xls": return self.download_contacts() raise web.notfound()