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 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
Пример #3
0
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
Пример #4
0
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
Пример #5
0
    def test_search_post(self):
        """Test case for search_post

        Search over Datamarts
        """
        body = Body()
        response = self.client.open('/search',
                                    method='POST',
                                    data=json.dumps(body),
                                    content_type='application/json')
        self.assert200(response,
                       'Response body is : ' + response.data.decode('utf-8'))
    def test_get_employees_search_results(self):
        """Test case for get_employees_search_results

        Get employee's search results
        """
        body = Body()
        response = self.client.open('/employees/search',
                                    method='POST',
                                    data=json.dumps(body),
                                    content_type='application/json')
        self.assert200(response,
                       'Response body is : ' + response.data.decode('utf-8'))
    def test_html2pdf(self):
        """Test case for html2pdf

        Convert html with addtional files to pdf
        """
        body = Body()
        response = self.client.open('/v1/html2pdf',
                                    method='POST',
                                    data=json.dumps(body),
                                    content_type='application/json')
        self.assert200(response,
                       'Response body is : ' + response.data.decode('utf-8'))
    def test_reactions_post(self):
        """Test case for reactions_post

        Réagir avec une emoji à un message
        """
        body = Body()
        response = self.client.open('/reactions',
                                    method='POST',
                                    data=json.dumps(body),
                                    content_type='application/json')
        self.assert200(response,
                       'Response body is : ' + response.data.decode('utf-8'))
    def test_filters(self):
        """Test case for filters

        urlから判断する
        """
        body = Body()
        response = self.client.open('/api/filters',
                                    method='POST',
                                    data=json.dumps(body),
                                    content_type='application/json')
        self.assert200(response,
                       'Response body is : ' + response.data.decode('utf-8'))
Пример #10
0
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 test_add_article(self):
        """Test case for add_article

        Создать новую статью
        """
        body = Body()
        response = self.client.open('/v2/article',
                                    method='POST',
                                    data=json.dumps(body),
                                    content_type='application/json')
        self.assert200(response,
                       'Response body is : ' + response.data.decode('utf-8'))
Пример #12
0
    def test_app_naive_forecast(self):
        """Test case for app_naive_forecast

        
        """
        body = Body()
        response = self.client.open('/forecast',
                                    method='POST',
                                    data=json.dumps(body),
                                    content_type='application/json')
        self.assert200(response,
                       'Response body is : ' + response.data.decode('utf-8'))
Пример #13
0
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 test_post_sm_contexts(self):
        """Test case for post_sm_contexts

        Create SM Context
        """
        body = Body()
        response = self.client.open('/sm-contexts',
                                    method='POST',
                                    data=json.dumps(body),
                                    content_type='multipart/related')
        self.assert200(response,
                       'Response body is : ' + response.data.decode('utf-8'))
Пример #15
0
    def test_towdata_put(self):
        """Test case for towdata_put

        Uploads live data to the server for predicition
        """
        body = Body()
        response = self.client.open('/towdata',
                                    method='PUT',
                                    data=json.dumps(body),
                                    content_type='application/json')
        self.assert200(response,
                       'Response body is : ' + response.data.decode('utf-8'))
Пример #16
0
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_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 test_add_product(self):
        """
        Test case for add_product

        Add a new product to the store
        """
        body = Body()
        response = self.client.open('/v2/v1/products',
                                    method='POST',
                                    data=json.dumps(body),
                                    content_type='application/json')
        self.assert200(response,
                       "Response body is : " + response.data.decode('utf-8'))
Пример #19
0
    def test_add_problem(self):
        """
        Test case for add_problem

        Creates a new problem and returns a problemID with default version 0
        """
        problem = Body()
        response = self.client.open('/v2/',
                                    method='POST',
                                    data=json.dumps(problem),
                                    content_type='application/json')
        self.assert200(response,
                       "Response body is : " + response.data.decode('utf-8'))
Пример #20
0
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 test_update_station(self):
        """Test case for update_station

        update existing station
        """
        body = Body()
        response = self.client.open(
            '/ayhanyunt12/MeteorolojiAPI/1.0.0/station',
            method='PUT',
            data=json.dumps(body),
            content_type='application/json')
        self.assert200(response,
                       'Response body is : ' + response.data.decode('utf-8'))
Пример #22
0
    def test_update_pet(self):
        """
        Test case for update_pet

        Update an existing pet
        """
        body = Body()
        response = self.client.open('/v2/pet',
                                    method='PUT',
                                    data=json.dumps(body),
                                    content_type='application/json')
        self.assert200(response,
                       "Response body is : " + response.data.decode('utf-8'))
Пример #23
0
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!'
Пример #24
0
    def test_post_analytic(self):
        """
        Test case for post_analytic

        Update the existing analytic
        """
        problem = Body()
        response = self.client.open(
            '/v1/analytic/ver={version}/'.format(version=789),
            method='POST',
            data=json.dumps(problem),
            content_type='application/json')
        self.assert200(response,
                       "Response body is : " + response.data.decode('utf-8'))
    def test_question_capsule_cid_post(self):
        """Test case for question_capsule_cid_post

        Post new answer for question capsules
        """
        body = Body()
        response = self.client.open(
            '/VegetableP/Time-Capsule-Post-2019/1.0.0/question_capsule/{cid}'.
            format(cid=56),
            method='POST',
            data=json.dumps(body),
            content_type='application/json')
        self.assert200(response,
                       'Response body is : ' + response.data.decode('utf-8'))
Пример #26
0
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
Пример #27
0
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)
Пример #28
0
    def test_update_problem(self):
        """
        Test case for update_problem

        Update the existing problem
        """
        problem = Body()
        response = self.client.open(
            '/v2/id={problem_id}/ver={version}/'.format(
                problem_id=56, version=56),
            method='PUT',
            data=json.dumps(problem),
            content_type='application/json')
        self.assert200(response,
                       "Response body is : " + response.data.decode('utf-8'))
    def test_obtener_progresion_lineal(self):
        """
        Test case for obtener_progresion_lineal

        Obtener la prediccion para un año dado el año a predecir y los datos de varios años anteriores
        """
        body = [Body()]
        query_string = [('AnioPrediccion', '2009')]
        response = self.client.open(
            '/server/Calculos/ObtenerProgresionLineal/',
            method='POST',
            data=json.dumps(body),
            content_type='application/json',
            query_string=query_string)
        self.assert200(response,
                       "Response body is : " + response.data.decode('utf-8'))
    def test_put_pipeline_favorite(self):
        """
        Test case for put_pipeline_favorite

        
        """
        body = Body()
        response = self.client.open(
            '//blue/rest/organizations/{organization}/pipelines/{pipeline}/favorite'
            .format(organization='organization_example',
                    pipeline='pipeline_example'),
            method='PUT',
            data=json.dumps(body),
            content_type='application/json')
        self.assert200(response,
                       "Response body is : " + response.data.decode('utf-8'))