def add_problem(problem): """ Creates a new problem and returns a problemID with default version 0 :param problem: Problem object that needs to be updated. :type problem: dict | bytes :rtype: int """ try: str_body = str(problem.decode("utf-8")).replace('\'', '\"') json.loads(str_body) db_size = db.posts.count() + 1 print(str_body) problem = Body.from_dict(connexion.request.get_json()) for i in range(1, db_size): if (db.posts.find_one({"problem_id": str(i)}) == None): insert_json(i, 0, problem) return jsonify({"problem_id": i}) print(i) insert_json(db_size, 0, problem) #print("out of func") return jsonify({"problem_id": db_size}) except ValueError: print("error") return get_status( 500, "Invalid JSON"), status.HTTP_500_INTERNAL_SERVER_ERROR
def post_auth_login(body=None): """ Although OpenAPI explicitly supports JWT - we don't enforce this - simply use it as a quick way to mock the behaviour of a more advanced system :param userid: :param password: :return: """ from flask import make_response, redirect if connexion.request.is_json: body = Body.from_dict(connexion.request.get_json()) # noqa: E501 if not body.userid: raise Unauthorized("Userid must be provided") timestamp = _current_timestamp() payload = { "iss": __JWT_ISSUER, "iat": int(timestamp), "exp": int(timestamp + __JWT_LIFETIME_SECONDS), "sub": str(body.userid), } token = jwt.encode(payload, __JWT_SECRET, algorithm=__JWT_ALGORITHM) response = make_response(redirect('/api/auth/status')) response.set_cookie('FCSESSIONID', token) return response
def add_article(body): # noqa: E501 """Создать новую статью # noqa: E501 :param body: Нужно отправить текст статьи и логин пользователя который её написал :type body: dict | bytes :rtype: None """ if connexion.request.is_json: body = Body.from_dict(connexion.request.get_json()) # noqa: E501 conn = sqlite3.connect(config.database) conn.row_factory = dict_factory cursor = conn.cursor() # получаем данные для модели ордера author = body.author text = body.text # регистрируем ордер в базе данных cursor.execute(f"""INSERT INTO article('text','user_id') VALUES ('{text}', '{author}') """) cursor.execute( f"""SELECT * FROM article WHERE id = (SELECT MAX(id) FROM article) """) article = cursor.fetchone() conn.commit() # сохраняем изменения return article
def filters(body): # noqa: E501 """urlから判断する # noqa: E501 :param body: :type body: dict | bytes :rtype: InlineResponse200 """ if connexion.request.is_json: body = Body.from_dict(connexion.request.get_json()) # noqa: E501 texts: List[str] = [] cached_rslt: List[Tuple[int, float]] = [] calc_urls: List[str] = [] for i, url in enumerate(body.urls): if rslt := redis.get(url): # type: ignore cached_rslt.append((i, float(rslt.decode()))) continue calc_urls.append(url) try: text = oneURL2text.oneURL2text(url) texts.append(text) except Exception as e: with open(f"{__main__.DATA_PATH}/error.csv", mode="a") as f: f.writelines([str(e), ", ", url, "\n"]) raise e
def add_product(body=None): """ Add a new product to the store :param body: :type body: dict | bytes :rtype: Product """ if connexion.request.is_json: body = Body.from_dict(connexion.request.get_json()) return 'do some magic!'
def update_pet(body): """ Update an existing pet :param body: Pet object that needs to be added to the store :type body: dict | bytes :rtype: None """ if connexion.request.is_json: body = Body.from_dict(connexion.request.get_json()) return 'do some magic!'
def update_problem(problem_id, version, problem): """ Update the existing problem :param problem_id: The id of the problem being manipulated :type problem_id: int :param version: The version of the problem being manipulated :type version: int :param problem: Problem object that needs to be updated. :type problem: dict | bytes :rtype: int """ #this checks if incoming data is valid json and for valid uid try: print("before check") str_body = str(problem.decode("utf-8")).replace('\'', '\"') print("after str") print(str_body) json.loads(str_body) #update the version print("after check") new_version = version + 1 problem = Body.from_dict(connexion.request.get_json()) print("after body") ret_object = db.posts.find_one({"problem_id": str(problem_id)}) print("after ret_obj") if ret_object is None: print("1") return get_status(404, "COULD NOT FIND"), status.HTTP_404_NOT_FOUND elif ret_object['version'] != version: print("2") return jsonify({"version": ret_object['version'] }), status.HTTP_412_PRECONDITION_FAILED else: print("3") db.posts.find_one_and_update( { "problem_id": str(problem_id), "version": version }, {"$set": { "body": problem, "version": new_version }}) print("after if") #need to write better messages to return for a success return jsonify({"version": new_version}) except ValueError: print("error") return get_status( 500, "Invalid JSON"), status.HTTP_500_INTERNAL_SERVER_ERROR
def post_sm_contexts(body): # noqa: E501 """Create SM Context # noqa: E501 :param body: representation of the SM context to be created in the SMF :type body: dict | bytes :rtype: SmContextCreatedData """ if connexion.request.is_json: body = Body.from_dict(connexion.request.get_json()) # noqa: E501 return 'do some magic!'
def reactions_post(body=None): # noqa: E501 """Réagir avec une emoji à un message # noqa: E501 :param body: :type body: dict | bytes :rtype: None """ if connexion.request.is_json: body = Body.from_dict(connexion.request.get_json()) # noqa: E501 return 'do some magic!'
def post_auth_login(body=None): # noqa: E501 """Submit authentication details TODO: # noqa: E501 :param body: :type body: dict | bytes :rtype: None """ if connexion.request.is_json: body = Body.from_dict(connexion.request.get_json()) # noqa: E501 return 'do some magic!'
def search_post(body): # verify correct schema (swagger) and get user parameters if connexion.request.is_json: body = Body.from_dict(connexion.request.get_json()) all_search_results = [] # All Search if body['data_location'] == "All": # Limfac is ISI with keyword search only... param_errors = isi.isi_search_validate(body) if param_errors != []: return f'{param_errors}', 405, {'x-error': 'method not allowed'} else: #NYU API hit nyu_search_url = f'https://{nyu_user}:{nyu_pwd}@wm.auctus.vida-nyu.org/api/v1/search' nyu_search_results = nyu.nyu_search(body, nyu_search_url) #ISI API hit isi_search_url = f'https://{isi_user}:{isi_pwd}@dsbox02.isi.edu:8888/datamart-api-wm/metadata/variables?' isi_search_results = isi.isi_search(body, isi_search_url) # add results together all_search_results.append(nyu_search_results) all_search_results.append(isi_search_results) #flatten the list of dicts all_search_results = list(chain.from_iterable(all_search_results)) return all_search_results # NYU Search if body['data_location'] == "NYU": nyu_search_url = f'https://{nyu_user}:{nyu_pwd}@wm.auctus.vida-nyu.org/api/v1/search' nyu_search_results = nyu.nyu_search(body, nyu_search_url) return nyu_search_results # ISI Search if body['data_location'] == "ISI": isi_search_url = f'https://{isi_user}:{isi_pwd}@dsbox02.isi.edu:8888/datamart-api-wm/metadata/variables?' isi_search_results = isi.isi_search(body, isi_search_url) return isi_search_results
def towdata_put(body): # noqa: E501 """Uploads live data to the server for predicition The data should be in a csv format # noqa: E501 :param body: :type body: dict | bytes :rtype: None """ body = Body.from_dict(connexion.request.get_json()) # noqa: E501 print(body) UpdateData.update(SaveData, body.csv)
def put_pipeline_favorite(organization, pipeline, body): """ put_pipeline_favorite Favorite/unfavorite a pipeline :param organization: Name of the organization :type organization: str :param pipeline: Name of the pipeline :type pipeline: str :param body: Set JSON string body to {\"favorite\": true} to favorite, set value to false to unfavorite :type body: dict | bytes :rtype: FavoriteImpl """ if connexion.request.is_json: body = Body.from_dict(connexion.request.get_json()) return 'do some magic!'
def question_capsule_cid_post(body, cid): # noqa: E501 """Post new answer for question capsules # noqa: E501 :param body: :type body: dict | bytes :param cid: capsule id :type cid: int :rtype: List[QuestionCapsule] """ if not checkOpenID(): return "Please call WeChat API first.", 401 u_info = database.getInfo(flask.session.get("open_id")) if u_info is None: return "Not found", 404 if connexion.request.is_json: body = Body.from_dict(connexion.request.get_json()) # noqa: E501 info = database.getQuestionCapsuleByID(u_info[0], cid) if not info: return "Not Found", 404 if info[6]: return "Already answered", 409 print(body) if not body.answer: return "Bad Request", 400 qid = int(info[3]) database.updateQuestionCapsule(cid, body.answer) return { "id": info[0], "quesion": questions[qid // 100 - 1][qid % 100], "answer": info[4].decode("utf-8") == "voice" and "audio" or "text", "time": int(info[5].timestamp()), "new_answer": body.answer } return "Bad Request", 400
def app_naive_forecast(body): # noqa: E501 """app_naive_forecast Sending time series which needs to be forecasted # noqa: E501 :param body: :type body: dict | bytes :rtype: InlineResponse200 """ if connexion.request.is_json: body = Body.from_dict(connexion.request.get_json()) # noqa: E501time_series = connexion.request.get_json(); """ time_series = time_series['time_series'] time_series = pd.Series(time_series) forecaster = NaiveForecaster(strategy="last") forecaster.fit(time_series) #TODO: Move to yaml spec fh = ForecastingHorizon(list(range(1,7)), relative = False) y_pred = forecaster.predict(fh) print(y_pred) return {"forecast": y_pred.values.tolist()} """ print(type(body)) time_series = body.to_dict() time_series = time_series["time_series"] time_series = pd.Series(time_series) forecaster = NaiveForecaster(strategy="last") forecaster.fit(time_series) #TODO: Move to yaml spec fh = ForecastingHorizon(list(range(1,7)), is_relative = True) y_pred = forecaster.predict(fh) print(y_pred) return {"forecast": y_pred.values.tolist()}
def html2pdf(body): """ Convert html with addtional files to pdf :param body: data for conversion :type body: dict | bytes :rtype: None """ if connexion.request.is_json: body = Body.from_dict(connexion.request.get_json()) extra_files = {} for ef in body.extrafiles: data = base64.decodebytes(ef.content.encode("utf-8")) mime = magic.from_buffer(data, True) extra_files[ef.name] = dict(string=data, mime_type=mime) def my_data_fetcher(url: str): print("requested:", url, file=sys.stderr) parsed = urlparse(url) path = parsed.path while path.startswith("/"): path = path[1:] print("calculated path:", path, file=sys.stderr) item = extra_files.get(path, None) if item is None: print("element not found:", url, file=sys.stderr) raise ValueError("Data not found: %s" % path) return item print("starting to generate", file=sys.stderr) html = HTML(string=base64.decodebytes(body.basedocument.encode("utf-8")), url_fetcher=my_data_fetcher, base_url="internal:///renderit.html") return html.write_pdf()
def post_primary(version, problem): global vrs """ Update the existing primary :param version: The version of the problem being manipulated :type version: int :param problem: Problem object that needs to be updated. :type problem: dict | bytes :rtype: int if connexion.request.is_json: problem = Body.from_dict(connexion.request.get_json()) return 'do some magic!' """ try: print("\n-----------------------POST PRIMARY----------------------\n") str_body = str(problem.decode("utf-8")).replace('\'', '\"') json.loads(str_body) #pprint(str_body) print("vrs is: {0} | In Version is: {1}\n".format(vrs, version)) #Gets JSON from connection and store in problem problem = Body.from_dict(connexion.request.get_json()) json.dumps(problem, sort_keys=True, indent=4, ensure_ascii=False) print("\nproblem\n") pprint(problem) #If the Version is 9000 and the JSON has "delete" = 1, then reset server database if (version == 9000) and ("delete" in problem): if problem["delete"] == 1: print("Deleting data in db") #Resets server database db.posts.delete_many({}) #Sets vrs variable to 0 so it will get deleted vrs = 0 return jsonify({"version": version}) else: print( "Version was 9000 but 'delete' = 1 not in body. Database still intact" ) else: #Does a check. Happens when server restarts anew if vrs == 0: print("Deleting data in db") #Deletes database db.posts.delete_many({}) vrs = 0 #Run actual POST of message into database if vrs == version: print("Versions Equal") db_size = db.posts.count() + 1 print("\ndb_size is: {0}".format(db_size)) #Inserts the content into the body and adds version number as well db.posts.insert_one({"version": version, "body": problem}) #Increments vrs variable vrs = vrs + 1 print("\nvrs incremented to {0}".format(vrs)) print("\n\tSUCCESS") #Return to server, the version # just as a check return jsonify({"version": version}) else: print("\n\tError Versions NOT EQUAL") print("\n\tFAILURE") #return 'Versions not equal' return get_status(412, "Incorrect Version Number" ), status.HTTP_412_PRECONDITION_FAILED print("\n-------------------------------------------------\n") #return 'Magic happened2' except ValueError: print("\n\tError Post_Primary") print("\n\tFAILURE") return get_status( 500, "Invalid JSON"), status.HTTP_500_INTERNAL_SERVER_ERROR