def PUT(self): ctx = readPlistFromString(web.data()) status = ctx.get("Status") UDID = ctx.get("UDID") g_cmd_queue = MDMDB("./mdm.db") g_cmd_queue.open() cmdinfo = g_cmd_queue.getCommandInfo(UDID=UDID) if not cmdinfo: g_cmd_queue.close() return web.ok() cmd_status = int(cmdinfo["Status"]) print cmd_status if cmd_status == 0: plist = getCommandPlist(cmdinfo["Command"], args=cmdinfo["Arguments"]) g_cmd_queue.setCommandStatus(UDID=UDID, status=1) g_cmd_queue.close() return plist elif cmd_status == 1: print ctx # TODO:Add code here to check device status. g_cmd_queue.removeCommand(UDID=UDID) g_cmd_queue.close() return web.ok() else: return web.unauthorized
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 PUT(self): ctx = readPlistFromString(web.data()) status = ctx.get('Status') UDID = ctx.get('UDID') g_cmd_queue = MDMDB("./mdm.db") g_cmd_queue.open() cmdinfo = g_cmd_queue.getCommandInfo(UDID=UDID) if not cmdinfo: g_cmd_queue.close() return web.ok() cmd_status = int(cmdinfo["Status"]) print cmd_status if cmd_status == 0: plist = getCommandPlist(cmdinfo["Command"], args=cmdinfo["Arguments"]) g_cmd_queue.setCommandStatus(UDID=UDID, status=1) g_cmd_queue.close() return plist elif cmd_status == 1: print ctx #TODO:Add code here to check device status. g_cmd_queue.removeCommand(UDID=UDID) g_cmd_queue.close() return web.ok() else: return web.unauthorized
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 GET(self, id): try: scan = db[id] body = json.dumps({'id': int(id), 'points': scan}) web.ok(self, headers={'Content-Type': 'application/json'}) return body except KeyError: web.notfound(self)
def GET(self, id): try: scan = db[id] bbox = threed.boundingbox(scan) center = threed.center(scan) body = json.dumps({'boundingbox': bbox, 'center': center}) web.ok(self, headers={'Content-Type': 'application/json'}) return body except KeyError: web.notfound(self)
def GET(self): con = ESL.ESLconnection('127.0.0.1', '8021', 'ClueCon') if not con.connected(): # Unable to connect FreeSWITCH print("Unable to connect FreeSWITCH") web.header('Content-Type', 'application/json','unique=True') raise web.InternalError("{\"message\": \"active call list error\"}") #Sending command to FreeSWITCH print("Sending command to FreeSWITCH for call list") e = con.api("show calls as json") if e: # Found active calls. Prasing and makeing list of call uuid. Sending response 200 - ok with list of call uuids in JSON print("Active calls found") web.header('Content-Type', 'application/json','unique=True') calls_str = json.loads(e.getBody()) arr_call_uuids = [] if calls_str['row_count'] > 0: for call in calls_str['rows']: arr_call_uuids.append(call['call_uuid']) raise web.ok(json.dumps(arr_call_uuids)) else: web.header('Content-Type', 'application/json','unique=True') raise web.InternalError("{\"message\": \"active call list error\"}")
def __call__(self, handler): if self.is_cors_path(): self.add_cors_headers() if web.ctx.method == "OPTIONS": raise web.ok("") else: return handler()
def __call__(self, handler): if web.ctx.path.startswith("/api/") or web.ctx.path.endswith(".json"): self.add_cors_headers() if web.ctx.method == "OPTIONS": raise web.ok("") else: return handler()
def PUT(self, slug): entry = db.entries.find_one({'slug': slug}) if not entry: raise web.notfound() else: updated_entry = objectify.fromstring(web.data()) db.entries.update({'_id': entry['_id'],},{ 'slug': slug, 'title': updated_entry.title.text, 'updated': datetime.datetime.now(), 'author': updated_entry.author.name.text, 'content': updated_entry.content.text, }) body = xmlify(db.entries.find_one({'slug': slug}), web.home) web.header( 'Content-Type', 'application/atom+xml;type=entry;charset="utf-8"' ) web.header( 'Content-Length', len(body) ) raise web.ok(body)
def GET(self): type = web.input().get('type', '') if type == 'atom': out = render.atomfeed(web.ctx.home) else: out = render.rssfeed(web.ctx.home) raise web.ok(out)
def success(self, i): if i.redirect_url: url = self.build_url(i.redirect_url, status="ok") return web.seeother(url) else: d = json.dumps({ "status" : "ok" }) return web.ok(d, {"Content-type": "application/json"})
def POST(self): data = web.data() print print 'DATA RECEIVED:' jsondata = json.loads(data) data_handler(jsondata) return web.ok('explicit 200')
def GET(self): type = web.input().get('type', '') comments = get_objects('/type/comment')[:10] if type == 'atom': response = render.comments_atom_feed(comments, web.ctx.home) else: response = render.comments_rss_feed(comments, web.ctx.home) raise web.ok(render)
def POST(self): x = web.input() if x.has_key("id"): if not s.exists(x['id']): item = s.get_item(x['id']) raise web.created() else: raise web.ok()
def PUT(self, id): if id == 0: web.badrequest(self, message="Indexes start at 1") return updating = id in db db[id] = json.loads(web.data())['points'] body = json.dumps({'id': int(id), 'points': db[id]}) if updating: web.ok(self, headers={'Content-Type': 'application/json'}) else: web.created(self, headers={ 'Location': 'http://0.0.0.0:8080/scans/' + str(id), 'Content-Type': 'application/json' }) return body
def GET(self, method=None): # Default is to turn something on if method == 'on' or not method: self._d.turn_on() return web.ok() if method == 'off': self._d.turn_off() return web.ok() # TODO: Test this so it doesn't clash with the web.input() call in # __init__() if method == 'parameter': query = web.input( parameter = None, value = '' ) if not query.parameter: raise web.badrequest() try: value = self._d.get_parameter(parameter) except: raise web.internalerror() if not value: raise web.notfound() return json.dumps(dict( parameter = parameter, value = value )) if method == 'model': model = self._d.model if not model: raise web.notfound() if method == 'learn': try: self._d.learn() except(td.TDDeviceError), e: web.internalerror() return json.dumps(dict(error=str(e))) return web.ok()
def DELETE(self, id=None): if id is None: DATA = [] try: del DATA[int(id)] except IndexError: raise web.badrequest() raise web.ok()
def POST(self): global last_snapshot i = web.input() if last_snapshot is not None: tweeter.tweet_photo(str(datetime.now()), last_snapshot['blob']) # tweeter.tweet('test') print i return web.ok()
def GET(self): if last_snapshot is None: return web.ok() else: web.header('Content-Type', 'image/png') # file type # web.header('Content-disposition', # 'attachment; filename=graphotti.png') return last_snapshot['blob']
def GET(self, slug): media = Media.get(slug) if media: web.ok( { "Expires": "Thu, 15 Apr 3010 20:00:00 GMT", "Cache-Control": "max-age=3600,public", "Content-Type": str(media.mtype), } ) a = web.input(a="")["a"] if a and a.lower() == "download": media.download += 1 media.put() return media.bits else: return web.notfound()
def GET(self, key): d = self.get_data(key) if web.input(text="false").text.lower() == "true": web.header('Content-Type', 'text/plain') else: web.header('Content-Type', 'text/x-yaml') raise web.ok(self.dump(d))
def POST(self): variables = web.input() if (variables.get('username') == configuration.web_user()) & (variables.get('password') == configuration.web_pwd()): user_session.login = 1 print 'Logged in.' return web.ok() else: user_session.login = 0 return web.unauthorized()
def DELETE(self, uuid=None): if uuid is None: raise web.badrequest() # @throws web.notfound self.handler.delete(uuid) raise web.ok()
def GET(self, uuid=None): if uuid is None: data = self.handler.get_list() else: # @throws web.notfound data = self.handler.get(uuid) raise web.ok(self.dump_json(data))
def GET(self, key): d = self.get_data(key) if web.input(text='false').text.lower() == 'true': web.header('Content-Type', 'text/plain; charset=utf-8') else: web.header('Content-Type', 'text/x-yaml; charset=utf-8') raise web.ok(self.dump(d))
def PUT(self, id=None): if id is None: raise web.badrequest() todo = self._get_todo_or_400(id) edits = json.loads(web.data()) todo.order = edits.get('order', todo.order) todo.title = edits.get('title', todo.title) todo.body = edits.get('body', todo.body) raise web.ok()
def GET(self, path): path = "/var/www/kottapalli.in/static/" + path assert ".." not in path web.header("Content-Disposition", 'attachment; filename="%s"' % os.path.basename(path)) if os.path.exists(path): data = open(path).read() raise web.ok(data) else: web.notfound()
def GET(self): web.header('Access-Control-Allow-Origin', '*') params = web.input() if 'user' not in params or 'pass' not in params: return web.badrequest() if random.choice([True, False]): return web.ok() else: return web.unauthorized()
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): web.header('Content-Type', 'text/xml') issues = web.ctx.site.things({'type': '/type/issue', 'published': True, 'sort': '-key', 'limit': 1000}) articles = web.ctx.site.things({'type': '/type/article', 'last_modified': None, 'sort': '-key', 'limit': 1000}, details=True) articles = [a for a in articles if a.key.rsplit('/', 1)[0] in issues] for a in articles: a.last_modified = client.parse_datetime(a.last_modified.value).strftime('%Y-%m-%dT%H:%M:%SZ') out = render.sitemap(articles) raise web.ok(out)
def POST(self): form = self.form() if not form.validates(): return render.reset(form) try: user_id = users.get_user(form.d.username).id except AttributeError: raise web.BadRequest('user does not exist') else: users.change_password(user_id, form.d.password) raise web.ok('password has been reset')
def POST(self): super(DeleteLeadController, self).POST() params = web.input() self.store.delete_by_key(Lead, lead_url=params.lead_url, date_created=int(params.date_created)) # lead = self.store.get_item(Lead, dict(lead_url=params.lead_url, date_created=params.date_created)) # lead = lead._asdict() # lead['deleted'] = True # self.store.update(Lead(lead)) return web.ok()
def DELETE( self, entityType, localID, remoteID, testdata = None ): """ delete an object """ if testdata == None: self._nocache() entity = self._getEntity( entityType, localID, remoteID ) if entity: entity.delete() return web.ok() else: return web.notfound()
def POST(self): global current_path i = web.input() p = loads(i['path']) zoom = float(i['zoom']) if 'latitude' in i: latitude = float(i['latitude']) else: latitude = 0.0 if 'longitude' in i: longitude = float(i['longitude']) else: longitude = 0.0 geo_location = (latitude, longitude) if not geo_fence.valid_position(geo_location): return web.notacceptable() #pixel_ratio = float(i['pixel_ratio']) for s in p[1]['segments']: s[0] /= (zoom) s[1] /= (zoom) new_path_cond.acquire() try: env = {} for (k, v) in web.ctx.env.items(): if type(v) is str: env[k] = v d = { 'path': p, 'env': env, 'dummy': range(1, 2048), # dummy data to stop proxy buffering } current_path = dumps(d) new_path_cond.notifyAll() # store relevant logs: fname = abspath + '/logs/graphotti_%s.json' % str(datetime.now()) with open(fname, 'w') as f: log_data = { 'path': p, 'env': env, 'longitude': longitude, 'latitude': latitude, 'timestamp': str(datetime.now()) } f.write(dumps(log_data)) finally: new_path_cond.release() return web.ok()
def process(self): args = { 'name': web.input(name='unknown').name, 'ip': web.input(ip='x.x.x.x').ip, 'ping_ip': web.ctx.ip, 'comment': web.input(comment='').comment, 'ts': datetime.now(), 'updated': web.input(updated='').updated, 'public_ip': web.input(public_ip='').public_ip } print args servers.put(args['name'], args) return web.ok()
def get_user(self): i = web.input(token=None) if i.token: user = Person.find_from_reset_token(i.token) if not user: form = forms.ChangePasswordForm() raise web.ok(render.change_password(user, form)) else: return user else: user = account.get_current_user() if not user: raise web.seeother("/account/login") else: return user
def POST(self): user_data = web.input(username='') info('pressed the button') user = str(user_data.username) if user is not '': self_app.car_states.users[user] = web.ctx self_app.params = { 'n_users': len(self_app.car_states.users), 'users': list(self_app.car_states.users) } info('user %s pressed the button') self_app.car_states.set_state(user, 'BUTTON') self_app.car_states.send_updated_states() return web.ok()
def POST(self): ''' Uses input from the image table and the csapi to delete an image. ''' image = web.input() token = web.cookies().get('token') tenant_id = web.cookies().get('tenant_id') headers = { "X-Auth-Token": token, "X-Auth-Tenant-ID": tenant_id } response = util.APIRequest(util.csapi_ip, util.csapi_port, util.csapi_root+"/image/v1/images/"+image.id, "DELETE", None, headers) if response: return web.ok() else: return web.BadRequest()
def POST(self): ''' Uses input from the image table and the csapi to create a new image. ''' project = web.input() token = web.cookies().get('token') tenant_id = web.cookies().get('tenant_id') headers = { "Accept": "application/json", "X-Auth-Token": token, "X-Auth-Tenant-ID": tenant_id } params = {"tenant": {"name": project.name, "description": project.description}} response = util.APIRequest(util.csapi_ip, util.csapi_port, util.csapi_root+"/identity/tenant/", "POST", params, headers) if response: return web.ok() else: return web.BadRequest()
def g(self, code, *args): place = Place.find(key=code) if not place: raise web.notfound() if types is not None and place.type not in types: raise web.notfound() user = account.get_current_user() if not user or not place.viewable_by(user): raise web.ok(render.access_restricted()) if roles: if not user or not place.writable_by(user, roles=roles): return render.permission_denied(user=user) return f(self, place, *args)
def adjust_credits(self, data): required_fields = ["imsi", "change"] if not all([_ in data for _ in required_fields]): return web.BadRequest() imsi = data["imsi"] try: change = int(data["change"]) except ValueError: return web.BadRequest() old_credit = subscriber.get_account_balance(imsi) if change > 0: subscriber.add_credit(imsi, str(abs(change))) elif change < 0: subscriber.subtract_credit(imsi, str(abs(change))) new_credit = subscriber.get_account_balance(imsi) # Codeship is stupid. These imports break CI and this is an untested # method :) from core import freeswitch_interconnect, freeswitch_strings # Send a confirmation to the subscriber number = subscriber.get_caller_id(imsi) change_frmt = freeswitch_strings.humanize_credits(change) balance_frmt = freeswitch_strings.humanize_credits(new_credit) fs_ic = freeswitch_interconnect.freeswitch_ic(self.conf) fs_ic.send_to_number( number, '000', freeswitch_strings.gt( "The network operator adjusted your credit by %(change)s. " "Your balance is now %(balance)s.") % { 'change': change_frmt, 'balance': balance_frmt }) # TODO(matt): all credit adjustments are of the kind "add_money," even # if they actually subtract credit. reason = 'Update from web UI (add_money)' events.create_add_money_event(imsi, old_credit, new_credit, reason, to_number=number) return web.ok()
def POST(self): try: # check for Token: HTTP header as bucket id token = self.do_authentication() bucket = self.handler.get_bucket(token) data_json = web.data() data = json.loads(data_json) self.handler.create(bucket, data) except Exception as ex: self.logger.error('Caught exception in POST(): %s' % ex) raise web.badrequest() raise web.ok()
def POST(self, domain): if not qv_domains.is_admin(domain): return web.notacceptable() user_data = web.input() if hasattr(user_data, "delete_question") and \ hasattr(user_data, 'uuid'): print("Deleting") qv_questions.remove({'uuid': user_data.uuid}) elif hasattr(user_data, 'options') and \ hasattr(user_data, 'correct') and \ hasattr(user_data, 'question') and \ hasattr(user_data, 'domain') and \ hasattr(user_data, 'uuid'): if user_data.uuid == '': user_data.uuid = str(uuid4()) if user_data.domain == '': user_data.domain = str(domain) options_str = user_data.options.split(',') correct_str = user_data.correct.split(',') doc = { 'options': [o.strip() for o in options_str], 'correct': [o.strip() for o in correct_str], 'question': user_data.question, 'uuid': user_data.uuid, 'domain': user_data.domain, 'inserted_at': datetime.now() } if hasattr(user_data, 'image'): doc['image'] = user_data.image # the is a delete request if the question is empty: if len(user_data.question) > 0: qv_questions.update({'uuid': user_data.uuid}, doc, upsert=True) else: qv_questions.remove({'uuid': user_data.uuid}) else: web.internalerror("could not all data provided as required: " "user_data=%s" % user_data) return web.ok() # web.seeother('/%s/%s/editor' % (domain, admin_url))
def GET(self, id, taskid): """Checks the status of a pending 'avatar-change' operation. The 'HTTP_ACCEPT' header is required to allow the controller to specify the acceptable media type for the response. There should be a logged-in user behind this request. The specified ``id`` should match the one of the logged-in user. If all these prerequisites hold true then the controller will check the status of a task with ID ``taskid``. If the task is still active the controller will return '200 OK'; clients are then supposed to come later and check again the status of the task. On the other hand a '201 Created' status message with the 'Location' header pointing to the uploaded avatar will be sent back to client if the task has exited normally. Note that a '415 Unsupported Media Type' status message is returned if the format of the uploaded avatar cannot be handled by the server. """ task = tasks.UsersAvatarChangeTask status, arg = workflows.check_avatar_change_status( web.ctx.logger, task, taskid) if status == workflows.TASK_RUNNING: raise web.ok() elif status == workflows.TASK_FAILED: if type(arg).__name__ == 'IOError': raise web.unsupportedmediatype() else: raise arg else: assert status == workflows.TASK_FINISHED ok, arg = arg if not ok: return jsonify(arg) else: web.header('Location', arg) raise web.created()
def POST(self): """TODO (matt): need to verify: this is used by the dashboard only? and is insecured? """ # Always send back these headers. headers = {'Content-type': 'text/plain'} data = web.input() needed_fields = ["text", "to", "sender", "msgid"] if all(i in data for i in needed_fields): # Make sure we haven't already seen this message. if self.msgid_db.seen(str(data.msgid)): return data.msgid to = str(data.to) from_ = str(data.sender) body = str(data.text) self.fs_ic.send_to_number(to, from_, body) self.bill(to, from_) return web.ok(None, headers) else: return web.badrequest(None, headers)
def DELETE(self, path): path = unquote(path) tokens = [x for x in path.split("/") if x] if len(tokens) == 1: if s.exists(tokens[0]): s.del_item(tokens[0]) raise web.ok() else: raise web.notfound() elif len(tokens) == 2: if s.exists(tokens[0]): item = s.get_item(tokens[0]) if tokens[1] not in item.versions: raise web.notfound() else: item.del_version(tokens[1]) return "{'ok':'true'}" else: raise web.notfound() elif len(tokens) > 2: if s.exists(tokens[0]): item = s.get_item(tokens[0]) if tokens[1] not in item.versions: raise web.notfound() else: item.set_version_cursor(tokens[1]) filepath = "/".join(tokens[2:]) if item.isfile(filepath): item.del_stream(filepath) return "{'ok':'true'}" elif item.isdir(filepath): try: item.del_stream(filepath) return "{'ok':'true'}" except OSError: raise web.forbidden("The subpath directory is not empty") else: raise web.notfound() else: raise web.notfound()
def GET(self): return web.ok('explicit 200')
class status: def GET(self): name = web.input().name if name in auctions and auctions[name]['bid'] > 0: return auctions[name]['bidder'] else: return "UNKNOWN" class winner: def GET(self): name = web.input().name if name in auctions and auctions[name]['end_time'] < current_time(): return auctions[name]['bidder'] else: return "UNKNOWN" class rst: def POST(self): with auction_lock: auctions.clear() if __name__ == "__main__": app = web.application(urls, globals()) app.internalerror = lambda: web.ok("") # Return 200, even for errors app.run()
def POST(self, id=None): if id is not None: raise web.badrequest() DATA.append(Todo(**json.loads(web.data()))) DATA.sort(key=lambda todo: todo.order) raise web.ok()