def GET(self): # Get the request data and look whether the correct credentials were provided data = web.input() if 'Password' not in data or 'User' not in data: raise web.NotFound() password_given = data['Password'] user_given = data['User'] if password_given != password_tr or user_given != user_tr: raise web.NotFound() # Get the apartment object, turn it into json and make the response web.header('Content-Type', 'application/json') apartment_copy = copy.deepcopy(apartment.get_dict()) # Add the credentials to the message object apartment_copy['Password'] = password_tr apartment_copy['User'] = user_tr # Add the behavior information to the message object apartment_copy['lamp_movement'] = lamp_movement_reaction apartment_copy['no_movement_time'] = no_movement_interval apartment_copy['no_water_time'] = no_water_interval # Add the alarm information to the message object apartment_copy['alarm'] = alarms_all apartment_copy['alarmList'] = alarmList apartment_copy['alarm_urgent'] = alarms_urgend_all apartment_copy['alarmUrgentList'] = alarmsUrgentList json_apartment = json.dumps(apartment_copy) return json_apartment
def GET(self, user): baseurl = user.strip('/').split('/') if len(baseurl) > 0: user = baseurl[-1] if not user: raise steam.items.InventoryError("Need an ID") try: prof = models.user(user).load() ctx = models.sim_context(prof).load() for ct in (ctx or []): ct.setdefault("inventory_logo", '') return template.sim_selector(prof, ctx) except steam.items.InventoryError as E: raise web.NotFound( template.errors.generic( "Failed to load backpack ({0})".format(E))) except steam.user.ProfileError as E: raise web.NotFound( template.errors.generic( "Failed to load profile ({0})".format(E))) except steam.api.HTTPError as E: raise web.NotFound( template.errors.generic( "Couldn't connect to Steam (HTTP {0})".format(E))) except models.CacheEmptyError as E: raise web.NotFound(template.errors.generic(E))
def POST(self): # get the posted json object and turn it into a dictionary json_request = web.data() post_dict = json.loads(json_request) # check the credentials stored in the json if 'Password' not in post_dict or 'User' not in post_dict: raise web.NotFound() password_given = post_dict['Password'] user_given = post_dict['User'] if password_given != password_tr or user_given != user_tr: raise web.NotFound() del post_dict['Password'] del post_dict['User'] # if the post object contains behavior information, update the values if 'lamp_movement' in post_dict: global no_movement_interval global lamp_movement_reaction no_movement_interval = int(post_dict['no_movement_time']) lamp_movement_reaction = post_dict['lamp_movement'] global no_water_interval no_water_interval = post_dict['no_water_time'] # adjust the state of both the real and the virtual apartment apartment.adjust_state(post_dict) if (not lamp_movement_reaction) and apartment.get_dev_status( 'Fedors_Zimmer', 'Lampe') == 'off': control.set_dev_state('Fedors_Zimmer', 'Lampe', 'off') # the reponse contains the current apartment state web.header('Content-Type', 'application/json') response = {'response': 'success'} json_resp = json.dumps(response) return json_resp
def GET(self, app, attachment_check=None): markup.init_theme(app) markup.set_navlink() try: schema = models.schema(scope=app) attribs = schema.attributes except (models.CacheEmptyError, models.ItemBackendUnimplemented) as E: raise web.NotFound(template.errors.generic(E)) attribute = None if attachment_check: attached_items = [] for attr in attribs: if str(attr.id) == attachment_check: attribute = attr break if not attribute: raise web.NotFound( template.errors.generic(attachment_check + ": No such attribute")) for item in schema.processed_items.values(): if attr.id in map(operator.itemgetter("id"), item.get("attrs", [])): attached_items.append(item) return template.attribute_attachments(app, attached_items, attribute) else: return template.schema_attributes(attribs)
def _error(e): # https://github.com/webpy/webpy/blob/master/web/webapi.py#L15 if e.response.status_code == 403: return web.Forbidden() elif e.response.status_code == 404: return web.NotFound() else: print(e) # traceback.print_exc() return web.NotFound()
def GET(self, command): """Handles get requests for certain commands.""" valid_get_commands = ('req_usage', 'req_log', 'add_credit', 'req_checkin') if command not in valid_get_commands: return web.NotFound() d = web.input() if 'jwt' not in d: return web.BadRequest() try: data = self.check_signed_params(d['jwt']) except ValueError as e: logger.error("Value error dispatching %s" % (command, )) return web.BadRequest(str(e)) except Exception as e: logger.error("Other error dispatching %s: %s" % (command, str(e))) raise if command == "req_usage": # NOTE: deprecated 2014oct23 return self.req_checkin() if command == "req_log": return self.req_log(data) elif command == "add_credit": return self.adjust_credits(data) elif command == "req_checkin": return self.req_checkin()
def GET(self, key): logger.info("woker %s" % 'redirect_to') logger.info("key=%s" % key) # print "key=%s" % key if key is None or len(key.strip()) == 0: logger.error('key is %s' % 'None') return web.NotFound('key is null') url = getUrl(key.strip()) if url is None: logger.error('geturl url is %s' % 'None') return web.NotFound(message='url not found') # return web.seeother(url, absolute=True)# TODO 检查语义是否合理 if not url.lower().startswith("http"): url = "http://%s" % url logger.info("url is %s, 302" % url) return web.redirect(url, '302')
def GET(self, name): if name == "about": return titled_render("About").about(about="About") elif name == "contact": return titled_render("Contact").about(about="Contact") else: return web.NotFound()
def load_machine(name): results = list(DB.select('machine', what='*', where='name = $name', vars=dict(name=name))) if not results: raise web.NotFound() return results[0]
def GET(self, request_packer, package): if not request_packer or not package: web.BadRequest() else: packer = pdb['packer-symlinks'].get( request_packer, request_packer) #try to resolve similar packers super_packer = pdb['super-packer'].get(packer, '') ret = pdb.get(package, {}).get(packer, False) ret = ret if ret else pdb.get(package, {}).get(super_packer, False) if not ret: try: if polite: local_announce( "Client `%s` asked for the tool `%s` in packer `%s` but i do not have it in my Database. Please update me!" % (web.ctx.ip, package, packer)) else: local_announce("404: no %s/%s for %s" % (request_packer, package, gethostbyaddr(web.ctx.ip)[0])) except Exception, e: print("Got Exception %s: %s" % (str(Exception), (e))) web.NotFound() return "not found. i'm so sorry :(" else:
def GET(self, app, user, cid=None): app = models.app_aliases.get(app, app) self._cid = cid markup.init_theme(app) try: userp = models.user(user).load() pack = models.inventory(userp, scope=app).load() items = pack["items"].values() equippeditems = {} classmap = set() slotlist = [] self._app = app markup.set_navlink( markup.generate_root_url("loadout/{0}".format(userp["id64"]), app)) # initial normal items try: sitems = models.schema(scope=app).processed_items.values() normalitems = views.filtering(sitems).byQuality("normal") equippeditems, slotlist, classmap = self.build_loadout( normalitems, equippeditems, slotlist, classmap) except models.CacheEmptyError: pass # Real equipped items equippeditems, slotlist, classmap = self.build_loadout( items, equippeditems, slotlist, classmap) return template.loadout(app, userp, equippeditems, sorted(classmap), self._slots_sorted + sorted(slotlist), cid) except steam.items.InventoryError as E: raise web.NotFound( template.errors.generic("Backpack error: {0}".format(E))) except steam.user.ProfileError as E: raise web.NotFound( template.errors.generic("Profile error: {0}".format(E))) except steam.api.HTTPError as E: raise web.NotFound( template.errors.generic( "Couldn't connect to Steam (HTTP {0})".format(E))) except models.ItemBackendUnimplemented: raise web.NotFound( template.errors.generic( "No backend found to handle loadouts for these items"))
def GET(self): rows = list(DB.select('machine', what='*')) if not rows: raise web.NotFound() for row in rows: row.locked_since = row.locked_since.isoformat() web.header('Content-type', 'text/json') return json.dumps(rows)
def GET(self): """ Scours RESOURCES for data samples, picks a random sample and publishes it """ log.debug("Servicing GET request") resource = utils.pick_one_random_item(RESOURCES) log.info("Picked %r" % resource.name) if not resource: log.debug("No resource Found(1)") raise web.NotFound() item = resource.get_one() if self.publishable(item): log.debug("Publishing item") return json.dumps(item) log.warning("No publishable item found") raise web.NotFound()
def GET(self, app, iid): user = None markup.init_theme(app) try: sitems = models.schema(scope=app).processed_items item = sitems[iid] if web.input().get("contents"): contents = item.get("contents") if contents: item = contents except steam.api.HTTPError as E: raise web.NotFound( template.errors.generic( "Couldn't connect to Steam (HTTP {0})".format(E))) except steam.items.SchemaError as E: raise web.NotFound( template.errors.generic("Couldn't open schema: {0}".format(E))) except KeyError: raise web.NotFound(template.item_error_notfound(iid)) except models.CacheEmptyError as E: raise web.NotFound(template.errors.generic(E)) except models.ItemBackendUnimplemented: raise web.NotFound( template.errors.generic( "No backend found to handle the given item, this could mean that the item has no available associated schema (yet)" )) caps = markup.get_capability_strings(item.get("caps", [])) try: assets = models.assets(scope=app).price_map price = markup.generate_item_price_string(item, assets) except models.CacheEmptyError: price = None # Strip off quality prefix for possessive name itemname = item["mainname"] if itemname.startswith("The "): item["ownedname"] = itemname[4:] else: item["ownedname"] = itemname return template.item(app, user, item, price=price, caps=caps)
def cmdDelete(self, request): self.checkAuth() meta = _StoreMeta.get_by_key_name(request) if not meta: raise web.NotFound() meta.delete() blobstore.delete(meta.blobKey) return 'OK'
def GET(self, themeFloder, file, other): try: f = open(self.staticFloder + themeFloder + '/' + file, 'rb') #if other=='css': contentType = mimetypes.guess_type(file)[0] web.header("Content-Type", contentType) return f.read() except: raise web.NotFound()
def POST(self, command): """Handles certain POST commands.""" # Always send back these headers. headers = {'Content-type': 'text/plain'} # Validate the exact endpoint. valid_post_commands = ('deactivate_number', 'deactivate_subscriber') if command not in valid_post_commands: return web.NotFound() # Get the posted data and validate. There should be a 'jwt' key with # signed data. That dict should contain a 'number' key -- the one we # want to deactivate. data = web.input() jwt = data.get('jwt', None) if not jwt: return web.BadRequest() serializer = itsdangerous.JSONWebSignatureSerializer( self.conf['bts_secret']) try: jwt = serializer.loads(jwt) except itsdangerous.BadSignature: return web.BadRequest() if command == 'deactivate_number': if 'number' not in jwt: return web.BadRequest() # The params validated, deactivate the number. ValueError is # raised if this is the subscriber's last number. # The number should correspond to an IMSI or give a 404 try: imsi = subscriber.get_imsi_from_number(jwt['number']) subscriber.delete_number(imsi, jwt['number']) except SubscriberNotFound: return web.NotFound() except ValueError: return web.BadRequest() return web.ok(None, headers) elif command == 'deactivate_subscriber': if 'imsi' not in jwt: return web.BadRequest() # The number should correspond to an IMSI. try: subscriber.delete_subscriber(jwt['imsi']) except SubscriberNotFound: return web.NotFound() return web.ok(None, headers)
def GET(self, namespace=None): """ List supported Cloudwatch namespaces :: GET /_metrics/cloudwatch/namespaces Returns: :: {'namespace-name1': {...}, 'namespace-name2': {...} ,... } OR List supported Cloudwatch metrics for a given namespace :: GET /_metrics/cloudwatch/{namespace-name}` Returns: :: { 'namespace-name': { 'metrics': ['metric-name',...], 'dimensions': ['dimension-name',...] } } """ adapter = datasource_adapter_factory.createCloudwatchDatasourceAdapter( ) resources = adapter.describeSupportedMetrics() namespaces = _translateResourcesIntoNamespaces(resources) # Adding Autostacks namespaces to this list for now, to maintain API # backwards-compatibility during adapter refactor namespaces["Autostacks"] = {"metrics": ["InstanceCount"]} if namespace is None: self.addStandardHeaders() return utils.jsonEncode(namespaces) if not namespace in namespaces: raise web.NotFound("Namespace '%s' was not found" % namespace) self.addStandardHeaders() return utils.jsonEncode({str(namespace): namespaces[namespace]})
def GET(self, app): markup.init_theme(app) markup.set_navlink() try: schema = models.schema(scope=app) particles = schema.particle_systems return template.schema_particles(app, particles) except (models.CacheEmptyError, models.ItemBackendUnimplemented) as E: raise web.NotFound(template.errors.generic(E))
def GET(self, app, user, iid): markup.init_theme(app) try: user, items = models.load_inventory(user, scope=app) except steam.api.HTTPError as E: raise web.NotFound( template.errors.generic( "Couldn't connect to Steam (HTTP {0})".format(E))) except steam.user.ProfileError as E: raise web.NotFound( template.errors.generic( "Can't retrieve user profile data: {0}".format(E))) except steam.items.InventoryError as E: raise web.NotFound( template.errors.generic( "Couldn't open backpack: {0}".format(E))) item = None try: item = items["items"][iid] except KeyError: for cid, bpitem in items["items"].iteritems(): oid = bpitem.get("oid") if oid == long(iid): item = bpitem break if not item: raise web.NotFound(template.item_error_notfound(iid)) if web.input().get("contents"): contents = item.get("contents") if contents: item = contents # Strip off quality prefix for possessive name itemname = item["mainname"] if itemname.startswith("The "): item["ownedname"] = itemname[4:] else: item["ownedname"] = itemname return template.item(app, user, item)
def GET(self): if LoginChecker.loggedIn(): data = {} try: data['success'] = commandSender.downloadThumbnail(web.input()) outJSON = json.dumps(data) except IOError as e: raise web.NotFound(e.message) return outJSON
def GET(self, region): """ List all existing Cloudwatch metrics for a given region :: GET /_metrics/cloudwatch/regions/{region} Returns: :: [ { 'name': 'tag-or-empty-string', 'region': 'region-name', 'namespace': 'namespace-name', 'datasource': 'cloudwatch', 'identifier': 'id-from-dimension', 'metric': 'metric-name', 'dimensions': { ... } },... ] """ adapter = datasource_adapter_factory.createCloudwatchDatasourceAdapter( ) resources = adapter.describeSupportedMetrics() def translateResourcesIntoMetrics(): for resource, metrics in resources.items(): for specificResource in adapter.describeResources( region, resource): for metric, cloudwatchParams in metrics.items(): yield { "datasource": "cloudwatch", "dimensions": { cloudwatchParams["dimensionGroups"][0][0]: specificResource["resID"] }, "identifier": specificResource["resID"], "metric": metric, "name": specificResource["name"], "namespace": cloudwatchParams["namespace"], "region": region } if region not in dict(adapter.describeRegions()): raise web.NotFound("Region '%s' was not found" % region) self.addStandardHeaders() return utils.jsonEncode(list(translateResourcesIntoMetrics()))
def NotFound(data=None): """<comment-ja> 404 Not Found メソッド 呼出は直接ではなく、web.notfound を利用してください。 </comment-ja> <comment-en> TODO: English Comment </comment-en> """ if isinstance(data, list): data = "\n".join(data) return web.NotFound(data)
def GET(self): folder_static_full_path = config_agent.get_full_path( "paths", "static_path") path = os.path.join(folder_static_full_path, "favicon.ico") if not os.path.exists(path): raise web.NotFound() with open(path) as f: content = f.read() web.header("Content-Type", "image/vnd.microsoft.icon") return content
def GET(self, app): query = web.input() schema = models.schema(scope=app) markup.init_theme(app) markup.set_navlink() try: sitems = schema.processed_items items = sitems.values() except (models.CacheEmptyError, models.ItemBackendUnimplemented) as E: raise web.NotFound(template.errors.generic(E)) dropdowns = views.build_dropdowns(items) filter_classes = markup.sorted_class_list( dropdowns["equipable_classes"], app) filter_qualities = markup.get_quality_strings(dropdowns["qualities"], schema) filter_capabilities = markup.get_capability_strings( dropdowns["capabilities"]) filters = views.filtering(items) try: items = filters.byClass( markup.get_class_for_id(query["cls"], app)[0]) except KeyError: pass try: items = filters.byQuality(query["quality"]) except KeyError: pass try: items = filters.byCapability(query["capability"]) except KeyError: pass sorter = views.sorting(items) try: items = sorter.sort(query.get("sort", "SchemaID")) except KeyError: pass item_page = views.item_page(items) stats = item_page.summary price_stats = item_page.build_price_summary(models.assets(scope=app)) return template.schema_items(app, items, sorter.get_sort_methods(), filter_classes, filter_qualities, filter_capabilities, stats, price_stats)
def GET(self): if not GLOBALS['session']['loggedin']: raise web.Forbidden() try: data = memrise.user(GLOBALS['session']['loggedin']['username'], True) except HTTPError as e: if e.response.status_code == 403: raise web.Forbidden() else: raise web.NotFound() return data
def wp_source(config_agent, tpl_render, req_path): folder_pages_full_path = config_agent.get_full_path("paths", "pages_path") local_full_path = mdutils.req_path_to_local_full_path( req_path, folder_pages_full_path) if os.path.isfile(local_full_path): web.header("Content-Type", "text/plain; charset=UTF-8") buf = commons.shutils.cat(local_full_path) return buf elif os.path.isdir(local_full_path): msg = "folder doesn't providers source in Markdown, using file instead" raise web.BadRequest(msg) else: raise web.NotFound()
def GET(self): logger.info("woker %s" % 'url2key_without_save') if is_ip_deny(web): raise web.forbidden() url = web.input().get('url') logger.info("url=%s" % url) # print "url=%s" % url if url is None or len(url.strip()) == 0: logger.error("url is %s" % "None") return web.NotFound('url is null') key = toKey(url.strip()) logger.info("key=%s" % key) # print "key=%s" % key # TODO 构造json,返回 return key
def GET(self, name): print name if name.endswith('js'): contentType = 'text/javascript; charset=utf-8' elif name.endswith('css') or name.endswith('css.map'): contentType = 'text/css; charset=utf-8' # print('contentType:' + contentType) else: contentType = 'text/html; charset=utf-8' web.header('Content-Type', contentType) try: with open(web_path + '/lib/' + name) as f: return f.read() except Exception: return web.NotFound()
def GET(self, dirpath, filename): file_path = web_path + '/' + dirpath + '/' + filename web.header('Content-Type', 'text/html; charset=utf-8') web.header('Access-Control-Allow-Origin', '*') web.header('Access-Control-Allow-Methods', '*') if os.path.isfile(file_path): try: with open(file_path) as f: return f.read() except Exception as e: print e return web.InternalError() else: print 'the file not exist:', file_path return web.NotFound()