def get(self, item_id=None): req = parse_request(self.request, self.rest_settings) response = {} data = [{"user": "******"}, {"user": "******"}] if item_id: items = [i for i in data if i["user"] == item_id] else: items = data for item in items: item["updated"] = last_updated(item) item["created"] = date_created(item) item['etag'] = item_etag(item) response["items"] = items response['links'] = self._pagination_links(None, None, len(items)) self.set_header('Content-Type', 'application/json') self.write(render_json(response))
def get_labsysteminfo(): if request.method == 'GET': return jsonify_list(LabSystemInfo.get_all()) if request.method == 'POST': data = parse_request(request) if not data: abort(400, 'Your data should be in JSON format') if 'lab_id' not in data: abort(400, 'You need to provide lab_id') lab = Lab.query.get(data['lab_id']) if lab is None: abort(404, 'No lab exist with given lab_id') try: new_system_info = LabSystemInfo(**data) new_system_info.save() return jsonify(new_system_info.to_client()) except (TypeError, AttributeError), e: current_app.logger.error("Error saving labs system info data: %s" % e) # return 'Error: Provide correct attribute name' abort(400, 'Invalid attributes in request data')
def add_message(): arguments = parse_request(req_parse_message) message = MessagesModel.create(**arguments) message_data = marshal(message, message_fields) return response(message_data, 200)
def do_DATANET(self): sesskey = privkey.decrypt(self.headers['Session-Key']) a = AES.new(sesskey[0:32], AES.MODE_CBC, sesskey[32:48]) payload = a.decrypt(self.rfile.read()) request = utils.parse_request(payload) self.headers = request['headers'] return self.proxy(request['method'], aes=a)
def add_new_user(): fields = [ ('email', str, True, None), ('password', str, True, None), ('password_repeat', str, True, None), ] arguments = parse_request(fields) UserModel.create(**arguments) return response(dict(email=arguments['email']), 201)
def get_lab_by_id(id): if request.method == 'GET': fields = request.args.getlist('fields') or None try: lab_dict = Lab.get_specific_lab(id, fields) except Exception: abort(400, 'Invalid field attribute') if lab_dict is None: abort(404, 'Invalid id') return jsonify(lab_dict) if request.method == 'PUT': data = parse_request(request) if not data: abort(400, 'Your data should be in JSON format') lab = Lab.query.get(id) if not lab: abort(404, 'No lab with id: %s exist' % str(id)) # From the nested object in the request data, get the id, and associate # the entities separately.. if 'discipline' in data: disc = Discipline.query.get(data['discipline']['id']) if not disc: abort(400, 'No such discipline exist') lab.discipline = disc del(data['discipline']) if 'institute' in data: instt = Institute.query.get(data['institute']['id']) if not instt: abort(400, 'No such institute exist') lab.institute = instt del(data['institute']) if 'developers' in data: del(data['developers']) if 'technologies' in data: del(data['technologies']) try: lab.update(**data) except (AttributeError, KeyError), e: current_app.logger.error("Error while saving lab data: %s" % e) # return 'Provide correct attribute name' abort(400, 'Invalid attributes in request data') return jsonify(lab.to_client())
def get_lab_by_id(id): if request.method == 'GET': fields = request.args.getlist('fields') or None try: lab_dict = Lab.get_specific_lab(id, fields) except Exception: abort(400, 'Invalid field attribute') if lab_dict is None: abort(404, 'Invalid id') return jsonify(lab_dict) if request.method == 'PUT': data = parse_request(request) if not data: abort(400, 'Your data should be in JSON format') lab = Lab.query.get(id) if not lab: abort(404, 'No lab with id: %s exist' % str(id)) # From the nested object in the request data, get the id, and associate # the entities separately.. if 'discipline' in data: disc = Discipline.query.get(data['discipline']['id']) if not disc: abort(400, 'No such discipline exist') lab.discipline = disc del (data['discipline']) if 'institute' in data: instt = Institute.query.get(data['institute']['id']) if not instt: abort(400, 'No such institute exist') lab.institute = instt del (data['institute']) if 'developers' in data: del (data['developers']) if 'technologies' in data: del (data['technologies']) try: lab.update(**data) except (AttributeError, KeyError), e: current_app.logger.error("Error while saving lab data: %s" % e) # return 'Provide correct attribute name' abort(400, 'Invalid attributes in request data') return jsonify(lab.to_client())
def put_json(self, url, data): payload = json.dumps(utils.parse_request(data)) resp = self.s.put( self.config['P2P_API_ROOT'] + url, data=payload, headers=self.http_headers('application/json'), verify=False) resp_log = self._check_for_errors(resp, url) try: return utils.parse_response(resp.json()) except ValueError: log.error('JSON VALUE ERROR ON SUCCESSFUL RESPONSE %s' % resp_log) raise
def get(self, skills_needed_string): #to store the different plans plans = [] plan = Plans() position, budget, timeAllocation, user_skills = parse_request( skills_needed_string) course_providers = [2, 3, 4] inputs = OR_inputs(course_providers) courses, ratings, prices, lengths = inputs.fetch_courses() courseSkill_matrix = inputs.fetch_courseSkill_matrix(len(courses)) courseSkillLvl_matrix = inputs.fetch_courseSkillLvls_matrix( len(courses)) combination_ids, combinations = inputs.fetch_tech_combinations( position) needed_skills, needed_skills_lvls = inputs.fetch_needed_skills( position, user_skills) #to fetch the tech combination id for the plans i = 0 for tech_skill_combo in combinations.values(): skills_needed = add_tech_combo(needed_skills, tech_skill_combo) course_scores = inputs.fetch_course_scores(skills_needed) infeasible, courses_recomended = run_algorithm( courses, courseSkill_matrix, courseSkillLvl_matrix, prices, ratings, lengths, timeAllocation, budget, skills_needed, needed_skills_lvls, course_scores) outputs = OR_outputs(courses_recomended) plan_json = outputs.fetch_course_details() plan_id = plan.add(position, plan_json, combination_ids[i], needed_skills) plan_json[0]['plan_id'] = plan_id skills = Skills(tech_skill_combo) plan_json[0]['tech_combo'] = skills.get_names() position_id = Positions(position) plan_json[0]['position'] = position_id.get_name() if infeasible == 1: plan_json[0]['relaxed'] = infeasible plans.append(plan_json) i = i + 1 return plans
def create_record(entity_name, entity): data = parse_request(request) if not data or type(data) is not dict: abort(400, "The data should be in JSON format") data = typecast_data(entity_name, data) print "creating new, typecasted data: %s" % data try: print "Creating record: %s with data: %s" % (entity_name, data) new_record = entity(**data) new_record.save() except Exception, e: print e abort(500, str(e))
def create_record(entity_name, entity): data = parse_request(request) if not data or type(data) is not dict: current_app.logger.debug( "Unsupported data...The data should be in JSON format") abort(400, "The data should be in JSON format") data = typecast_data(entity_name, data) try: new_record = entity(**data) new_record.save() except Exception, e: current_app.logger.error("Error is %s" % (str(e))) abort(500, str(e))
def update_exp_by_id(id): if request.method == 'PUT': data = parse_request(request) if not data: abort(400, 'Your data should be in JSON format') exp = Experiment.query.get(id) if exp is None: abort(404, 'No such experiment') try: exp.update(**data) except (AttributeError, KeyError): # return 'Provide correct attribute name' abort(400, 'Invalid attributes in request data') return jsonify(exp.to_client())
async def on_message(message): author = message.author nickname = db.get_nickname(author.id, author.display_name) await change_nickname(message, author, nickname) user, command, nickname = parse_request(message) #await top_kek(message) await name_parses.run(client, message, user, command, nickname, message.channel) await easter_eggs.run(client, message) await fight(message) await run_animations(message) #await quiz_client.handle_message(client, message) if command in MEMEGEN_PARSES: await memegen_parse(command, nickname, message)
def get_messages_list(): arguments = parse_request( [ ('lat', float, True, None), ('lon', float, True, None), ], get=True ) messages = MessagesModel.all() available_messages = list() for message in messages: msg_distance = is_message_in_range(arguments.lat, arguments.lon, message) if msg_distance is not False and is_message_available(message): available_messages.append(message) setattr(message, 'distance', msg_distance) messages_data = marshal(available_messages, message_fields, 'messages') return response(messages_data, 200)
def put_json(self, url, data): payload = json.dumps(utils.parse_request(data)) resp = self.s.put( self.config['P2P_API_ROOT'] + url, data=payload, headers=self.http_headers('application/json'), verify=False) resp_log = self._check_for_errors(resp, url) if resp.content == "" and resp.status_code < 400: return {} else: try: return utils.parse_response(resp.json()) except Exception: log.error('THERE WAS AN EXCEPTION WHILE TRYING TO PARSE YOUR JSON: %s' % resp_log) raise
def technologies(): if request.method == 'GET': return jsonify_list(Technology.get_all()) if request.method == 'POST': data = parse_request(request) if not data: abort(400, 'Your data should be in JSON format') try: new_technology = Technology(**data) new_technology.save() return jsonify(new_technology.to_client()) except (TypeError, AttributeError), e: current_app.logger.error("Error while saving technology data: %s" % e) # return 'Error: Provide correct attribute name' abort(400, 'Invalid attributes in request data')
def update_tech_by_id(id): if request.method == 'PUT': data = parse_request(request) if not data: abort(400, 'Your data should be in JSON format') tech = Technology.query.get(id) if not tech: abort(404, 'No such technology exist') try: tech.update(**data) except (AttributeError, KeyError), e: current_app.logger.error("Error while saving technology data: %s" % e) # return 'Provide correct attribute name' abort(400, 'Invalid attributes in request data') return jsonify(tech.to_client())
def put_json(self, url, data): payload = json.dumps(utils.parse_request(data)) resp = self.s.put(self.config['P2P_API_ROOT'] + url, data=payload, headers=self.http_headers('application/json'), verify=False) resp_log = self._check_for_errors(resp, url) if resp.content == "" and resp.status_code < 400: return {} else: try: return utils.parse_response(resp.json()) except Exception: log.error( 'THERE WAS AN EXCEPTION WHILE TRYING TO PARSE YOUR JSON: %s' % resp_log) raise
def update_record(entity_name, entity, id): record = entity.get_by_id(id) if not record: abort(404, 'No %s with id %s' % (entity_name, id)) data = parse_request(request) if not data or type(data) is not dict: abort(400, "The data should be in JSON format") data = typecast_data(entity_name, data) print "typecasted data: %s" % data try: print "Updating record: %s with data: %s" % (record, data) record.update(**data) except Exception, e: print e abort(500, str(e))
def post_json(self, url, data): payload = json.dumps(utils.parse_request(data)) log.debug("GET: %s" % url) resp = self.s.post( self.config['P2P_API_ROOT'] + url, data=payload, headers=self.http_headers('application/json'), verify=False ) resp_log = self._check_for_errors(resp, url) if resp.content == "" and resp.status_code < 400: return {} else: try: return utils.parse_response(resp.json()) except Exception: log.error('EXCEPTION IN JSON PARSE: %s' % resp_log) raise
def update_develop_by_id(id): if request.method == 'PUT': data = parse_request(request) if not data: abort(400, 'Your data should be in JSON format') develop = Developer.query.get(id) if develop is None: abort(404, 'No developer with id: %s found' % str(id)) try: develop.update(**data) except (AttributeError, TypeError), e: current_app.logger.error("Error while saving developer data: %s" % e) # return 'Provide correct attribute name' abort(400, 'Invalid attributes in request data') return jsonify(develop.to_client())
async def listener(websocket, path): print('start server listener:', websocket, path) event_list, data = await recv_http_websocket(websocket) print('recv_http_websocket:', event_list, data) request = parse_request(event_list) remote_reader, remote_writer = await asyncio.open_connection( request['host'], request['port']) if request['method'] == b'CONNECT': await websocket.send( b'HTTP/1.0 200 Connection Established\r\nProxy-agent: Pyx\r\n\r\n') else: remote_writer.write(data) await remote_writer.drain() pipe1 = socket_to_websocket(remote_reader, websocket) pipe2 = websocket_to_socket(websocket, remote_writer) await asyncio.gather(pipe1, pipe2)
def update_instt_by_id(id): if request.method == 'PUT': data = parse_request(request) if not data: abort(400, 'Your data should be in JSON format') instt = Institute.query.get(id) if instt is None: abort(404, 'No institute with id: %s found' % str(id)) try: instt.update(**data) except (AttributeError, KeyError), e: current_app.logger.error("Error while saving institute data: %s" % e) # return 'Error: Provide correct attribute name' abort(400, 'Invalid attributes in request data') return jsonify(instt.to_client())
def update_disc_by_id(id): if request.method == 'PUT': data = parse_request(request) if not data: abort(400, 'Your data should be in JSON format') disc = Discipline.query.get(id) if disc is None: abort(404, 'No discipline with id: %s found' % str(id)) try: disc.update(**data) except (KeyError, AttributeError), e: current_app.logger.error("Error while saving discipline data: %s" % e) # return 'Invalid attribute found' abort(400, 'Invalid attributes in request data') return jsonify(disc.to_client())
def update_labsysteminfo_by_id(id): if request.method == 'PUT': data = parse_request(request) if not data: abort(400, 'Your data should be in JSON format') labsysteminfo = LabSystemInfo.query.get(id) if labsysteminfo is None: abort(404, 'No id found') try: labsysteminfo.update(**data) except (AttributeError, TypeError), e: current_app.logger.error("Error saving labs system info data: %s" % e) # return 'Provide correct attribute name' abort(400, 'Invalid attributes in request data') return jsonify(labsysteminfo.to_client())
def listen(self, client_socket, client_address): request_client = client_socket.recv(int( self.config['MAX_REQUEST_LEN'])) print("Recieved request from client:") print(request_client) request_method = parse_request(request_client) uname, pswd = parse_cred(request_client) if not user_valid(uname, pswd, self.config): client_socket.send("Unauthorised") client_socket.close() return udir = self.root_dir + "/" + uname if request_method == "GET": get_data(client_socket, udir + "/" + parse_filename(request_client)) if request_method == "PUT": client_socket.send("Authorised") return put_data(udir, client_socket, request_client) if request_method == "LIST": get_list(udir, client_socket) client_socket.close()
def update_record(entity_name, entity, id): record = entity.get_by_id(id) if not record: current_app.logger.debug("No %s with id %s" % (entity_name, id)) abort(404, "No %s with id %s" % (entity_name, id)) data = parse_request(request) if not data or type(data) is not dict: current_app.logger.debug("The data should be in JSON format") abort(400, "The data should be in JSON format") data = typecast_data(entity_name, data) try: record.update(**data) current_app.logger.debug( "The data of %s entity updated sucessfully..." % entity_name) except Exception, e: current_app.logger.error("Error is %s" % (str(e))) abort(500, str(e))
def labs(): if request.method == 'GET': fields = request.args.getlist('fields') or None try: current_app.logger.debug(jsonify_list(Lab.get_all(fields)).data) return jsonify_list(Lab.get_all(fields)) except Exception: abort(404, 'Invalid field attribute') if request.method == 'POST': data = parse_request(request) if not data: abort(400, 'Your data should be in JSON format') if 'institute_id' not in data: abort(400, 'Provide institute_id') if 'discipline_id' not in data: abort(400, 'Provide discipline_id') instt = Institute.query.get(data['institute_id']) if instt is None: abort(404, 'Foreign_key constraint fails: Provide institute_id') dis = Discipline.query.get(data['discipline_id']) if dis is None: abort(404, 'Foreign_key constraint fails: Provide discipline_id') try: new_lab = Lab(**data) new_lab.save() return jsonify(new_lab.to_client()) except (TypeError, AttributeError), e: current_app.logger.error("Error while saving lab data: %s" % e) abort(400, 'Invalid attributes in request data')
def post_exp(): if request.method == 'POST': data = parse_request(request) if not data: abort(400, 'Your data should be in JSON format') if 'lab_id' not in data: abort(400, 'You need to provide lab_id') lab = Lab.query.get(data['lab_id']) if lab is None: abort(404, 'No lab exist with given lab_id') try: new_experiment = Experiment(**data) new_experiment.save() return jsonify(new_experiment.to_client()) except (TypeError, AttributeError), e: current_app.logger.error("Error saving experiment data: %s" % e) # return 'Error: Provide correct attribute name' abort(400, 'Invalid attributes in request data')
def developers(): if request.method == 'GET': return jsonify_list(Developer.get_all()) if request.method == 'POST': data = parse_request(request) if not data: abort(400, 'Your data should be in JSON format') if 'institute_id' not in data: abort(400, 'Provide institute_id') # instt = Institute.query.get(data['institute_id']) try: new_develop = Developer(**data) new_develop.save() return jsonify(new_develop.to_client()) except TypeError, e: current_app.logger.error("Error while saving developer data: %s" % e) # return jsonify(error='Error: Provide correct attribute name') abort(400, 'Invalid attributes in request data')
def default(source): req_img = parse_request(source, request) if None in (req_img.strategy, req_img.quality): req_img.strategy = 'crop' req_img.quality = 60 req_img.path = app.config['IMAGE_400'] if req_img.path is None: req_img.path = app.config['IMAGE_404'] if not auth.acl.has_permission(request): req_img.path = app.config['IMAGE_401'] try: return graph_response(req_img) except ResizerError: req_img.path = app.config['IMAGE_500'] return graph_response(req_img) except Exception: sentry.captureException() return send_file(app.config['IMAGE_500'], mimetype='image/jpeg')
def proxy(self, method, aes=None): if not self.path.startswith('http'): return self.send_error(403, 'scheme not supported') connection = None request_header_exceptions = dict(header_exceptions) def connection_exception(h, k, v): global connection connection = v return True request_header_exceptions['connection'] = connection_exception headers = fix_headers(self.headers.items(), request_header_exceptions) if 'max-forwards' not in headers: headers.addheader('Max-Forwards', '5') u = urlparse.urlparse(self.path) if u.scheme == 'http': if headers['max-forwards'] == '0': c = httplib.HTTPConnection(u.netloc, timeout=10) url = urlparse.urlunparse(('', '') + u[2:]) peer = None else: try: peer = proxymanager.get_peer(True) except proxynet.EmptyPeerList: return self.send_error(502) #print peer c = httplib.HTTPConnection('{0}:{1}'.format(peer['ip'], peer['port']), timeout=proxy_timeout) url = self.path headers.setheader('max-forwards', int(headers['max-forwards']) - 1) if 'via' in headers: # TODO: fix hard coded IP address if headers['via'] == '': headers.setheader('via', '1.1 109.74.202.182:{0}'.format(server_address[1])) else: headers.setheader('via', headers['Via'] + ', 1.1 109.74.202.182:{0}'.format(server_address[1])) else: return self.send_error(403, 'scheme not supported') if connection: for f in [f.strip() for f in connection.split(',')]: if f in headers: del headers[f] headers.addheader('Connection', 'close') c.set_debuglevel(1) try: if peer != None and 'pub_key' in peer: pubkey = RSA.construct((long(peer['pub_key']['n']), long(peer['pub_key']['e']))) payload, key, a = self.create_payload(headers, method, url, self.rfile.read(), pubkey) c.putrequest('DATANET', '*', True, True) c.putheader('Host', '*') c.putheader('Session-Key', key[0].encode('base64')) c.putheader('Content-Length', len(payload)) c.endheaders() c.send(payload) else: c.putrequest(method, url, True, True) for h in headers.items(): c.putheader(*h) c.endheaders() content_length = int(self.headers.get('Content-Length', 0)) while content_length > 0: data = self.rfile.read(min(content_length, 4096)) if len(data) == 0: return self.send_error(400) c.send(data) content_length -= len(data) except socket.gaierror: return self.send_error(404, 'name resolution error') except socket.timeout: return self.send_error(504) except ValueError: return self.send_error(502) except httplib.BadStatusLine: return self.send_error(502, 'Bad Gateway: Bad status line') r = c.getresponse() connection = None response_header_exceptions = dict(header_exceptions) response_header_exceptions['connection'] = connection_exception if r.status == 700: resp = utils.parse_request(a.decrypt(r.read())) headers = fix_headers(resp['headers'], response_header_exceptions) status = resp['status'] reason = resp['reason'] body = resp['body'] else: status = r.status reason = r.reason headers = fix_headers(r.getheaders(), response_header_exceptions) if connection: for f in [f.strip() for f in connection.split(',')]: if f in headers: del headers[f] headers.addheader('Connection', 'close') if aes != None: payload = self.create_encrypted_response(headers, r.status, r.reason, r.read(), aes) self.send_response(700, 'Encrypted') self.send_header('Cache-Control', 'no-cache', really_send=True) self.send_header('Content-Length', len(payload), really_send=True) self.wfile.write(payload) else: self.send_response(status, reason) for h, v in headers.items(): self.send_header(h, v, really_send=True) self.end_headers() if r.status == 700: self.wfile.write(body) else: data = r.read(4096) while data: self.wfile.write(data) data = r.read(4096) c.close()
def proxy(self, method, aes=None): if not self.path.startswith('http'): return self.send_error(403, 'scheme not supported') connection = None request_header_exceptions = dict(header_exceptions) def connection_exception(h, k, v): global connection connection = v return True request_header_exceptions['connection'] = connection_exception headers = fix_headers(self.headers.items(), request_header_exceptions) if 'max-forwards' not in headers: headers.addheader('Max-Forwards', '5') u = urlparse.urlparse(self.path) if u.scheme == 'http': if headers['max-forwards'] == '0': c = httplib.HTTPConnection(u.netloc, timeout=10) url = urlparse.urlunparse(('', '') + u[2:]) peer = None else: try: peer = proxymanager.get_peer(True) except proxynet.EmptyPeerList: return self.send_error(502) #print peer c = httplib.HTTPConnection('{0}:{1}'.format( peer['ip'], peer['port']), timeout=proxy_timeout) url = self.path headers.setheader('max-forwards', int(headers['max-forwards']) - 1) if 'via' in headers: # TODO: fix hard coded IP address if headers['via'] == '': headers.setheader( 'via', '1.1 109.74.202.182:{0}'.format(server_address[1])) else: headers.setheader( 'via', headers['Via'] + ', 1.1 109.74.202.182:{0}'.format( server_address[1])) else: return self.send_error(403, 'scheme not supported') if connection: for f in [f.strip() for f in connection.split(',')]: if f in headers: del headers[f] headers.addheader('Connection', 'close') c.set_debuglevel(1) try: if peer != None and 'pub_key' in peer: pubkey = RSA.construct( (long(peer['pub_key']['n']), long(peer['pub_key']['e']))) payload, key, a = self.create_payload(headers, method, url, self.rfile.read(), pubkey) c.putrequest('DATANET', '*', True, True) c.putheader('Host', '*') c.putheader('Session-Key', key[0].encode('base64')) c.putheader('Content-Length', len(payload)) c.endheaders() c.send(payload) else: c.putrequest(method, url, True, True) for h in headers.items(): c.putheader(*h) c.endheaders() content_length = int(self.headers.get('Content-Length', 0)) while content_length > 0: data = self.rfile.read(min(content_length, 4096)) if len(data) == 0: return self.send_error(400) c.send(data) content_length -= len(data) except socket.gaierror: return self.send_error(404, 'name resolution error') except socket.timeout: return self.send_error(504) except ValueError: return self.send_error(502) except httplib.BadStatusLine: return self.send_error(502, 'Bad Gateway: Bad status line') r = c.getresponse() connection = None response_header_exceptions = dict(header_exceptions) response_header_exceptions['connection'] = connection_exception if r.status == 700: resp = utils.parse_request(a.decrypt(r.read())) headers = fix_headers(resp['headers'], response_header_exceptions) status = resp['status'] reason = resp['reason'] body = resp['body'] else: status = r.status reason = r.reason headers = fix_headers(r.getheaders(), response_header_exceptions) if connection: for f in [f.strip() for f in connection.split(',')]: if f in headers: del headers[f] headers.addheader('Connection', 'close') if aes != None: payload = self.create_encrypted_response(headers, r.status, r.reason, r.read(), aes) self.send_response(700, 'Encrypted') self.send_header('Cache-Control', 'no-cache', really_send=True) self.send_header('Content-Length', len(payload), really_send=True) self.wfile.write(payload) else: self.send_response(status, reason) for h, v in headers.items(): self.send_header(h, v, really_send=True) self.end_headers() if r.status == 700: self.wfile.write(body) else: data = r.read(4096) while data: self.wfile.write(data) data = r.read(4096) c.close()
async def run(self, message): user, command, arg = parse_request(message) if command == self.trigger: await self.animate(message.channel)