def users(user_id=None): """ Manages return of /users/ pages """ if user_id is None: if request.method == "POST": form = request.get_json() if form is None: return "Not a JSON", 400 if form.get('email') is None: return "Missing email", 400 if form.get('password') is None: return "Missing password", 400 new_user = User(**form) new_user.save() return new_user.to_dict(), 201 if request.method == "GET": users = storage.all(User).values() users = [user.to_dict() for user in users] return jsonify(users) user = storage.get(User, user_id) if user is None: abort(404) if request.method == "DELETE": user.delete() storage.save() return {} if request.method == "PUT": form = request.get_json() if form is None: return "Not a JSON", 400 for key, value in form.items(): if key not in ['id', 'email', 'created_at', 'updated_at']: setattr(user, key, value) user.save() return user.to_dict()
def spotify_search(): """Search interface for javascript frontend function 'get_spotify_search_results' """ # POST request if request.method == 'POST': # Get values from post request search_text = request.get_json()["search_text"] music_type = MusicType[request.get_json()["music_type"]] # Initialize response dict response_dict = {"music_results": [], "invalid_link": False} # Get the corresponding list of music to the search text. If the text # is an open spotify link, then attempt to get the music from it. # Otherwise, just search for the text in spotify and get a list of results. if re.match(r'https*://open.spotify.com/', search_text): if spotify_iface.spotify_link_invalid(music_type, search_text): response_dict["invalid_link"] = True else: music = spotify_iface.get_music_from_link(music_type, search_text) response_dict["music_results"] = [music.format_for_response_dict()] elif search_text: music_results = spotify_iface.search_for_music(music_type, search_text, num_results=20) response_dict["music_results"] = [music.format_for_response_dict() for music in music_results] return response_dict, 200
def amenities(amenity_id=None): """ Manages return of /amenities/ pages """ if amenity_id is None: if request.method == "POST": form = request.get_json() if form is None: return "Not a JSON", 400 if form.get('name') is None: return "Missing name", 400 new_amenity = Amenity(**form) new_amenity.save() return new_amenity.to_dict(), 201 if request.method == "GET": amenities = storage.all(Amenity).values() amenities = [amenity.to_dict() for amenity in amenities] return jsonify(amenities) amenity = storage.get(Amenity, amenity_id) if amenity is None: abort(404) if request.method == "DELETE": amenity.delete() storage.save() return {} if request.method == "PUT": form = request.get_json() if form is None: return "Not a JSON", 400 for key, value in form.items(): if key not in ['id', 'created_at', 'updated_at']: setattr(amenity, key, value) amenity.save() return amenity.to_dict()
def states(state_id=None): """ Manages return of /states/ pages """ # Handle '/states/' cases if state_id is None: if request.method == "POST": form = request.get_json() if form is None: return "Not a JSON", 400 if form.get('name') is None: return "Missing name", 400 new_state = State(**form) new_state.save() return new_state.to_dict(), 201 if request.method == "GET": states = storage.all(State).values() states = [state.to_dict() for state in states] return jsonify(states) # Handle '/states/<state_id>' cases # get state state = storage.get(State, state_id) # abort if state doesn't exist if state is None: abort(404) # if "DELETE", delete state, return empty dict if request.method == "DELETE": state.delete() storage.save() return {} # if "PUT", update state if request.method == "PUT": form = request.get_json() if form is None: return "Not a JSON", 400 for key, value in form.items(): if key not in ['id', 'created_at', 'updated_at']: setattr(state, key, value) state.save() # return dict representation of state # Flask returns exit code 200 by default-- no need to specify it. return state.to_dict()
def signup(): ''' Callback for validation of signup ''' # Extracts data from the posted request container = request.get_json(False, True, False) if request.mimetype == "application/json" else request.form login = container["login"] password = container["password"] email = container["email"] # Checks parameters are filled if (not login) or (not password) or (not email): return jsonify(message = "Login, password and email must be filled."), 400 # Checks if a user with given login already exists in db if not user_db_service.get_user_by_login(login) is None: return jsonify(message = "This login is already used."), 400 # # Here we should check that email is valid and not already registered in db. # Then we would send a email to this address with an hyperlink to allow the user to confirm her address. # For the sake of simplicity, let's forget all this stuff and let's validate the account # # Registers user in db user = User(login, password, email) user.signin_count += 1 user_db_service.create_user(user) # Everything is ok, let's finalize the authentication session["uid"] = user.uid session["auth"] = True # Redirects to user page return jsonify(redirect_uri = url_for("user"))
def convert_to_text(): LoggerUtil.getLogger(__name__) logging.info("received request for conversion") jsonRequestData = request.get_json(force=True) reqData = json.dumps(jsonRequestData) logging.debug("getting JSON request data") converterRequestData = jsonpickle.decode(reqData) outputData = ConverterData() for fileObj in converterRequestData["files"]: fileOutputObj = FileObject() fileOutputObj.extn = "txt" fileOutputObj.id = fileObj["id"] logging.debug("decoding base64 file data") decodedData = base64.b64decode(fileObj["data"]) extnConverter = ConverterFactory.getInstance(fileObj["extn"]) if extnConverter == None: logging.error("unsupported extension %s", fileObj["extn"]) fileOutputObj.error = "Extension not supported" else: logging.debug("writing file to disk") fileName = FileObject.writeFileToDisk(fileObj["id"], fileObj["extn"], decodedData) logging.debug("converting file to txt") textData = extnConverter.convert(fileName) fileOutputObj.data = base64.b64encode(bytes( textData, "utf-8")).decode('ascii') outputData.files.append(fileOutputObj) logging.info("returning response") text = jsonpickle.encode(outputData, unpicklable=False) logging.info(text) return jsonpickle.encode(outputData, unpicklable=False)
def find(): try: items, totalCount = user_service.find_filtered(request.oauth.user, request.get_json()) response = [n.to_json() for n in items] return jsonify({'response': response, 'totalCount': totalCount}) except ServiceError: raise BadRequest('A service error occurred')
def query(): payload = request.get_json(silent=True) if payload.get('query') is None: return 'Not good' query = payload['query'] data = schema.execute(query) return json.dumps({'data': data.data, 'error': data.errors})
def index(): try: data = request.get_json() df = pd.read_csv("./%s.csv" % (data['token'])) df = df[df['State/UnionTerritory'] == data["State"]] df["Confirmed"] = df["Confirmed"].diff() df = df.dropna() X = df[["Date", "Confirmed"]].values clf = algorithms[int(data["Algorithm"])] X = X[:, 1].reshape(X.shape[0], 1) if int(data["Algorithm"]) == 0: Y = clf.fit_predict(X) else: Y = clf.fit(X).predict(X) df["Anomaly"] = Y a = df[df["Anomaly"] == -1] fig = go.Figure() fig.add_trace( go.Scatter(x=df["Date"], y=df["Confirmed"], name='Confirmed')) fig.add_trace( go.Scatter(x=a["Date"], y=a["Confirmed"], mode='markers', name='Anomaly')) fig.update_layout( showlegend=True, title='Detected anomalies(Algorithm:%s, State:%s)' % (str(algorithms[int( data["Algorithm"])]).split("(")[0], data['State'])) fig.write_html("./templates/%s.html" % (data['token'])) return render_template("%s.html" % (data['token'])) except KeyError: return "Algorithm Not Specified"
def add_id_card(): data = request.get_json() link = data['link'] session_user = tokenAuth.current_user() session_user.id_card = link db.session.commit() return make_response({"msg":"added id card link", link:link},200)
def put(self): request_data = request.get_json(force=True) order_id = int(request_data.get('order_id')) order_obj = Order.objects.get(sales_order_id=order_id) order_obj.status = str(request_data.get('status')) order_obj.save() return "Status successfully updated"
def post(self): data = request.get_json() chem_composition = ChemicalComposition(data['commodity_id'], data['element_id'], data['percentage']) chem_composition.save_to_db() return chem_composition.json(), 200
def cleanup_uploads(): """ Deletes uploaded images (input image and extra input images, if any), for each of the given keys in the data to process or list of filenames to process """ data = request.get_json()['data'] for file_name in data: # Delete the file from uploads/images file_path = os.path.join(app.config['IMAGES_DIR'], file_name) try: os.remove(file_path) except OSError as err: print('>>> [/cleanup/uploads] Error deleting file:', file_name) print('>>>', err) # Delete associated extra inputs from uploads/images/extra_inputs extra_inputs = [ file for file in os.listdir(app.config['EXTRA_IMAGES_DIR']) if file.startswith(file_name.split('.')[0] + '_') ] for extra in extra_inputs: extra_path = os.path.join(app.config['EXTRA_IMAGES_DIR'], extra) try: os.remove(extra_path) except OSError as err: print('>>> [/cleanup/uploads] Error deleting file:', extra) print('>>>', err) return make_response(jsonify('Server: Uploaded files have been deleted'), 200)
def cleanup_tempdata(): """ Deletes the resulting images (processed images and pickles) for each of the given list of processed files """ filenames = request.get_json()['filenames'] for filename in filenames: # Delete the processed file processed_path = os.path.join(app.config['TEMP_DATA'], filename) try: if os.path.exists(processed_path): os.remove(processed_path) else: print('>>> [/cleanup/tempdata] Requested file does not exist:', filename) except OSError as err: print('>>> [/cleanup/tempdata] Error deleting file:', filename) print('>>>', err) # Delete the pickled channels unprocessed_filename = filename.rsplit('_', 1)[0] for channel in 'rgba': pickle_name = unprocessed_filename + '_' + channel + '.pickle' pickle_path = os.path.join(app.config['TEMP_DATA'], pickle_name) try: if os.path.exists(pickle_path): os.remove(pickle_path) # else: # print('>>> [/cleanup/tempdata] Pickle does not exist:', pickle_name) except OSError as err: print('>>> [/cleanup/tempdata] Error deleting pickle:', pickle_name) print('>>>', err) return make_response(jsonify('Server: Result files have been deleted'), 200)
def reviews_API(place_id=None, reviews_id=None): """ Get all reviews based on place ID """ if place_id is None: abort(404) the_place = storage.get(Place, place_id) if the_place is None: abort(404) if request.method == "GET": review_list = the_place.reviews review_list = [review.to_dict() for review in review_list] return jsonify(review_list) if request.method == "POST": form = request.get_json() if form is None: return "Not a JSON", 400 user_id = form.get('user_id') if user_id is None: return "Missing user_id", 400 if storage.get(User, user_id) is None: abort(404) if form.get('text') is None: return "Missing text", 400 new_review = Review(**form) setattr(new_review, 'place_id', place_id) new_review.save() return new_review.to_dict(), 201
def control(device): """Change or check the status of one of the machine/interface's controls: -caster's pump, -caster's motor (using two relays), -compressed air supply, -cooling water supply, -solenoid valves. GET checks the device's state, DELETE turns the device off, PUT turns it on POST turns on (state=True), off (state=False) """ # find a suitable interface method, otherwise it's not implemented # handle_request will reply 501 method_name = '{}_control'.format(device) request_data = request.get_json() or {} device_state = request_data.get('state') try: routine = getattr(self, method_name) except AttributeError: raise NotImplementedError # we're sure that we have a method if request.method == POST and device_state is not None: routine(bool(device_state)) elif request.method == PUT: routine(ON) elif request.method == DELETE: routine(OFF) # always return the current state of the controlled device return dict(active=self.status.get(device))
def Places_API(city_id=None): """ Get all cities based on State ID """ if city_id is None: abort(404) the_city = storage.get(City, city_id) if the_city is None: abort(404) if request.method == "GET": place_list = the_city.places place_list = [place.to_dict() for place in place_list] return jsonify(place_list) if request.method == "POST": form = request.get_json() if form is None: return "Not a JSON", 400 if form.get('user_id') is None: return 'Missing user_id', 400 the_user = storage.get(User, form.get('user_id')) if the_user is None: abort(404) if form.get('name') is None: return "Missing name", 400 new_place = Place(**form) setattr(new_place, 'city_id', city_id) new_place.save() return new_place.to_dict(), 201
def simulate(): simulator = Simulator() req_data = request.get_json() data = {'price':[req_data['price']], 'bedrooms':[req_data['bedrooms']], 'bath':[req_data['bath']], 'size_sqft':[req_data['size_sqft']], 'professionally_managed':[req_data['professionally_managed']], 'no_pet_allowed':[req_data['no_pet_allowed']], 'suit_laundry':[req_data['suit_laundry']], 'park_stall':[req_data['park_stall']], 'available_now':[req_data['available_now']], 'amenities':[req_data['amenities']], 'brand_new':[req_data['brand_new']], 'loc_vancouver':[req_data['loc_vancouver']], 'loc_burnaby':[req_data['loc_burnaby']], 'loc_richmond':[req_data['loc_richmond']], 'loc_surrey':[req_data['loc_surrey']], 'loc_newwest':[req_data['loc_newwest']], 'loc_abbotsford':[req_data['loc_abbotsford']], 'no_basement':[req_data['no_basement']] } # Create DataFrame record = pd.DataFrame(data) record = simulator.simulate(record) return record.to_json(orient='index')
def insertStudentDetails(): #Save the data to database student = request.get_json() print(student) print("Saving the Data to DataBase") result = s_util.save_Details_To_DB(student) return result
def compra(): json_data = request.get_json() if not json_data: return {"message": "No data provided"}, 400 # Validate and deserialize input try: precioIdQuantityList = json_data['precioIdQuantitySelected'] asientosId = json_data['asientoIdSelected'] funcionId = json_data['funcionId'] email = json_data['email'] nombre = json_data['nombre'] cont = 0 ticketIdList = [] for e in precioIdQuantityList: for x in range(e['quantity']): asientoId = asientosId[cont] ticketId = ticketService.create_ticket(asientoId, e['precioId'], email, nombre) ticketIdList.append(ticketId) cont += 1 compra = compraService.compra(funcionId, ticketIdList, email, nombre) sendmail(compraService.get_compra(compra)) except ValueError as e: print(e) return Response(mimetype="application/json", status=HTTPStatus.INTERNAL_SERVER_ERROR, response=json.dumps({"message": str(e)})) return Response('{"data": "JSON string example"}', headers=dict({"HeaderExample": "HeaderContent"}), mimetype="application/json")
def check_signature(callback_uri): # Extracts data from the posted request (from form of from json data according to the method used by the client) container = request.get_json(False, True, False) if request.mimetype == "application/json" else request.form bitid_uri = container["uri"] signature = container["signature"] address = container["address"] # Checks the address if not bitid.address_valid(address, USE_TESTNET): return (False, None, address, "Address is invalid or not legal") # Checks the bitid uri if not bitid.uri_valid(bitid_uri, callback_uri): return (False, None, address, "BitID URI is invalid or not legal") # Checks the signature if not bitid.signature_valid(address, signature, bitid_uri, callback_uri, USE_TESTNET): return (False, None, address, "Signature is incorrect") # Note that the previous 3 steps could also be done in 1 step with following code: # if not bitid.challenge_valid(address, signature, bitid_uri, callback_uri, USE_TESTNET): # return (False, "Sorry but something does not match") # Checks the nonce nid = bitid.extract_nonce(bitid_uri) # Tries to retrieve the nonce from db nonce = nonce_db_service.get_nonce_by_nid(nid) if nonce is None: return (False, None, address, "NONCE is illegal") elif nonce.has_expired(): nonce_db_service.delete_nonce(nonce) return (False, None, address, "NONCE has expired") # Everything is ok return (True, nonce, address, "")
def basic_auth(): ''' Checks basic authentication by login/password ''' # Extracts data from the posted request container = request.get_json(False, True, False) if request.mimetype == "application/json" else request.form login = container["login"] password = container["password"] # Checks parameters are filled if (not login) or (not password): return jsonify(message = "Login, password and email are mandatory"), 400 # Checks if user with given login exists in db user = user_db_service.get_user_by_login(login) if user is None: return jsonify(message = "Wrong login and password combination."), 400 # Checks user password if not user.check_password(password): return jsonify(message = "Wrong login and password combination."), 400 # Registers user id in session session["uid"] = user.uid # Checks if 2fa is activated if user.tfa_activited(): # 2FA activated - Redirects to tfa_challenge page return jsonify(redirect_uri = url_for("tfa_challenge")) else: # Basic auth only # Let's increase the sign_in counter in user object (for demo purpose only) user.signin_count += 1 user_db_service.update_user(user) # Everything is ok, let's finalize the authentication session["auth"] = True # Redirects to user page return jsonify(redirect_uri = url_for("user"))
def add_order(data, id): userID = data["id"] body = request.get_json() menus = body['menus'] if not menus: return {'success': False, 'message': 'ไม่พบเมนู'}, 400 have_order = Order.query.filter( func.DATE(Order.created_at) == date.today(), Order.shop_id == id, Order.customer_id == userID, or_(Order.status == 'ordering', Order.status == 'waiting')).count() if not have_order: new_order = Order( customer_id=userID, shop_id=id, note=body["note"], menus=[ OrderMenu(menu_id=menu['id'], extra=menu['is_extra'], total=menu['total']) for menu in menus ], queue='A%02d' % Order.query.filter( func.DATE(Order.created_at) == date.today()).count()) db.session.add(new_order) db.session.commit() return { 'success': True, 'order': new_order.getData(), }, 201 return {'success': False, 'message': 'คุณมีออเดอร์ของร้านนี้อยู่แล้ว'}, 400
def check_signature(callback_uri): # Extracts data from the posted request (from form of from json data according to the method used by the client) container = request.get_json( False, True, False) if request.mimetype == "application/json" else request.form bitid_uri = container["uri"] signature = container["signature"] address = container["address"] # Checks the address if not bitid.address_valid(address, USE_TESTNET): return (False, None, address, "Address is invalid or not legal") # Checks the bitid uri if not bitid.uri_valid(bitid_uri, callback_uri): return (False, None, address, "BitID URI is invalid or not legal") # Checks the signature if not bitid.signature_valid(address, signature, bitid_uri, callback_uri, USE_TESTNET): return (False, None, address, "Signature is incorrect") # Note that the previous 3 steps could also be done in 1 step with following code: # if not bitid.challenge_valid(address, signature, bitid_uri, callback_uri, USE_TESTNET): # return (False, "Sorry but something does not match") # Checks the nonce nid = bitid.extract_nonce(bitid_uri) # Tries to retrieve the nonce from db nonce = nonce_db_service.get_nonce_by_nid(nid) if nonce is None: return (False, None, address, "NONCE is illegal") elif nonce.has_expired(): nonce_db_service.delete_nonce(nonce) return (False, None, address, "NONCE has expired") # Everything is ok return (True, nonce, address, "")
def signup(): ''' Callback for validation of signup ''' # Extracts data from the posted request container = request.get_json( False, True, False) if request.mimetype == "application/json" else request.form login = container["login"] password = container["password"] email = container["email"] # Checks parameters are filled if (not login) or (not password) or (not email): return jsonify( message="Login, password and email must be filled."), 400 # Checks if a user with given login already exists in db if not user_db_service.get_user_by_login(login) is None: return jsonify(message="This login is already used."), 400 # # Here we should check that email is valid and not already registered in db. # Then we would send a email to this address with an hyperlink to allow the user to confirm her address. # For the sake of simplicity, let's forget all this stuff and let's validate the account # # Registers user in db user = User(login, password, email) user.signin_count += 1 user_db_service.create_user(user) # Everything is ok, let's finalize the authentication session["uid"] = user.uid session["auth"] = True # Redirects to user page return jsonify(redirect_uri=url_for("user"))
def basic_auth(): ''' Checks basic authentication by login/password ''' # Extracts data from the posted request container = request.get_json( False, True, False) if request.mimetype == "application/json" else request.form login = container["login"] password = container["password"] # Checks parameters are filled if (not login) or (not password): return jsonify(message="Login, password and email are mandatory"), 400 # Checks if user with given login exists in db user = user_db_service.get_user_by_login(login) if user is None: return jsonify(message="Wrong login and password combination."), 400 # Checks user password if not user.check_password(password): return jsonify(message="Wrong login and password combination."), 400 # Registers user id in session session["uid"] = user.uid # Checks if 2fa is activated if user.tfa_activited(): # 2FA activated - Redirects to tfa_challenge page return jsonify(redirect_uri=url_for("tfa_challenge")) else: # Basic auth only # Let's increase the sign_in counter in user object (for demo purpose only) user.signin_count += 1 user_db_service.update_user(user) # Everything is ok, let's finalize the authentication session["auth"] = True # Redirects to user page return jsonify(redirect_uri=url_for("user"))
def create_user(): data = request.get_json() login_manager = LoginManager() if 'email' not in data: return jsonify({"message": 'Campo e-mail é obrigatório'}), 401 regex = '^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,})$' match = re.match(regex, data['email'].lower()) if match is None or not valida_sufixos_hosts_email(data['email']): return jsonify({"message": 'Campo e-mail inválido'}), 401 user = {**data, 'email': data['email'],'password': login_manager.password_to_hash(data['password'])} try: user_exists = db.collection_users.find_one({'email': user['email']}) there_is_user = user_exists if user_exists else {} if 'password' in there_is_user: return jsonify({'message': 'Usuário já cadastro'}), 401 else: user_temp = user user_temp['_id'] = db.collection_users.insert_one(user).inserted_id user_temp['_id'] = str(user_temp['_id']) token = login_manager.generate_auth_token(user_temp, 600000).decode('ascii') template = render_template('bem-vindo.html', nome=user_temp['email'], token=token, api_url=API) mail = SendEmail() mail.send_verify_email(template, user_temp['email']) return jsonify({"message": 'Usuário cadastrado com sucesso'}), 201 except Exception as e: return not_found(e)
def post(): """ 유저 정보를 받아와 새로운 유저를 생성해 준다. """ print("-------- signup.py --------\n") body = request.get_json() print('type(body): ', type(body)) print('body:' , body) user = UserDto(**body) print(f'[ user Dto ] {user}') print('아이디: ', user.user_id) print('비밀번호: ', user.password) print('이름: ', user.name) print('성별: ', user.gender) print('나이: ', user.age) print('핸드폰 번호: ', user.phone) print('이메일: ', user.email) try: UserDao.register(user) return "worked.." except Exception as e: return e
def add_configs_byproject(self, project): """add config item by project api method.""" if redis_slave.sismember(CONF_PROJECTS_KEY_FORMAT, project): if self._check_conf_permission(project, 'write'): data = request.get_json() if data.get('name') and data.get('value'): if not self._check_conf_exists(project, data['name']): try: value = json.loads(data.get('value')) except Exception: value = data.get('value') item = ConfItem(project, data.get('name'), value) #---we are going to use rejson to wrap the use custmize config item value into JSON type pipe = redis_master.pipeline() pipe.jsonset( CONF_KEY_FORMAT.format(p=project, k=data.get('name')), '.', item) pipe.sadd(CONF_PROJECT_KEYSET_FORMAT.format(p=project), data.get('name')) pipe.execute() log.info("Successfully add config {c} for project {p} by {u}".format(c=data.get('name'), \ p=project, u=g.user.username)) return jsonify({'message': 'success'}) else: return jsonify({'message': 'Key exists'}), 400 else: return jsonify({'message': 'Wrong parameter data'}), 400 else: return jsonify({'message': 'doesn\'t have permission'}), 403 else: return jsonify({'message': 'project does not exists'}), 400
def initialise(): files = request.get_json()['files'] images = files['image'] videos = files['video'] for image in images: # Initialise the data needed for each image file_path = os.path.join(app.config['IMAGES_DIR'], image) image_file = cv2.imread(file_path, cv2.IMREAD_UNCHANGED) image_name_components = image.split('.') if utils.is_grayscale(image_file): # Compute the padded image image_h, image_w = image_file.shape[:2] # padded_h, padded_w = 2 * image_h, 2 * image_w # padded_image = np.zeros((padded_h, padded_w), np.uint8) # padded_image[0:image_h, 0:image_w] = image_file # # Compute the FFT of the padded image # padded_image_FFT = np.fft.fftshift(np.fft.fft2(padded_image)) # # Serialise the FFT of the padded image # pickle_name = image_name_components[0] + '_fft.pickle' # pickle_path = os.path.join(app.config['TEMP_DATA'], pickle_name) # with open(pickle_path, 'wb') as f: # pickle.dump(padded_image_FFT, f) else: # Compute the R, G, B channels of the image image_channels = utils.get_channels(image_file) # Serialise the image channels channels_string = 'bgra' for i in range(len(image_channels)): pickle_name = image_name_components[0] + '_' + channels_string[i] + '.pickle' pickle_path = os.path.join(app.config['TEMP_DATA'], pickle_name) with open(pickle_path, 'wb') as f: pickle.dump(image_channels[i], f) # # Compute the padded image # image_h, image_w, channels = image_file.shape # padded_h, padded_w = 2 * image_h, 2 * image_w # padded_image = np.zeros((padded_h, padded_w, channels), np.uint8) # padded_image[0:image_h, 0:image_w] = image_file # # Compute the R, G, B channels of the padded image # padded_image_channels = utils.get_channels(padded_image) # # Compute the FFT of the padded image channels # padded_image_FFTs = [np.fft.fftshift(np.fft.fft2(channel)) for channel in padded_image_channels] # # Serialise the FFTs of the padded image channels # for i in range(len(padded_image_FFTs)): # pickle_name = image_name_components[0] + '_' + channels_string[i] + '_fft.pickle' # pickle_path = os.path.join(app.config['TEMP_DATA'], pickle_name) # with open(pickle_path, 'wb') as f: # pickle.dump(padded_image_FFTs[i], f) return make_response(jsonify('Server: Initialisations process completed successfully'), 200)
def delete(self, id): data = request.get_json() chem_composition = ChemicalComposition.query.filter_by( commodity_id=id).filter_by(element_id=data['element_id']).first() if chem_composition: chem_composition.delete_from_db() return {"message": "data deleted "} return {"message": "data not found"}, 400
def upadteTask(tsk): num = 1 todo = mongo.db.todo if not request.json: abort(404) content = request.get_json() todo.update({'userid':num,'taskid':tsk},{'$set':content}) return "Successfully Updated"
def delete(tsk): num = 1 todo = mongo.db.todo if not request.json: abort(404) content = request.get_json() todo.delete_one({'userid':num,'taskid':tsk}) return "Successfully Deleted"
def set_alerts(): """ Receive custom alerts Status codes: 400 invalid input 403 invalid server key """ ssn = g.db # Input validation data = request.get_json() assert isinstance(data, dict), 'Invalid data: should be JSON object' assert 'server' in data, 'Data: "server" key is missing' assert 'alerts' in data, 'Data: "alerts" key is missing' # Input validation: alerts assert isinstance(data['alerts'], list), 'Data: "alerts" should be a list' assert all( isinstance(s, dict) and 'message' in s and isinstance(s['message'], basestring) and ('service' not in s or isinstance(s['service'], basestring)) and set(s.keys()) <= {'title', 'message', 'service'} for s in data['alerts'] ), 'Data: "alerts" should be a list of objects with keys "title", "message"?, "service"?' # Identify server server = _identify_server(ssn, data['server']) ssn.add(server) # Alerts services_cache = {} for a in data['alerts']: # Identify service (if any) service = None if 'service' in a: try: service = services_cache[a['service']] except KeyError: service = _identify_service(ssn, server, a['service']) services_cache[service.name] = service ssn.add(service) # Raise alert = models.Alert( server=server, service=service, ctime=datetime.utcnow(), channel='api', event='alert', message=unicode(a['message']) ) ssn.add(alert) logger.debug(u'Alert reported for {server}:`{service}`: {message}'.format(server=server.name, service=service.name if service else '-', message=a['message'])) # Save ssn.commit() return {'ok': 1}
def change_state(node, st, key): rpc = request.get_json() st_instance = get_network().get_node(node).get_station(st) if key == 'switch': if rpc['switch'] == 'on': st_instance.turn_on() elif rpc['switch'] == 'off': st_instance.turn_off() return ('', 204)
def mc_api_name(): data = request.get_json() if data is None: return "Invalid request", 406 if len(data) >= 100: return "Too many uuids", 406 if not isinstance(data, list): return "Not a list", 406 return json.dumps(retrieve_names(data))
def add_movie2list(): data = request.get_json() temp = json.loads(str(data['listName'])) conn = mysql.connect() cur = conn.cursor() cur.callproc('addListPost', (data['title'], temp['name'], 'Movies' , data['description'], data['movieTitle'] )) conn.commit() conn.close() return jsonify({})
def pictograma(): if request.method == "POST": ids = inserir_pictograma(request.get_json(force=True)) return Response(response=json.dumps({'inseridos': ids}), status=200, mimetype="application/json") elif request.method == "GET": if len(request.args.getlist('topicos')) is 0: picto = buscar_pictogramas(None) else: lista = ast.literal_eval(str(request.args.getlist('topicos'))) picto = buscar_pictogramas(lista) response = Response(response=get_list_as_json(picto), status=200, mimetype="application/json") return response
def mc_api_uuid(): data = request.get_json() if data is None: return "Invalid request: {}".format(request.data), 406 if len(data) >= 100: return "Too many usernames", 406 if not isinstance(data, list): return "Not a list", 406 data = tuple(str(user) for user in data) try: return json.dumps(retrieve_uuids(data)) except MojangError as e: return e.message, 500
def update_node(): ''' Update the node text. ''' node = request.get_json() node_id = node.get('id') node_text = node.get('text') structure = Structure.query.filter_by(id=node_id).first() structure.title = node_text db.session.commit() return jsonify(status_text=gettext("Hoorah! Section was updated."))
def delete_node(): ''' Delete the node and associated section text. ''' nodes = request.get_json().get('ids') for node_id in nodes: section = Section.query.filter_by(structure_id=node_id).first() db.session.delete(section) structure = Structure.query.filter_by(id=node_id).first() db.session.delete(structure) db.session.commit() return jsonify(status_text=gettext("Hoorah! Section was deleted."))
def finaliza_jogo_e_mostra_metricas(): json_dic = request.get_json(force=True) assert json_dic is not None assert metricas.json_valido(json_dic) metricas.salvar_jogo(json_dic) partidas = metricas.pegar_metricas_ultimas_partidas() return_json = {"partidas": []} for i, partida in enumerate(partidas): respostas_corretas = 0 for resposta in partida["respostas"]: if resposta["acertou"]: respostas_corretas += 1 return_json["partidas"].append({"x": partidas.count() - i, "y": respostas_corretas}) return_json["topicos"] = metricas.pegar_metricas_ultimos_topicos() return Response(response=json_util.dumps(return_json))
def update_workspace(workspace, storage=None): fields = request.get_json(silent=True) or {} for k in request.form.keys(): fields[k] = request.form.get(k, type=str) if not 'code' in fields: file = request.files.get('code', None) if file: fields['code'] = file.read().decode("utf-8") if len(request.args) > 0: return bad_request('invalid update parameters') with workspaces.find_or_404(workspace) as w: if storage is None: w.update(**fields) else: s = w.storage[storage] with s as s: s.update(**fields) return {'status': 200, 'message': 'updated' }
def convert(): kwargs = request.get_json(force=True) input_tar = kwargs["input"] archive_name = kwargs["options"].get("filename", "hepdata-converter-ws-data") output_format = kwargs["options"].get("output_format", "") output, os_handle = StringIO.StringIO(), None if output_format.lower() in SINGLEFILE_FORMATS or "table" in kwargs["options"]: os_handle, tmp_output = tempfile.mkstemp() else: tmp_output = tempfile.mkdtemp() tmp_dir = tempfile.mkdtemp() try: conversion_input = os.path.abspath(tmp_dir) conversion_output = os.path.abspath(tmp_output) with tarfile.open(mode="r:gz", fileobj=StringIO.StringIO(base64.decodestring(input_tar))) as tar: tar.extractall(path=conversion_input) # one file - treat it as one file input format walked = list(os.walk(tmp_dir)) if len(walked) == 1 and len(walked[0][2]) == 1: path, dirs, files = walked[0] conversion_input = os.path.join(path, files[0]) else: conversion_input = conversion_input + "/" + archive_name + "/" hepdata_converter.convert(conversion_input, conversion_output, kwargs.get("options", {})) if not os.path.isdir(conversion_output): archive_name = archive_name + "." + output_format with tarfile.open(mode="w:gz", fileobj=output) as tar: tar.add(conversion_output, arcname=archive_name) finally: if os_handle: os.fdopen(os_handle).close() shutil.rmtree(tmp_dir, ignore_errors=True) shutil.rmtree(tmp_output, ignore_errors=True) return Response(output.getvalue(), mimetype="application/x-gzip")
def ping(): """ Test connection and server credentials Status codes: 400 invalid input 403 invalid server key """ ssn = g.db # Input validation data = request.get_json() assert isinstance(data, dict), 'Invalid data: should be JSON object' assert 'server' in data, 'Data: "server" key is missing' # Identify server (will raise exception if not fine) server = _identify_server(ssn, data['server']) ssn.add(server) ssn.commit() return {'pong': 1}
def add_node(project_id): ''' Add a new node to the tree and pass the created data back to the caller so it can add it to the tree in the browser. ''' nodes = request.get_json() parent_id = nodes.get('parent') project = Project.query.filter(id==project_id).first() parent = Structure.query.filter(id==parent_id).first() # Get the highest display order for this project so we can assign the new node to last place. displayorder = db.session.query(db.func.max(Structure.displayorder)).filter(Project.id==project_id).scalar() + 1 structure = create_node(project=project, parent=parent, displayorder=displayorder) db.session.commit() return jsonify(id=structure.id, text=structure.title, displayorder=structure.displayorder, status_text=gettext("Hoorah! Section was added."))
def negotiation(): errors = [] if session.get('nid', None) is None: # Generates a new negotiation if needed is_new_nego = True session['nid'] = str(uuid.uuid4()) nego = Negotiation(session['nid'], ROLE_BUYER, TESTNET) nego_db_service.create_nego(session['nid'], nego) else: # Gets the negotiation is_new_nego = False nego = nego_db_service.get_nego_by_id(session['nid']) ''' Prepares the BargainingMessage to be sent (if there's one) ''' if is_new_nego: # CASE 1: We start a new negotiation # Builds a REQUEST message new_msg, errors = negotiator.process(nego) elif request.method == 'POST': # Case 2: We continue an existing negotiation # Gets data sent by the user container = request.get_json(False, True, False) if request.mimetype == "application/json" else request.form amount = int(Decimal(container['amount']) * SATOSHIS_TO_BITCOIN) memo = container['memo'] # Builds a new message (PROPOSAL or CANCEL) # For this demo, we never send fees (test network) new_msg, errors = negotiator.process(nego, memo, amount) else: new_msg = None errors.append('Invalid HTTP method') ''' Sends the BargainingMessage ''' if len(errors) == 0: # Appends the new message to the chain nego.append(new_msg) nego_db_service.update_nego(session['nid'], nego) # Sends the message next_msg_types = nego.get_next_msg_types() uri = SELLER_URI if (new_msg.msg_type == TYPE_BARGAIN_REQUEST) else nego.get_bargain_uri_for_role(ROLE_BUYER) response = send_msg(new_msg, uri, next_msg_types) ''' Processes the response ''' try: if response.code == 200: if check_req_format(response): pbuff = response.read() msg = BargainingMessage.deserialize(pbuff) if not nego.already_received(msg): if msg.check_msg_fmt(NETWORK): nego.check_consistency(msg) nego.append(msg) nego_db_service.update_nego(session['nid'], nego) else: errors.append('Remote node returned an error') except: errors.append('A problem occurred while processing the message sent by the remote node') ''' Prepares rendering ''' params_tpl = {} params_tpl['errors'] = '' if len(errors) == 0 else '\n'.join(errors) params_tpl['wallet_blc'] = get_balance([negotiator.addr1]) params_tpl['chain'] = nego._msgchain params_tpl['completed'] = True if nego.status in {NEGO_STATUS_CANCELLED, NEGO_STATUS_COMPLETED} else False return render_template('negotiation.html', params_tpl=params_tpl)
def set_service_status(): """ Receive single service status Status codes: 400 invalid input 403 invalid server key """ ssn = g.db # Input validation data = request.get_json() assert isinstance(data, dict), 'Invalid data: should be JSON object' assert 'server' in data, 'Data: "server" key is missing' assert 'period' in data, 'Data: "period" key is missing' assert 'services' in data, 'Data: "services" key is missing' # Input validation: period try: data['period'] = int(data['period']) except ValueError: raise AssertionError('Data: "period" should be an integer') # Input validation: services assert isinstance(data['services'], list), 'Data: "services" should be a list' assert all( isinstance(s, dict) and 'name' in s and isinstance(s['name'], basestring) and 'state' in s and isinstance(s['state'], basestring) and ('info' not in s or isinstance(s['info'], basestring)) for s in data['services'] ), 'Data: "services" should be a list of objects with keys "name", "state", "info"?, "period"?' # Identify server server = _identify_server(ssn, data['server']) ssn.add(server) # Services services_cache = {} for s in data['services']: # Identify service try: service = services_cache[s['name']] except KeyError: service = _identify_service(ssn, server, s['name']) services_cache[service.name] = service ssn.add(service) # Update period try: service_period = int(s['period']) except (KeyError, ValueError): service_period = data['period'] service.period = service_period # State if not models.state_t.is_valid(s['state']): s['info'] += u' (sent unsupported state: "{}")'.format(s['state']) s['state'] = 'UNK' state = models.ServiceState( service=service, rtime=datetime.utcnow(), state=s['state'], info=s['info'] ) ssn.add(state) logger.debug(u'Service {server}:`{name}` state update: {state}: {info}'.format(server=server.name, **s)) # Save ssn.commit() return {'ok': 1}
def callback(): ''' This function validates the response sent by the client about the challenge This is the route called by the bitcoin wallet when the challenge has been signed ''' # Retrieves the callback uri callback_uri = get_callback_uri() # Extracts data from the posted request (from form of from json data according to the method used by the client) container = request.get_json(False, True, False) if request.mimetype == "application/json" else request.form bitid_uri = container["uri"] signature = container["signature"] address = container["address"] # # Let's start by a bunch of validations # # Checks the address if not bitid.address_valid(address, USE_TESTNET): return jsonify(message = "Address is invalid or not legal"), 401 # Checks the bitid uri if not bitid.uri_valid(bitid_uri, callback_uri): return jsonify(message = "BitID URI is invalid or not legal"), 401 # Checks the signature if not bitid.signature_valid(address, signature, bitid_uri, callback_uri, USE_TESTNET): return jsonify(message = "Signature is incorrect"), 401 # Note that the previous 3 steps could also be done in 1 step with following code: # if not bitid.challenge_valid(address, signature, bitid_uri, callback_uri, USE_TESTNET): # return jsonify(message = "Sorry but something does not match"), 401 # Checks the nonce nid = bitid.extract_nonce(bitid_uri) # Tries to retrieve the nonce from db nonce = nonce_db_service.get_nonce_by_nid(nid) if nonce is None: return jsonify(message = "NONCE is illegal"), 401 elif nonce.has_expired(): nonce_db_service.delete_nonce(nonce) return jsonify(message = "NONCE has expired"), 401 # # So good so far, everything seems ok # It's time to check if we have a sign out or a sign in # # Checks if a user with the given address has already been registered in db (sign in) user = user_db_service.get_user_by_address(address) # If we have a sign out if user is None: # Here, we have an important check to do in order to avoid flooding of the users db # Let's check for a proof of goodwill (@see pybitid_demo.services.fake_tx_db_service) if not tx_db_service.check_proof_of_goodwill(address): return jsonify(message = "Address is invalid or not legal"), 401 else: # Creates a new user and stores it in db user = User(address) if not user_db_service.create_user(user): return jsonify(message = "Ooops ! Something went wrong but we work on it"), 500 # To finalize the authentication, let's set the user id in the nonce and update it in db nonce.uid = user.uid if not nonce_db_service.update_nonce(nonce): return jsonify(message = "Ooops ! Something went wrong but we work on it"), 500 # Everything was ok: user is authenticated return jsonify(address = address, nonce = nonce.sid)