def create_book(): book = Book.query.filter_by(title=request.form.get('title')) if book: return jsonify({'data': 'Error, already exists'}) book = Book(request.form) keywords = request.form.get('keywords') if keywords: for keyword in keywords.split(','): k = Keyword.query.filter_by(keyword=keyword) if not k: k = Keyword(keyword.strip()) book.keywords.append(k) authors = request.form.get('authors') if authors: for author in authors.split(','): a = Author.query.filter_by(name=author) if not a: a = Author(author.strip()) book.authors.append(a) curriculum = request.form.get('curriculum') if curriculum: for curricula in curriculum.split(','): c = Curricula.query.filter_by(link=curricula) if not c: c = Curricula(curricula.strip()) book.curriculum.append(c) try: db.session.add(book) db.session.commit() return jsonify({'data': 'Success'}) except Exception as e: return jsonify({'data': 'Error'})
def article(article_id): article = Article.query.filter_by(id=article_id).first() if article: return jsonify({'data': article.to_dict()}) else: return jsonify({'data': None })
def get_config(): cfg = request.args.get('cfg') if request.method == 'POST': if allowadmin == "true": cfgtext = request.form.get('cfgtxt') open(cfg, 'w').write(cfgtext) return redirect("/?msg=Config+file+has+been+updated") else: sec = request.args.get('sec') if (not os.path.isfile(cfg) ): # copy default config if it doesn't exist shutil.copy2('{}/template.ini'.format(os.path.dirname(cfg)), cfg) if sec is None: action = request.args.get('action') if action == "getmtime": return jsonify({'mtime': os.path.getmtime(cfg)}) else: cfgtext = open(cfg, 'r').read() form = open( 'static/html-snippets/form-config.html').read().format( cfg, cfgtext) return form else: config = ConfigParser.ConfigParser() config.read(cfg) if sec == "all": return jsonify(config.sections()) else: dict = {} for opt in config.options(sec): dict[opt] = config.get(sec, opt) return jsonify(dict)
def curricula_books(curricula_id): curricula = Curricula.query.filter_by(id=curricula_id).first() books = [book.to_dict() for book in curricula.books] if books: return jsonify({'data': books}) else: return jsonify({'data': None })
def subtract(): try: first_number = int(request.args.get('a')) second_number = int(request.args.get('b')) return jsonify({'result': first_number - second_number}) except Exception as e: return jsonify({'result': "There was an error" + str(e)})
def score_revisions(context, model): # Check to see if we have the context available in our score_processor if context not in score_processor: return responses.not_found( "No models available for {0}".format(context)) if model not in score_processor[context]: return responses.bad_request( "Model '{0}' not available for {1}.".format(model, context)) # Try to read the rev_ids if 'revids' in request.args: try: rev_ids = set(read_bar_split_param(request, "revids", type=int)) except ParamError as e: return responses.bad_request(str(e)) if len(rev_ids) == 0: return responses.bad_request("No revids provided.") else: return jsonify( score_processor[context][model].format_info(format="json")) precache = "precache" in request.args try: model_scores, _ = score_processor.score(context, model, rev_ids, precache=precache) except errors.ScoreProcessorOverloaded: return responses.server_overloaded() return jsonify(model_scores)
def post(self): global counter #image = request.json["image"] #recibir la imagen y guardarla en un directorio en local #image_path = image_path #image = recognition.predict_with_url(image) #print(image) #print(prediction["probabilities"]) #sorted_predictions = [prediction] #sorted_predictions = sorted(sorted_predictions, key=lambda k: k['probability'], reverse=True) image = request.files["picture"] image_path = "images/" + str(counter) + ".jpg" image.save(image_path) prediction = recognition.predict_with_url( utilities.get_image_url(image_path)).text prediction = loads(prediction) label = prediction["probabilities"][0]["label"] prob = prediction["probabilities"][0]["probability"] print(label, prob) d = utilities.jsonToDict("data_new.json") counter += 1 try: return jsonify({ "label": label, "probability": prob, "other_data": d[label] }) except: return jsonify({ "label": label, "probability": prob, "other_data": {} })
def changeLightState(command): """ Changes the state of the lights. (off/on) """ command = command.lower() lights = bridge.get_light_objects() if command == 'on': # Loop through and turn all lights off for light in lights: light.on = True db.insert("state", command) logger.info("Set 'light state' to %s", command) return jsonify({"Status": "Ok"}) elif command == 'off': for light in lights: light.on = False db.insert("state", command) logger.info("Set 'light state' to %s", command) return jsonify({ "Status": "Ok" }) else: logger.error( " Invalid command (command=%s)", command ) abort(500)
def getAllCategory(): items = Category.query.all() if items: return jsonify(categories=[item.serialize() for item in items]) return jsonify(error="No Category")
def create_news(): data = { 'news_title' : request.args.get('news_title', ''), 'news_content' : request.args.get('news_content', ''), 'topic_id' : request.args.get('topics'), 'status_id' : request.args.get('news_status_id') } sql = "INSERT INTO news(title, content, active, status_id) VALUES('" + data['news_title'] + "', '" + data['news_content'] + "', 1, " + str(data['status_id']) + ");" try: query = conn.execute(sql) # conn.commit() sql = "SELECT MAX(id) FROM news" query = conn.execute(sql) last_id_news = max(row[0] for row in query.cursor.fetchall()) topic_id_list = data['topic_id'].split('_') for topic_id in topic_id_list: sql = "INSERT INTO mapping_topics_news(topic_id, news_id) VALUES(" + str(topic_id) + ", " + str(last_id_news) + ");" query = conn.execute(sql) return jsonify({'success':True}) except: return jsonify({'success':False})
def route_place(id): place = get_place(ObjectId(id)) if not place: return json_error(404, 'Place with id %s not found.' % id) if request.method == 'GET': return jsonify(place=place) if request.method == 'PUT': # TODO: Tim, should places also be associated with the person who created them (so that he/she can delete them as well?) put_place(ObjectId(id), request.form['floor'], request.form['name'], request.form.get('alias', '')) return jsonify(place=get_place(ObjectId(id))), 200 #TODO: #if request.method == 'PATCH': # patch = JsonPatch(request.json) # obj = patch.apply(get_place(ObjectId(id))) # put_place(ObjectId(id), obj['name'], obj['floor'], obj.get('alias', '')) # return jsonify(place=get_place(ObjectId(id))) if request.method == "DELETE": if get_current_username() in get_admin_users(): # TODO: Tim, should places also be associated with the person who created them (so that he/she can delete them as well?) delete_place(ObjectId(id)) return '', 204
def get(self, question_id): result = '' today = datetime.date.today() filelogname = 'file_' + str(today) + '.log' logging.basicConfig(filename=filelogname, level=logging.DEBUG, format='%(asctime)s %(message)s') logging.debug('Init') #encoded data_string = json.dumps(result) #Decoded decoded = json.loads(data_string) if question_id.isdigit(): question = 'Q' question += question_id try: with open('data.json', 'r') as f: data = json.load(f) try: question_data = data[question] logging.debug('Response for params: ' + question_id) return make_response(jsonify(question_data), 200) except Exception as ex: print("Not found. Param error") return make_response(jsonify(), 500) except Exception as e: #message to log logging.debug(str(e) + question_id) #return error return make_response(jsonify(e), 500) else: return abort(400)
def get_test_runs_for_test(test_id): test_id = parse.unquote(test_id) start_date = _parse_datetimes(flask.request.args.get('start_date', None)) stop_date = _parse_datetimes(flask.request.args.get('stop_date', None)) datetime_resolution = flask.request.args.get('datetime_resolution', 'min') if datetime_resolution not in ['sec', 'min', 'hour', 'day']: message = ('Datetime resolution: %s, is not a valid' ' choice' % datetime_resolution) status_code = 400 return abort(make_response(message, status_code)) with session_scope() as session: db_test_runs = api.get_test_runs_by_test_test_id(test_id, session=session, start_date=start_date, stop_date=stop_date) if not db_test_runs: # NOTE(mtreinish) if no data is returned from the DB just return an # empty set response, the test_run_aggregator function assumes data # is present. return jsonify({'numeric': {}, 'data': {}}) test_runs =\ test_run_aggregator.convert_test_runs_list_to_time_series_dict( db_test_runs, datetime_resolution) return jsonify(test_runs)
def score_revisions(context, model): # Check to see if we have the context available in our score_processor if context not in score_processor: return responses.not_found("No models available for {0}" .format(context)) if model not in score_processor[context]: return responses.bad_request("Model '{0}' not available for {1}." .format(model, context)) # Try to read the rev_ids if 'revids' in request.args: try: rev_ids = set(read_bar_split_param(request, "revids", type=int)) except ParamError as e: return responses.bad_request(str(e)) if len(rev_ids) == 0: return responses.bad_request("No revids provided.") else: return jsonify(score_processor[context][model].format_info(format="json")) precache = "precache" in request.args try: model_scores, _ = score_processor.score(context, model, rev_ids, precache=precache) except errors.ScoreProcessorOverloaded: return responses.server_overloaded() return jsonify(model_scores)
def globalSearch(term): if not (term): return jsonify(result="No results") else: print('searching for ' + term) listLevel1 = [] items = Pin.query.filter( or_(Pin.title.like("%" + term + "%"), Pin.description.like("%" + term + "%"))) if items: listLevel1.append(items) #return jsonify(Pins=[item.serialize() for item in items]) listLevel2 = [] itemsC = Category.query.filter( or_(Category.nom.like("%" + term + "%"), Category.description.like("%" + term + "%"))) if items: for i in itemsC: filter = "%," + str(i.id) + ",%" items2 = Pin.query.filter(Pin.categories.like(filter)) listLevel2.append(items2) listLevel1.extend(listLevel2) return jsonify(Pins=[[item.serialize() for item in items] for items in listLevel1])
def add_to_cart(): from datetime import datetime date_create_order = datetime.now() time_order = '00:00' order = Order.query.filter_by(user_id=current_user.id, status='pending').first() if not order: order = Order(user_id=current_user.id, status='pending', created_at=date_create_order, address='www', time=time_order) order.new_order(order) id = request.form['food_id'] food = Food.query.get(id) if food: #logic- add dish to cart food_order = FoodOrder(order_id=order.id, food_id=food.id, count=1, price=food.price) food_order.new_food_order(food_order) return jsonify(food.name) else: requestJson = jsonify("Ошибка! Блюдо не найдено") requestJson.status_code = 401 return requestJson
def route_user(username): if request.method == 'PUT': if not is_authorized_for(username): return json_error(401, "Only %s and admins can add a new user with the username %s. You are %s." % (username, username, get_current_username())) alias = request.form.get('alias', '') email = request.form.get('email', '') put_user(username, email, alias) return jsonify(user=get_user(username)) user = get_user(username) if not user: return json_error(404, 'User with name %s not found.' % username) if request.method == 'GET': return jsonify(user=user) #if request.method == 'PATCH': # patch = JsonPatch(request.json) # obj = patch.apply(get_user(username)) # put_user(obj['username'], obj.get('alias', '')) # return jsonify(user=get_user(obj['username'])) if request.method == "DELETE": # XXX: There may be a more efficient way to do this existing_user = get_user(username) if existing_user and not is_authorized_for(username): return json_error(401, "Only %s and admins can delete a user with the username %s. You are %s." % (username, username, get_current_username())) delete_user(username) return '', 204
def score_revisions(context, model): # Check to see if we have the context available in our score_processor if context not in scoring_system: return responses.not_found("No models available for {0}" .format(context)) if model not in scoring_system[context]: return responses.bad_request("Model '{0}' not available for {1}." .format(model, context)) # Try to read the rev_ids if 'revids' in request.args: try: rev_ids = set(read_bar_split_param(request, "revids", type=int)) except ParamError as e: return responses.bad_request(str(e)) if len(rev_ids) == 0: return responses.bad_request("No revids provided.") else: return jsonify(scoring_system.format_model_info( context, [model], include_model_info="all")[model]) precache = "precache" in request.args try: score_doc = scoring_system.score(context, [model], rev_ids, precache=precache) return jsonify(convert_score_doc(score_doc)[model]) except errors.ScoreProcessorOverloaded: return responses.server_overloaded() except Exception: return responses.unknown_error(traceback.format_exc())
def route_positions(): if request.method == 'GET': critkeys = ['username', 'bind'] crit = {key: request.args[key] for key in list(set(critkeys) & set(request.args.keys()))} return jsonify(positions=get_positions('history' in request.args, 'extended' in request.args, **crit)) if request.method == 'POST': # The only reason you would want to set username explicitly is if you are an admin and want to post as a user username = None if not 'username' in request.form: username = get_current_username() else: username = request.form['username'] bindid = request.form['bind'] bind = get_bind(ObjectId(bindid)) # XXX: There may be a more efficient way to do this existing_user = get_user(bind['username']) if existing_user and not is_authorized_for(username): return json_error(401, "Only %s and admins can add %s at a position! You are %s." % (username, username, get_current_username())) if not get_user(username): return json_error(400, 'User with name %s does not exist.' % username) if not bind: return json_error(400, 'Bind with id %s does not exist.' % bind) id = post_position(username, ObjectId(bindid)) return jsonify(position=get_position(id)), 201
def edit(qnumber): result = '' if qnumber.isdigit(): data_string = json.dumps(result) #Decoded decoded = json.loads(data_string) question = 'Q' question += qnumber print("--------------------------------------------") print("question " + question) print("--------------------------------------------") try: with open('data/data.json', 'r') as f: data = json.load(f) try: question_data = data[question] print("Responding json") return make_response(jsonify(question_data), 200) except Exception as ex: print("Not found. Param error") return make_response(jsonify(), 500) except Exception as e: return make_response(jsonify(e), 500) else: return abort(400)
def score_revisions(wiki): try: scorer = scorer_map[wiki] except KeyError: return responses.not_found("No scorers available for {0}" \ .format(wiki)) if "models" not in request.args: # Return the models that we have return jsonify({"models": list(scorer_map[wiki].model_map.keys())}) else: try: model_names = read_bar_split_param(request, "models", str) rev_ids = read_bar_split_param(request, "revids", int) except ParamError as e: return responses.bad_request(str(e)) scores = {} for rev_id in rev_ids: try: score = scorer.score(rev_id, models=model_names) except Exception as e: score = {"error": {'type': str(type(e)), 'message': str(e), 'traceback': traceback.format_exc()}} scores[rev_id] = score return jsonify(scores)
def book_curriculm(book_id): book = Book.query.filter_by(id=book_id).first() curriculum = [curricula.to_dict() for curricula in book.curriculum] if curriculum: return jsonify({'data': curriculum}) else: return jsonify({'data': None })
def book_authors(book_id): book = Book.query.filter_by(id=book_id).first() authors = [authors.to_dict() for authors in book.authors] if authors: return jsonify({'data': authors}) else: return jsonify({'data': None })
def keywords(): keywords = Keyword.query.all() keywords = [keyword.to_dict() for keyword in keywords if keyword.keyword] if keywords: return jsonify({'data': keywords}) else: return jsonify({'data': None })
def book_keyword(book_id): book = Book.query.filter_by(id=book_id).first() keywords = [keyword.to_dict() for keyword in book.keywords] if keywords: return jsonify({'data': keywords}) else: return jsonify({'data': None })
def articles(): articles = Article.query.all() articles = [article.to_dict() for article in articles] if articles: return jsonify({'data': articles}) else: return jsonify({'data': None })
def keyword_book(keyword_id): keyword = Keyword.query.filter_by(id=keyword_id).first() books = [book.to_dict() for book in keyword.books] if books: return jsonify({'data': books}) else: return jsonify({'data': None })
def getAllPin(): print "getAllPin" items = Pin.query.all() if items : print "pin non vide" return jsonify(Pins=[item.serialize() for item in items]) print "pin vide" return jsonify(error="No pin")
def put_word(word): word_object = Word(_word=word) WordService.initialize_word(word_object) if not word_object.initialized(): return jsonify({"word": None, "comment": "word not found"}) save_word_if_not_exists(word_object) resp = jsonify(**word_object.to_dict()) resp.headers['Access-Control-Allow-Origin'] = '*' return resp
def plan(): current_dir = os.path.dirname(__file__) file_path = os.path.join(current_dir, '..', JSON_FILE) try: with open(file_path) as file: json_file = json.load(file) return jsonify(json_file) except (IOError, ValueError) as e: return jsonify('Error: no optimal plan was found')
def deleteCategory(form): if (form['id']): item = Category.query.get(id) if item: db.session.delete(Category.query.get(id)) db.session.commit() return jsonify(deleted="1") return jsonify(deleted="0") return jsonify(deleted="No id")
def make_json_error(ex): if hasattr(ex, "information"): response = jsonp.jsonify(message=str(ex), information=ex.information) else: response = jsonp.jsonify(message=str(ex)) response.status_code = (ex.code if isinstance(ex, http.HTTPException) else 500) return response
def get_sshpub(): try: if pubkey is not None: n = '%x' % pubkey.n e = '%x' % pubkey.e return jsonify({'status': 'ok', 'n': n, 'e': e, 'result': True}) else: return jsonify({'status': 'error'}) except: return jsonify({'status': 'error'})
def deletePin(form): if (form['id']): item = Pin.query.get(id) if item: db.session.delete(Pin.query.get(id)) db.session.commit() return jsonify(deleted = "1") return jsonify(deleted = "0") return jsonify(deleted = "No id")
def getAllUser(): print "getAllUser" items = User.query.all() if items : print "users non vide" return jsonify(users=[item.serialize() for item in items]) print "user vide" return jsonify(error="No user")
def getPinById(idPin): print idPin if idPin: item = Pin.query.get(int(idPin)) if item: return jsonify(pin = [item.serialize()]) return jsonify(error="No pin") return jsonify(error="No idPin")
def delete_book(book_id): book = Book.query.filter_by(id=book_id).first() if book: try: db.session.delete(book) db.session.commit() return jsonify({'data': 'Success'}) except Exception as e: return jsonify({'data': 'Error'}) else: return jsonify({'data': None })
def getUserById(idUser): print "getUserById" if idUser: item = User.query.get(idUser).first() if item: return jsonify(categories=[item.serialize()]) return jsonify(error="No user") return jsonify(error = "No idUser")
def score_model_revisions(context): # Check to see if we have the context available in our score_processor if context not in score_processor: return responses.not_found( "No scorers available for {0}".format(context)) # If no model is specified, return information on available models if "models" not in request.args: # Return the models that we have models = { name: model.format_info(format="json") for name, model in score_processor[context].items() } return jsonify({"models": models}) # Read the params try: models = set(read_bar_split_param(request, "models", type=str)) except ParamError as e: return responses.bad_request(str(e)) # Check if all the models are available missing_models = models - score_processor[context].keys() if len(missing_models) > 0: return responses.bad_request( "Models '{0}' not available for {1}.".format( list(missing_models), context)) # Read the rev_ids try: rev_ids = set(read_bar_split_param(request, "revids", type=int)) except ParamError as e: return responses.bad_request(str(e)) if len(rev_ids) == 0: return responses.bad_request("No revids provided.") precache = "precache" in request.args # Generate scores for each model and merge them together try: scores = defaultdict(dict) for model in models: model_scores, _ = score_processor.score(context, model, rev_ids, precache=precache) for rev_id in model_scores: scores[rev_id][model] = model_scores[rev_id] except errors.ScoreProcessorOverloaded: return responses.server_overloaded() return jsonify(scores)
def getCategoryById(idCategory): print "getCategoryById" if idCategory: item = Category.query.get(idCategory).first() if item: return jsonify(categories=[item.serialize()]) return jsonify(error="No category") return jsonify(error="No idCategory")
def edit_book(book_id): book = db.session.query(Book).filter_by(id=book_id) if book: print request.form try: book.update(request.form) db.session.commit() return jsonify({'data': 'Success'}) except Exception as e: return jsonify({'data': 'Error'}) else: return jsonify({'data': None })
def get(self, led_set_name): if led_set_name is None: led_sets = [] for led_set in self.coordinator.get_led_sets(): led_sets.append(add_led_set_uri(led_set)) return jsonify( {'led_set' : led_sets} ) else: try: led_set = self.coordinator.get_led_set(led_set_name) return jsonify( add_led_set_uri(led_set) ) except HttpError as e: abort(e.error_code)
def route_places(): if request.method == 'GET': critkeys = ['alias', 'floor', 'name', 'alias'] crit = {key: request.args[key] for key in list(set(critkeys) & set(request.args.keys()))} return jsonify(places=get_places(**crit)) if request.method == 'POST': floor = request.form['floor'] name = request.form['name'] alias = request.form.get('alias', '') id = post_place(floor, name, alias) return jsonify(place=get_place(id)), 201
def create_badge(): try: badge = Badge(request.form['name'], request.form['description'], request.form['image_name']) db.session.add(badge) db.session.commit() except: return jsonify({ 'success': False, 'message': 'Something went wrong :(' }) return jsonify({'success': True, 'message': 'Badge added successfully'})
def get(self, controller_address): if controller_address is None: controllers = [] for controller in self.coordinator.get_controllers(): controllers.append(add_controller_uri(controller)) return jsonify( {'controller': controllers} ) else: try: controller = self.coordinator.get_controller(controller_address) return jsonify(add_controller_uri(controller)) except HttpError as e: abort(e.error_code)
def search_events(search_string): db = meteor_app.get_db() try: search = mp.ObservationSearch.from_dict( safe_load(unquote(search_string))) except ValueError: return jsonify({'error': str(sys.exc_info()[1])}) observations = db.search_observations(search) db.close_db() return jsonify({ 'obs': list(x.as_dict() for x in observations['obs']), 'count': observations['count'] })
def search_files(search_string): db = meteor_app.get_db() try: search = mp.FileRecordSearch.from_dict( safe_load(unquote(search_string))) except ValueError: return jsonify({'error': str(sys.exc_info()[1])}) files = db.search_files(search) db.close_db() return jsonify({ 'files': list(x.as_dict() for x in files['files']), 'count': files['count'] })
def getCategoryByIdPin(idPin): print "getCategoryByIdPin" #id de la pin if idPin: pin = Pin.query.get(idPin) if pin: items = pin.categories return jsonify(categories=[item.serialize() for item in items]) else: return jsonify(errors="No pin") return jsonify(errors="No idPin")
def delete_news(news_id): sql = "DELETE FROM news WHERE id = " + str(news_id) try: conn.execute(sql) # conn.commit() sql = "DELETE FROM mapping_topics_news WHERE news_id = " + str(news_id) conn.execute(sql) # conn.commit() return jsonify({'success':True}) except: return jsonify({'success':False})
def create_instance(): try: insance = Instance(request.form['name'], request.form['description']) db.session.add(insance) db.session.commit() except: return jsonify({ 'success': False, 'message': 'Something went wrong :(' }) return jsonify({ 'success': True, 'message': 'New instance created successfully' })
def get_demo(): if 'server_id' not in request.args: die_with_error("Need server_id") if 'showdown_id' not in request.args: die_with_error("Need showdown_id") server_id = request.args.get('server_id') showdown_id = request.args.get('showdown_id') demo_url = gen_demo_url(server_id, showdown_id) if not demo_url: return jsonify(success=False) return jsonify(success=True, demo_url=demo_url)
def get_obstory_status_by_time(obstory_id, unix_time=None): db = meteor_app.get_db() if unix_time is None: unix_time = time.time() status = {} try: obstory_info = db.get_obstory_from_id(obstory_id) if obstory_info: obstory_name = obstory_info['name'] status = db.get_obstory_status(obstory_name=obstory_name, time=float(unix_time)) except ValueError: return jsonify({'error': 'No such observatory "%s".' % obstory_id}) db.close_db() return jsonify({'status': status})
def get(): """Método de busca de países """ initial_date = request.args.get('initial') final_date = request.args.get('final') country = request.args.get('country') try: return jsonify( scrap.get_data(year_start=int(initial_date), year_end=int(final_date), country=country)) except: return jsonify('Insira todos os campos')
def search(asset_name): search_result = mobile_client_handle.search(asset_name, max_results=50) song_hits = search_result['song_hits'] search_result_array = [] for item in song_hits: search_result_array.append({'title':item['track']['title'], 'storeId':item['track']['storeId'], 'album':item['track']['album'], 'artist':item['track']['artist']}) return jsonify(search_result_array)