def health_get_api(): """ Implementation Notes Returns controller health status info, including component status, db status, cluster node info etc. Response Messages 200 Parameters none """ try: (out, err) = subprocess.Popen(['livecloud', 'status'], stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate() out_list = out.split('\n') while '' in out_list: out_list.remove('') del out_list[-1] out = '\n'.join(out_list) out += '\n' err_list = err.split('\n') while '' in err_list: err_list.remove('') del err_list[-1] err = '\n'.join(err_list) err += '\n' return Response(out + err), HTTP_OK except Exception as e: log.error(e) return Response(json.dumps(NEUTRON_500)), HTTP_INTERNAL_SERVER_ERROR
def get(self, play_store_id): start_time = time.time() app = App.for_play_store_id(play_store_id).first() if not app: try: res = requests.get( 'https://play.google.com/store/apps/details?id={}'.format( play_store_id)) if (res.status_code != 200): return Response.error( 'No app found for app id {}'.format(play_store_id), 404) except requests.exceptions.ConnectionError: return Response.error( 'Unable to fetch app from playstore, please try again after sometime', 500) app = App() app.parse_html_and_save(res.text, play_store_id) if not app.reviews.count() > 0: app.parse_and_save_reviews() args = reqparse.RequestParser().add_argument( 'page_num', type=int, required=False).parse_args() return Response.pagination( 'Reviews Delivered in {} seconds'.format( round(time.time() - start_time, 2)), Review.for_play_store_id(play_store_id).with_author(), args.get('page_num') or 1, 40)
def post(self): try: args = self.reqparse.parse_args() email = args['id'] query = db_session.query(models.User).filter(models.User.email == email) user = query.one_or_none() if user is None: # return {'status': 'error', 'code': error_code.Login.NOT_FOUND_ID, 'message': error_code.Login.NOT_FOUND_ID.message()} return Response.error(error_code.Login.NOT_FOUND_ID) if not sha256_crypt.verify(str(args['password']), user.password_hash): # return {'status': 'error', 'code': error_code.Login.WRONG_PASSWORD, 'message': error_code.Login.WRONG_PASSWORD.message()} return Response.error(error_code.Login.WRONG_PASSWORD) if user.confirmed is False: return Response.error(error_code.Login.NOT_CONFORMED) user.last_seen = datetime.now() db_session.commit() session.clear() session[Session.LOGIN_SESSION] = sha256_crypt.encrypt(str(user.code + user.password_hash)) session[Session.USER_SESSION] = user.code session[Session.ADMIN_SESSION] = decorators.is_admin(user.code) current_app.logger.info("Login - " + email) return Response.ok() except Exception as e: current_app.logger.error(str(e)) return Response.error(error_code.Global.UNKOWN)
def post(self): try: args = self.reqparse.parse_args() email = args['email'] query = db_session.query(models.User).filter(models.User.email == email) user = query.one_or_none() if user is not None: current_app.logger.warning("Already register id : " + email) return Response.error(error_code.Login.ALREADY_REGISTER) new_user = models.User(code=generate_uuid(), email=email, password_hash=sha256_crypt.encrypt(str(args['password'])), user_name=args['user_name'], role_id=args['role'], room=args['room'], phone=args['phone']) db_session.add(new_user) db_session.commit() current_app.logger.info("Register new user : "******"/auth/confirm/" + generate_uuid() confirm = models.Confirm(email=email, type=models.Confirm_type.CONFIRM_REGISTER.name, url=url) db_session.add(confirm) db_session.commit() mail.make_confirm_email(email, url) return Response.ok() except Exception as e: current_app.logger.error(str(e)) return Response.error(error_code.Global.UNKOWN)
def compute(self, _data): # _data will be the string returned from the device. # It should look something like this: '41 11 0 0\r\r' # create the response object with the raw data recieved r = Response(_data) # strips spaces, and removes [\n\r\t] _data = "".join(_data.split()) if (len(_data) > 0) and ("NODATA" not in _data) and isHex(_data): # the first 4 chars are codes from the ELM (we don't need those) _data = _data[4:] # constrain number of bytes in response if (self.bytes > 0): # zero bytes means flexible response constrainHex(_data, self.bytes) # decoded value into the response object r.set(self.decode(_data)) else: pass # not a parseable response return r
def delete(self, code): try: db_session.query(models.User).filter(models.User.code == code).delete() return Response.ok() except Exception as e: current_app.logger.error(str(e)) return Response.error(error_code.Global.UNKOWN)
def delete(self, index): try: db_session.query(Notice).filter(Notice.index == index).delete() return Response.ok() except Exception as e: current_app.logger.error(e) return Response.error()
def arp_get_api(): """ Implementation Notes Gets all ARP records. Response Class (Status 200) ArpRecord { ip (string, optional): IP addresss. , mac (string, optional): MAC address. , networkType (string, optional): Network type. Valid values are 'VLAN' and 'VXLAN'. , segmentationId (integer, optional): VLAN id or VXLAN vni } Parameters None """ code = 200 port_items = [] try: with MySQLdb.connect(**DB_INFO) as cursor: sql = 'SELECT * FROM neutron_ports WHERE mac_address IS NOT NULL' cursor.execute(sql) desc = [it[0] for it in cursor.description] for item in cursor: port_items.append(dict(zip(desc, item))) except Exception as e: log.error(e) return Response(json.dumps(NEUTRON_500)), 500 result = [] for port_item in port_items: r_item = models.ArpReply() fields = r_item.serialized_field_names() r_item.mac = port_item.get('mac_address', None) sql = 'SELECT * FROM neutron_networks WHERE id=%s' sql_param = port_item.get('network_id', None) cursor.execute(sql, sql_param if sql_param else '0') desc = [it[0] for it in cursor.description] item = cursor.fetchone() if item: network_item = dict(zip(desc, item)) r_item.network_type = network_item.get('type', None) r_item.segmentation_id = network_item.get('segmentation_id', 0) sql = 'SELECT * FROM neutron_port_ip WHERE port_id=%s' sql_param = port_item.get('id', None) cursor.execute(sql, sql_param if sql_param else '0') desc = [it[0] for it in cursor.description] item = cursor.fetchone() if item: port_ip_item = dict(zip(desc, item)) r_item.ip = port_ip_item.get('ip_address', None) r_item_dict = r_item.filtered_fields(fields) result.append(r_item_dict) return Response(json.dumps(result)), code
def runWithErrorHandling(fn): try: return Response.ok(fn()) except BaseError as error: raise Response.error(error.code, error.message) except AzureError as error: raise Response.error(400, 'Get Azure error: {}'.format(error)) except BaseException as error: raise Response.error(500, 'Unhandled exception: {}.'.format(error))
def get(self): room_list = [] try: for room, is_living in db_session.query(models.Room.room, models.Room.is_living).order_by(desc(models.Room.room)): room_list.append({'room': room, 'is_living': is_living}) return Response.ok(room_list) except Exception as e: current_app.logger.error(str(e)) return Response.error(error_code.Global.UNKOWN)
def subnet_delete_api(subnetid=None): """ Implementation Notes Deletes a subnet. Response Messages (Status 200) Parameters subnetId (string, required): The subnet uuid to act on. """ try: if not subnetid: return err_return('subnetId is required', 'ParameterInvalid', '', HTTP_BAD_REQUEST) cidr = subnet_db_get_one('cidr', id=subnetid) if not cidr: return err_return('subnetId does not exist', 'ParameterInvalid', '', HTTP_NOT_FOUND) if port_ip_db_get_all(subnet_id=subnetid): return err_return('subnet in use', 'ParameterInvalid', '', HTTP_BAD_REQUEST) networkid = subnetid_to_networkid(subnetid) external = network_db_get_one('external', id=networkid) log.debug('external=%s' % external) if external: ret, desc = delete_subnet_by_networkid(networkid) if not ret: return err_return(desc, 'SubnetDeleteFail', '', HTTP_BAD_REQUEST) return Response(), HTTP_OK vl2lcid = yynetworkid_to_lcvl2id(networkid) nets = [{ "prefix": VFW_TOR_LINK_NET_PRE, "netmask": VFW_TOR_LINK_NET_MASK }] subnets = get_subnets_by_network(networkid) for subnet in subnets: if str(subnet['id']) == subnetid: continue cidr = subnet['cidr'].split('/') nets.append({"prefix": cidr[0], "netmask": int(cidr[1])}) nw_name = network_db_get_one('name', id=networkid) payload = json.dumps({"name": nw_name, "nets": nets}) r = lcapi.patch(conf.livecloud_url + '/v1/vl2s/%s' % vl2lcid, data=payload) if r.status_code != HTTP_OK: err = r.json()['DESCRIPTION'] log.error(r.json()['DESCRIPTION']) return err_return(err, 'Fail', '', HTTP_BAD_REQUEST) subnet_db_delete(id=subnetid) return Response(), HTTP_OK except Exception as e: log.error(e) return Response(json.dumps(NEUTRON_500)), HTTP_INTERNAL_SERVER_ERROR
def get(self): role_list = [] try: for id, name in db_session.query(models.Role.id, models.Role.name).order_by(desc(models.Role.id)): role_list.append({'id': id, 'name': name}) # return role_list return Response.ok(role_list) except Exception as e: current_app.logger.error(str(e)) return Response.error(error_code.Global.UNKOWN)
def receiveExtractionTask(): reqData = request.get_json() if not ('resumes' in reqData and type(reqData['resumes']) is list): return Response.BadRequest() print(reqData['resumes']) rw.addResumes(reqData['resumes']) if rw.getThread() is None or not rw.getThread().isAlive(): extractionThread = threading.Thread(target=extractJob, args=()) rw.setThread(extractionThread) extractionThread.start() return Response.Success('The task is in process')
def put(self, code): try: args = self.reqparse.parse_args() room = db_session.query(models.Room).options(joinedload(models.Room.user)).filter(models.Room.room == args['room'] and models.User.code == code).one() room.is_living = args['is_living'] db_session.commit() return Response.ok(room) except Exception as e: current_app.logger.error(str(e)) return Response.error(error_code.Global.UNKOWN)
def portmapping_delete_api(): """ Implementation Notes Deletes a port mapping rule. If no parameters given, delete all rules. If only publicIP given, delete all rules on that IP. If both publicIP and publicPort given, delete that single rule. Parameters Parameter Description Parameter Type Data Type publicIp Public IP Address. query string publicPort Public port. query integer Response Messages HTTP Status Code Reason Response Model Headers 200 Port mapping rule(s) deleted. """ public_ip = request.args.get('publicIp', type=str) public_port = request.args.get('publicPort', type=int) log.debug('publicIp=%s,publicPort=%s' % (public_ip, public_port)) if public_ip is None and public_port is not None: return err_return("Port specified without IP", "IPNotSpecified", "", 400) if public_ip and not validate_ip(public_ip): return err_return('IP(%s) invalid' % public_ip, 'ParameterInvalid', '', 400) if public_port is not None and public_port <= 0: return err_return('Port(%s) invalid' % public_port, 'ParameterInvalid', '', 400) if public_ip and public_port: db_portmaps = portmap_db_get_all(public_ip=public_ip, public_port=public_port) elif public_ip: db_portmaps = portmap_db_get_all(public_ip=public_ip) else: db_portmaps = portmap_db_get_all() if not db_portmaps: log.debug('db_portmaps is None') return Response(), 200 for db_portmap in db_portmaps: portid = port_ip_db_get_one('port_id', ip_address=db_portmap['public_ip']) routerid = port_db_get_one('device_id', id=portid) if not rt_deconf_nat_one_to_one( routerid, 6, db_portmap['public_ip'], db_portmap['ip'], db_portmap['public_port'], db_portmap['port']): return Response(json.dumps(NEUTRON_500)), 500 portmap_db_delete(public_ip=db_portmap['public_ip'], public_port=db_portmap['public_port']) return Response(), 200
def get(self, code=None): try: if code is None: #check admin auth list = db_session.query(models.User).options(joinedload(models.User.role)).options(joinedload(models.User.room_info)).order_by(asc(models.User.email)).all() return Response.ok(list) else: user = db_session.query(models.User).options(joinedload(models.User.role)).options(joinedload(models.User.room_info)).filter(models.User.code == code).one() return Response.ok(user) except Exception as e: current_app.logger.error(str(e)) return Response.error(error_code.Global.UNKOWN)
def arp_byip_delete_api(): """ Implementation Notes Deletes ARP record for given IP address. Response Class (Status 200) Parameters { networkType (string): Network type. Valid values are 'VLAN' and 'VXLAN'. , segmentationId (string): VLAN id or VXLAN vni. , ipAddress (string): IP address. } """ try: req = models.ArpRequest(request.json) req.validate() except Exception as e: result = { "NeutronError": { "message": "Request check failed: %s" % e, "type": "BadRequest", "detail": "" } } log.error(result) return Response(json.dumps(result)), 500 if req.ip_address is None: result = { "NeutronError": { "message": "Request check failed, ipAddress not given", "type": "BadRequest", "detail": "" } } log.error(result) return Response(json.dumps(result)), 500 resp, code = get_arp_byip(req, True) if code != 200: return resp, code resp['macAddress'] = resp['mac'] del resp['mac'] del resp['ip'] req = models.ArpRequest(resp) return delete_arp_bymac(req)
def signInUser(): request_json = request.get_json() data = accessController.signInUser(user={ 'email': request_json['email'], 'password': request_json['password'] }) return Response(200, data)
def watch(self, c, callback=None, force=False): if not (self.has_command(c) or force): debug("'%s' is not supported" % str(c), True) return # if running, the daemon thread must be stopped before altering the command dict was_running = self.running if self.running: self.stop() # new command being watched, store the command if not self.commands.has_key(c): debug("Watching command: %s" % str(c)) self.commands[c] = Response() # give it an initial value self.callbacks[c] = [] # create an empty list # if a callback was given, push it if hasattr(callback, "__call__") and (callback not in self.callbacks[c]): debug("subscribing callback for command: %s" % str(c)) self.callbacks[c].append(callback) # start if neccessary if was_running: self.start()
def rankingResumes(): print('ranking') try: reqData = request.get_json() if not ('resumes' in reqData and type(reqData['resumes']) is list and 'criterions' in reqData and type(reqData['criterions']) is dict): return Response.BadRequest() rankingThread = threading.Thread(target=rankingResumesJob, args=(reqData['_id'], reqData['criterions'], reqData['resumes'])) rankingThread.start() return Response.Success() except: return Response.InternalError()
def delete_arp_bymac(req): code = 200 try: r = lcapi.delete(url=conf.livecloud_talker_url + '/v1/dvs/arps/%s/' % req.mac_address, timeout=30) if r.status_code != 200: return Response(json.dumps(NEUTRON_500)), r.status_code except Exception as e: log.error(e) return Response(json.dumps(NEUTRON_500)), 500 result = {'Reason': 'Reset completed successfully.'} return Response(json.dumps(result)), code
def arp_bymac_get_api(): """ Implementation Notes Returns IP address for given MAC address. Response Class (Status 200) ArpRecord { ip (string, optional): IP addresss. , mac (string, optional): MAC address. , networkType (string, optional): Network type. Valid values are 'VLAN' and 'VXLAN'. , segmentationId (integer, optional): VLAN id or VXLAN vni } Parameters { networkType (string): Network type. Valid values are 'VLAN' and 'VXLAN'. , segmentationId (string): VLAN id or VXLAN vni. , macAddress (string): MAC address. } """ try: req = models.ArpRequest(request.json) req.validate() except Exception as e: result = { "NeutronError": { "message": "Request check failed: %s" % e, "type": "BadRequest", "detail": "" } } log.error(result) return Response(json.dumps(result)), 500 if req.mac_address is None: result = { "NeutronError": { "message": "Request check failed, macAddress not given", "type": "BadRequest", "detail": "" } } log.error(result) return Response(json.dumps(result)), 500 return get_arp_bymac(req)
def subnet_get(subnetid=None, networkid=None): try: if subnetid: item = subnet_db_get_one('*', id=subnetid) if not item: return Response(json.dumps({"ERROR": "subnetId error"})),\ HTTP_NOT_FOUND r_item = models.Subnet() r_item.subnet_id = item['id'] r_item.subnet_name = item['name'] r_item.network_id = item['network_id'] r_item.cidr = item['cidr'] r_item.allocation_pools = json.loads(item['allocation_pools']) r_item.gateway_ip = item['gateway_ip'] r_item.dns_nameservers = json.loads(item['dns_nameservers']) return Response(json.dumps(r_item.to_primitive())), HTTP_OK networkids = [] log.debug('networkid=%s' % networkid) if networkid: networkids.append(networkid) else: with MySQLdb.connect(**DB_INFO) as cursor: sql = "SELECT id FROM neutron_networks" cursor.execute(sql) items = cursor.fetchall() for item in items: networkids.append(item['id']) log.debug('networkids=%s' % networkids) rs = [] for networkid in networkids: items = get_subnets_by_network(networkid) for item in items: r_item = models.Subnet() r_item.subnet_id = item['id'] r_item.subnet_name = item['name'] r_item.network_id = item['network_id'] r_item.cidr = item['cidr'] r_item.allocation_pools = json.loads(item['allocation_pools']) r_item.gateway_ip = item['gateway_ip'] r_item.dns_nameservers = json.loads(item['dns_nameservers']) rs.append(r_item.to_primitive()) return Response(json.dumps(rs)), HTTP_OK except Exception as e: log.error(e) return Response(json.dumps(NEUTRON_500)), 500
def portmapping_get_api(): """ Implementation Notes Gets all port mapping rules. Response Class (Status 200) Inline Model [ PortMapping ] PortMapping { networkId (string, optional): Network to draw public IP from. Dedicated port mapping network could be used. , subnetId (string, optional): Subnet to draw public IP from. Dedicated port mapping subnet could be used. , publicIp (string, optional): Public IP address. , publicPort (integer, optional): Public port assigned for this mapping. , fixedIPInfo (inline_model_1, optional): Fixed IP:port info. } inline_model_1 { ip (string, optional): Fixed IP address. , port (integer, optional): Fixed IP port. } """ items = [] try: with MySQLdb.connect(**DB_INFO) as cursor: cursor.execute('SELECT * FROM portmappings') desc = [it[0] for it in cursor.description] for item in cursor: items.append(dict(zip(desc, item))) ret = [] for it in items: r = models.PortMapping() r.network_id = it.get('network_id', None) r.subnet_id = it.get('subnet_id', None) r.public_ip = it.get('public_ip', None) r.public_port = it.get('public_port', 0) r.fixed_ip_info = models.IPInfo() r.fixed_ip_info.ip = it.get('ip', None) r.fixed_ip_info.port = it.get('port', None) ret.append(r.to_primitive()) return Response(json.dumps(ret)), 200 except Exception as e: log.error(e) return Response(json.dumps(NEUTRON_500)), 500
def put(self, index): try: # parser = fields.get_notice_parser() # args = parser.parse_args() args = self.reqparse.parse_args() notice = db_session.query(Notice).filter(Notice.index == index).one() notice.author_id = db_session.query(User.email).filter(User.email == session.get('email')).one() notice.title = args['title'] notice.content = args['content'] db_session.commit() return Response.ok() except Exception as e: current_app.logger.error(e) return Response.error()
def get(self): args = reqparse.RequestParser().add_argument('page_num', type=int, required=False).parse_args() return Response.pagination( 'Authors delivered', Author, args.get('page_num') or 1, 8 )
def query(self, c, force=False): """ facade 'send' command, protects against sending unsupported commands """ # check that the command is supported if not (self.has_command(c) or force): debug("'%s' is not supported" % str(c), True) return Response() # return empty response else: return self.send(c)
def test_response_custom_cors_content(): global environ # pylint: disable=global-statement, invalid-name temp = environ.copy() cors = "https://bogus" environ["CORS_ALLOW_ORIGIN"] = cors response = json.dumps(Response()) assert response == '{"isBase64Encoded": false, ' \ '"headers": {"Access-Control-Allow-Origin": "' + cors + '"}, "body": "{}"}' environ = temp
def get(self, year=None, month=None): try: if year is None or month is None: date = db_session.query(models.Bill.target_date).order_by(desc(models.Bill.target_date)).first() else: date = datetime.datetime(year, month, 1) bill = [] for month_bill in db_session.query(models.Bill).filter(models.Bill.target_date == date).all(): bill.append( {'date': '{:%Y %m}'.format(date), 'room': month_bill.room, 'electric': {'usage': month_bill.electric_usage, 'amount': month_bill.electric_amount}, 'gas': {'usage': month_bill.gas_usage, 'amount': month_bill.gas_amount}, 'description': month_bill.description}) return Response.ok(bill) except Exception as e: current_app.logger.error(str(e)) return Response.error(error_code.Global.UNKOWN)
def get(self): try: user = session.get(Session.USER_SESSION) bill = [] for target_date, electric_usage, electric_amount, gas_usage, gas_amount, description in db_session.query(models.Bill.target_date, models.Bill.electric_usage, models.Bill.electric_amount, models.Bill.gas_usage, models.Bill.gas_amount, models.Bill.description).filter( models.Bill.author_id == user).all(): date = '{:%Y %m}'.format(target_date) bill.append({'date': date, 'electric': {'usage': electric_usage, 'amount': electric_amount}, 'gas': {'usage': gas_usage, 'amount': gas_amount}, 'description': description}) return Response.ok(bill) except Exception as e: current_app.logger.error(str(e)) return Response.error(error_code.Global.UNKOWN)
def run_method(*args): request = args[0] method = args[1] if len(args)>2: params = args[2:] else: params = [] response = Response() response.instance_name = request.instance_name try: data = method(*params) except Exception, e: # TODO: Error should be json data logging.error(e) response.value = str(e) callback(FLAG_ERR, response)
def post(self, year, month): try: args = self.reqparse.parse_args() for bill in args['bill']: user = db_session.query(models.User.code).filter(models.User.room == bill['room']).one_or_none() user_bill = models.Bill(target_date=datetime.datetime(year, month, 1), room=bill['room'], author_id=user, electric_usage=bill['electric']['usage'], electric_amount=bill['electric']['amount'], gas_usage=bill['gas']['usage'], gas_amount=bill['gas']['amount'], description=bill['description']) db_session.add(user_bill) db_session.commit() return Response.ok() except Exception as e: db_session.rollback() current_app.logger.error(str(e)) return Response.error(error_code.Global.UNKOWN)
def port_delete_api(id): """ Implementation Notes Deletes a port. Parameters portId Response Messages HTTP Status Code Reason Response Model Headers 200 Port deleted. """ try: with MySQLdb.connect(**DB_INFO) as cursor: sql = 'SELECT * FROM neutron_ports WHERE id=%s' cursor.execute(sql, id) item = cursor.fetchone() if item is None: result = { "NeutronError": { "message": "Port %s could not be found" % id, "type": "PortNotFound", "detail": "" } } return Response(json.dumps(result)), 404 desc = [it[0] for it in cursor.description] port = dict(zip(desc, item)) url = conf.livecloud_url + '/v1/interfaces/%s/' % port['lcuuid'] url += '?skip_switch_config=false' log.debug('Delete to %s' % url) lcapi.delete(url) sql = 'DELETE FROM neutron_ports WHERE id=%s' cursor.execute(sql, id) sql = 'DELETE FROM neutron_port_ip WHERE port_id=%s' cursor.execute(sql, id) except Exception as e: log.error(e) return Response(json.dumps(NEUTRON_500)), 500 return Response(), 200
def verified(request, *args, **kwargs): user = User.objects.get(invite_code=request.session['user']) if user.phone == None or len(user.phone) == 0: if request.method == 'GET': request.session['backUrl'] = request.get_full_path() else: request.session['backUrl'] = '/' # 如果是post请求的话则要告诉前端进行跳转 return HttpResponse(Response(c=-2, m='/user?action=verify&type=phone').toJson(), content_type="application/json") return redirect('/user?action=verify&type=phone') return view(request, *args, **kwargs)
def test_response_body(): response = Response(name="TestResponse") assert response.body == '{"name": "TestResponse"}' response.put("Some Message") assert re.search('"http_code": 200', response.body) assert re.search('"message": "Some Message"', response.body) assert re.search(r'"timestamp": "[0-9|\-|\.|:|T|Z]+"', response.body) response.put(Exception("Some error")) assert re.search('"message": "Some error"', response.body) assert re.search('"http_code": 500', response.body) response.put(HandledError("Some other error", status_code=400)) assert re.search('"message": "Some other error"', response.body) assert re.search('"http_code": 400', response.body) response.put(NotImplementedError("Something else")) assert re.search('"message": "Something else"', response.body) assert re.search('"http_code": 501', response.body)
def post(self): try: # parser = fields.get_notice_parser().copy() args = self.reqparse.parse_args() title = args['title'] content = args['content'] # email = session.get('email') code = session.get(Session.USER_SESSION) # get json from request BUT title and content is null when they was inserted user = db_session.query(User.code).filter(User.code == code).one() new_notice = Notice(title=title, content=content, author_id=user) db_session.add(new_notice) db_session.commit() return Response.ok() except Exception as e: current_app.logger.error(e) return Response.error()
def get(self, play_store_id): app_found = App.for_play_store_id(play_store_id).first() if (app_found): return Response.model('Delivered', app_found) try: res = requests.get( 'https://play.google.com/store/apps/details?id={}'.format( play_store_id)) if (res.status_code != 200): return Response.error( 'No app found for app id {}'.format(play_store_id), 404) except requests.exceptions.ConnectionError: return Response.error( 'Unable to fetch app from playstore, please try again after sometime', 500) new_app = App() new_app.parse_html_and_save(res.text, play_store_id) return Response.model('Delivered', new_app)
def put(self, code): try: args = self.reqparse.parse_args() user = db_session.query(models.User).options(joinedload(models.User.role)).options(joinedload(models.User.room_info)).filter(models.User.code == code).one() if args['password'] is not None: user.password_hash = sha256_crypt.encrypt(str(args['password'])) if args['confirmed'] is not None: user.confirmed = args['confirmed'] if args['user_name'] is not None: user.user_name = args['user_name'] if args['phone'] is not None: user.phone = args['phone'] db_session.commit() return Response.ok(user) except Exception as e: current_app.logger.error(str(e)) return Response.error(error_code.Global.UNKOWN)
def send(self, c): """ send the given command, retrieve and parse response """ # check for a connection if not self.is_connected(): debug("Query failed, no connection available", True) return Response() # return empty response # send the query debug("Sending command: %s" % str(c)) self.port.send(c.get_command()) # send command to the port return c.compute( self.port.get()) # get the data, and compute a response object
def signUpUser(): request_json = request.get_json() username = '******' password = '******' email = 'email' if username in request_json and password in request_json: userSignUpController = accessController.signUpUser( user={ 'username': request_json[username], 'password': EncryptPassword.encrypt(request_json[password]), 'email': request_json[email] }) return Response(200, userSignUpController)
def arp_delete_api(): """ Implementation Notes Removes all records in ARP db. Response Class (Status 200) Parameters None """ code = 200 try: r = lcapi.delete(url=conf.livecloud_talker_url + '/v1/dvs/arps/', timeout=30) if r.status_code != 200: return Response(json.dumps(NEUTRON_500)), r.status_code except Exception as e: log.error(e) return Response(json.dumps(NEUTRON_500)), 500 result = {'Reason': 'Reset completed successfully.'} return Response(json.dumps(result)), code
def test_send_throws(mock): with pytest.raises(KeyError): send_to_pushover.send({"payload": "missing title in event"}) with pytest.raises(KeyError): send_to_pushover.send({"title": "missing payload in event"}) with pytest.raises(HandledError) as error: mock.return_value = Response() mock.return_value.put({ "status": 0, # wrong `status` value, expected 1 "request": "XXX-SOME-UNIQUE-ID-XXX", }) send_to_pushover.send({"title": "fake title", "payload": "some message here"}) assert error.status_code == 500 with pytest.raises(HandledError) as error: mock.return_value = Response() mock.return_value.put({ "status": 1, # missing `request` key }) send_to_pushover.send({"title": "fake title", "payload": "some message here"}) assert error.status_code == 500
def get(self, index): notice = db_session.query(Notice).filter(Notice.index == index).one() # add counter session_notice = session.get(Session.NOTICE_BOARD) if session_notice is None or str(index) not in session_notice: notice.counter += 1 db_session.commit() if session_notice is None: session[Session.NOTICE_BOARD] = {str(index): True} else: session_notice[str(index)] = True return Response.ok(notice)
def query(self, command, force=False): #print "TX: " + str(command) if self.has_command(command) or force: debug("Sending command: %s" % str(command)) # send command to the port self.port.send(command.get_command()) # get the data, and compute a response object return command.compute(self.port.get()) else: print "'%s' is not supported" % str(command) return Response() # return empty response
def unKnownErr(request, *args, **kwargs): try: return view(request, *args, **kwargs) except Exception, e: errId = '%s.%s' % (str(time.time()), str(random.randint(0, 1000))) print '*' * 10, 'errid:', errId, '*' * 10 traceback.print_exc() print '*' * 10, 'endof:', errId, '*' * 10 info = sys.exc_info() info = str(info[1]).decode("unicode-escape") # 如果一个post请求发生了未知的错误,则告诉前端将页面跳转到错误页面 if request.method == 'POST': return HttpResponse(Response(c=-2, m='/error?msg=%s' % errId).toJson(), content_type="application/json") # 如果是一个get请求发生了为知的错误,则将页面重定向到错误情面 return HttpResponseRedirect('/error?msg=%s' % errId)
def get(self, page=1): count = db_session.query(Notice).count() if count == 0: pagination = {'page': page, 'per_page': PER_PAGE, 'total_count': count} return {'paging': pagination} # boardList = db_session.query(Notice).options(joinedload(User)).order_by(desc(Notice.index))[(page - 1) * PER_PAGE: page * PER_PAGE] boardList = [] for index, title, counter, registerDate, user_name in db_session.query(Notice.index, Notice.title, Notice.counter, Notice.register_date, User.user_name). \ join(User, Notice.author_id == User.code).order_by(desc(Notice.index))[ (page - 1) * PER_PAGE: page * PER_PAGE]: boardList.append({'index': index, 'title': title, 'author_id': user_name, 'counter': counter, 'register_date': registerDate}) pagination = {'page': page, 'per_page': PER_PAGE, 'total_count': count} return Response.ok({'notice': boardList, 'paging': pagination})
def test_send(mock): mock.return_value = Response() mock.return_value.put({ "status": 1, "request": "XXX-SOME-UNIQUE-ID-XXX", }) send_to_pushover.send({"title": "fake title", "payload": "some message here"}) assert mock.called assert mock.call_args.kwargs == { "url": send_to_pushover.PUSHOVER_API_ENDPOINT, "data": { "token": env["PUSHOVER_TOKEN"], "user": env["PUSHOVER_USERKEY"], "message": "some message here", "title": "fake title", }, }
def nmap(host, num=0): ''' This function uses xmltodict <mydocument has="an attribute"> <and> <many>elements</many> <many>more elements</many> </and> <plus a="complex"> element as well </plus> </mydocument> doc['mydocument']['@has'] # == u'an attribute' doc['mydocument']['and']['many'] # == [u'elements', u'more elements'] doc['mydocument']['plus']['@a'] # == u'complex' doc['mydocument']['plus']['#text'] # == u'element as well' ''' response = Response() p = multiprocessing.current_process() print(p.name, p.pid) a = 'nmap -O {h} -oX -'.format(h=host) print(host) try: r = subprocess.check_output(a) except Exception as error: response.success = False response.error = str(error) return response try: doc = xmltodict.parse(r) response.result = doc except Exception as error: response.success = False response.error = str(error) return response time.sleep(num) return response