Example #1
0
    def test_black_list(self):
        con = self.connection_db
        count_users = 10
        with con:
            target_param = dict(test_target_user)
            id_vk_target = target_param.pop("id_vk")
            target_id = target_param.get("id")
            db_engine.insert_update_user_vk(con, "target_users_vk",
                                            id_vk_target, **target_param)

            user_param1 = dict(test_user1)
            id_vk1 = user_param1.pop("id_vk")
            user_param1.pop("id")

            dict_test = dict(test_grade1)
            dict_test.pop("target_users_id")
            dict_test.pop("users_id")
            dict_test.pop("id")

            for num in range(1, count_users + 1):
                user_param1.update({"id": num})
                dict_test.update(points_user=(-1 if (num % 2) == 0 else num))
                db_engine.insert_update_user_vk(con, "users_vk", id_vk1 + num,
                                                **user_param1)
                db_engine.insert_update_grade_users(con, target_id, num,
                                                    **dict_test)

        with patch("db_engine.input", side_effect=["нет"]):
            result = db_engine.black_list(con, target_id)
        self.assertIsInstance(result, list)
        self.assertEqual(len(result), count_users // 2)
Example #2
0
    def test_get_user_of_id_vk(self):
        con = self.connection_db
        with con:
            target_param = dict(test_target_user)
            id_vk_target = target_param.pop("id_vk")
            target_id = target_param.get("id")
            db_engine.insert_update_user_vk(con, "target_users_vk",
                                            id_vk_target, **target_param)

            user_param1 = dict(test_user1)
            id_vk1 = user_param1.pop("id_vk")
            user_id1 = user_param1.get("id")
            db_engine.insert_update_user_vk(con, "users_vk", id_vk1,
                                            **user_param1)

        result = db_engine.get_user_of_id_vk(con, "target_users_vk",
                                             id_vk_target)
        self.assertEqual(
            [result[0], result[1], result[8]],
            [target_id, id_vk_target,
             target_param.get("age")],
        )

        result = db_engine.get_user_of_id_vk(con, "users_vk", id_vk1)
        self.assertEqual(
            [result[0], result[1], result[6]],
            [user_id1, id_vk1, user_param1.get("age")],
        )
Example #3
0
    def test_get_grade_users(self):
        with self.connection_db as con:
            target_param = dict(test_target_user)
            id_vk_target = target_param.pop("id_vk")
            db_engine.insert_update_user_vk(con, "target_users_vk",
                                            id_vk_target, **target_param)

            user_param1 = dict(test_user1)
            id_vk1 = user_param1.pop("id_vk")
            db_engine.insert_update_user_vk(con, "users_vk", id_vk1,
                                            **user_param1)

            dict_test = dict(test_grade1)
            target_id = dict_test.pop("target_users_id")
            users_id = dict_test.pop("users_id")
            db_engine.insert_update_grade_users(con, target_id, users_id,
                                                **dict_test)

        result = db_engine.get_grade_users(con, target_id, id_vk1, False)
        self.assertEqual(
            result,
            (
                test_grade1.get("users_id"),
                test_grade1.get("num_common_groups"),
                test_grade1.get("points_auto"),
            ),
        )
        result = db_engine.get_grade_users(self.connection_db, target_id,
                                           users_id, True)
        self.assertIsNone(result)
Example #4
0
    def test_top_from_grade_users(self):
        con = self.connection_db
        count_top = 1000
        with con:
            target_param = dict(test_target_user)
            id_vk_target = target_param.pop("id_vk")
            target_id = target_param.get("id")
            db_engine.insert_update_user_vk(con, "target_users_vk",
                                            id_vk_target, **target_param)

            user_param1 = dict(test_user1)
            id_vk1 = user_param1.pop("id_vk")
            user_param1.pop("id")

            dict_test = dict(test_grade1)
            dict_test.pop("target_users_id")
            dict_test.pop("users_id")
            dict_test.pop("id")
            points_auto = dict_test.pop("points_auto")

            for num in range(1, count_top + 1):
                user_param1.update({"id": num})
                dict_test.update(points_auto=points_auto + num)
                db_engine.insert_update_user_vk(con, "users_vk", id_vk1 + num,
                                                **user_param1)
                db_engine.insert_update_grade_users(con, target_id, num,
                                                    **dict_test)

        result = db_engine.top_from_grade_users(con, count_top, target_id)
        for num, grade in enumerate(result):
            self.assertEqual(grade[3], points_auto + count_top - num)
Example #5
0
def get_id_vk_vkapi_of_login(
    connection, current_login, vk_v, application_id
) -> (int, vk.API):
    vk_api = None
    vk_id = None
    current_user = get_id_vk_token_on_login(connection, current_login)
    # если нет такого логина в БД идем на сайт ВК
    test_session_vk_flag = False
    connect_to_site_flag = True
    if current_user:
        vk_id = current_user[0]
        # print('юзер есть')
        # test_token = f"{current_user[1]}"
        # print(f'test_token:{test_token}')
        # проверяем токен на валидность
        try:
            session_vk = vk.Session(f"{current_user[1]}")
            if vk.API(session=session_vk, timeout=60, v=vk_v).users.get():
                test_session_vk_flag = True
        except (vk.api.VkAPIError, vk.api.VkAuthError, requests.exceptions.ConnectionError) as e:
            if e.__str__().find("Errno 11001") > 0:
                print("Не могу подключиться к сайту, проверьте соединение")

            else:
                print("Не удалось подключиться к сайту")
            connect_to_site_flag = False
    # если токен не валидный и есть соединение с сайтом пробуем его получить через пароль
    if connect_to_site_flag:
        if not current_user or not test_session_vk_flag:
            try:
                # пробуем получить токен
                password = getpass(prompt="Введите пароль:")
                session_vk_login = vk.AuthSession(
                    application_id, current_login, password,
                )
                # логинимся через токен для его проверки
                session_vk = vk.Session(session_vk_login.access_token)
                vk_api = vk.API(session_vk, timeout=60, v=vk_v)
                user_target_dict = vk_api.users.get()[0]
                # сохраняем пользователя/ обновляем токен в БД
                user_in_bd = insert_update_user_vk(
                    connection,
                    "target_users_vk",
                    user_target_dict.get("id"),
                    login=current_login,
                    token=session_vk.access_token,
                )
                vk_id = user_in_bd[1]
            except vk.api.VkAuthError as e:
                if e.__str__().find("incorrect password") > 0:
                    print(f"Пароль не верный")
        else:  # логин имеется в бд и токен работает
            session_vk = vk.Session(f"{current_user[1]}")
            vk_api = vk.API(session_vk, timeout=60, v=vk_v)
    if vk_id and vk_api:
        return vk_id, vk_api
Example #6
0
    def test_insert_update_grade_users(self):
        dict_test = dict(test_grade1)
        target_id = dict_test.pop("target_users_id")
        users_id = dict_test.pop("users_id")
        with self.connection_db as con:
            with con.cursor() as curs:
                curs.execute(
                    f"select * from grade_users where target_users_id = {target_id}"
                    f"and users_id = {users_id}")
                curs.fetchall()

                target_param = dict(test_target_user)
                id_vk_target = target_param.pop("id_vk")
                db_engine.insert_update_user_vk(con, "target_users_vk",
                                                id_vk_target, **target_param)

                user_param1 = dict(test_user1)
                id_vk1 = user_param1.pop("id_vk")
                db_engine.insert_update_user_vk(con, "users_vk", id_vk1,
                                                **user_param1)

        with self.connection_db as con:
            result = db_engine.insert_update_grade_users(
                con, target_id, users_id, **dict_test)

        self.assertEqual(
            result,
            (
                test_grade1.get("id"),
                test_grade1.get("target_users_id"),
                test_grade1.get("users_id"),
                test_grade1.get("points_auto"),
                test_grade1.get("points_user"),
                test_grade1.get("num_common_friends"),
                test_grade1.get("num_common_groups"),
                test_grade1.get("export_state"),
            ),
        )
Example #7
0
    def test_get_users_of_id_vk(self):
        con = self.connection_db
        count_users = 10
        user_param1 = dict(test_user1)
        id_vk1 = user_param1.pop("id_vk")
        user_param1.pop("id")
        with con:
            list_ids = []
            for num in range(1, count_users + 1):
                result = db_engine.insert_update_user_vk(
                    con, "users_vk", id_vk1 + num, **user_param1)
                list_ids.append(result[0])

        result = db_engine.get_users_of_id_vk(con, "users_vk", list_ids, True)
        self.assertEqual(len(result), len(list_ids))
Example #8
0
    def test_all_items_in_table(self):
        con = self.connection_db
        count_users = 100
        user_param1 = dict(test_user1)
        id_vk1 = user_param1.pop("id_vk")
        user_param1.pop("id")
        with con:
            list_ids = []
            for num in range(1, count_users + 1):
                result = db_engine.insert_update_user_vk(
                    con, "users_vk", id_vk1 + num, **user_param1)
                list_ids.append(result[0])

        result = db_engine.all_items_in_table(con, "users_vk")
        self.assertIsInstance(result, list)
        self.assertEqual(result[2][1], id_vk1 + 3)
        self.assertEqual(len(result), count_users)
Example #9
0
 def test_insert_update_user_vk(self):
     user_param = dict(test_target_user)
     user_id_vk = user_param.pop("id_vk")
     user_param.pop("id")
     user_param.pop("login")
     user_param.pop("token")
     result = db_engine.insert_update_user_vk(self.connection_db,
                                              "users_vk", user_id_vk,
                                              **user_param)
     self.assertEqual(
         [
             result[1],
             result[2],
             result[3],
             result[4],
             result[5],
             result[6],
             result[7],
             result[8],
             result[9],
             result[10],
             result[11],
             result[12],
             result[13],
             result[14],
         ],
         [
             test_target_user.get("id_vk"),
             test_target_user.get("first_name"),
             test_target_user.get("last_name"),
             test_target_user.get("sex"),
             test_target_user.get("city"),
             test_target_user.get("age"),
             test_target_user.get("activities"),
             test_target_user.get("interests"),
             test_target_user.get("movies"),
             test_target_user.get("music"),
             test_target_user.get("books"),
             test_target_user.get("quotes"),
             test_target_user.get("about"),
             test_target_user.get("home_town"),
         ],
     )
Example #10
0
    def test_count_in_table(self):
        con = self.connection_db
        count_users = 10
        target_param = dict(test_target_user)
        id_vk_target = target_param.pop("id_vk")
        target_param.pop("id")
        with con:
            for num in range(1, count_users + 1):
                db_engine.insert_update_user_vk(con, "target_users_vk",
                                                id_vk_target + num,
                                                **target_param)
            db_engine.insert_update_user_vk(con, "target_users_vk",
                                            id_vk_target + 1, **target_param)
            db_engine.insert_update_user_vk(con, "target_users_vk",
                                            id_vk_target + 2, **target_param)

        result = db_engine.count_in_table(con, "target_users_vk")
        self.assertEqual(result, count_users)
Example #11
0
def search_users_of_parametr(connection, vk_api, search_p, current_target_user):
    all_users_id_search = []
    count_all_iteration = len(search_p.status) * (
        search_p.age_to - search_p.age_from + 1
    )
    print("Поиск подходящих пользователей")
    status_bar_find = StatusBar(count_all_iteration)
    for current_status in search_p.status:
        count_errors = 0
        for current_age in range(search_p.age_from, search_p.age_to + 1):
            status_bar_find.plus(1)
            dict_search = dict(
                q=search_p.q,
                city=search_p.city,
                age_from=current_age,
                age_to=current_age,
                count=search_p.count,
                sex=search_p.sex,
                has_photo=search_p.has_photo,
                status=current_status,
                sort=random.choice((0, 1)),
                fields=[
                    "bdate",
                    "relation",
                    "city",
                    "common_count",
                    "sex",
                    "activities",
                    "interests",
                    "music",
                    "movies",
                    "books",
                    "quotes",
                    "about",
                    "home_town",
                ],
            )
            users_search = api_reuest(vk_api, "users.search", **dict_search)
            # счетчик ошибок, если на одном пользователе нет ответа, то выходим из цикла досрочно
            if not users_search:
                count_errors += 1
                if count_errors == 10:
                    break
                continue

            with connection:
                for user in users_search.get("items"):
                    # print(user)
                    try:
                        user_current_search = insert_update_user_vk(
                            connection,
                            "users_vk",
                            user.get("id"),
                            first_name=user.get("first_name"),
                            last_name=user.get("last_name"),
                            age=current_age,
                            city=search_p.city,
                            sex=user.get("sex"),
                            relation=current_status,
                            activities=list_from_string(user.get("activities")),
                            interests=list_from_string(user.get("interests")),
                            movies=list_from_string(user.get("movies")),
                            music=list_from_string(user.get("music")),
                            books=list_from_string(user.get("books")),
                            quotes=list_from_string(user.get("quotes")),
                            about=list_from_string(user.get("about")),
                            home_town=list_from_string(user.get("home_town")),
                        )
                        user_id_bd = user_current_search[0]
                        # print('user', user_current_search)
                        all_users_id_search.append(user_id_bd)
                        # if user_current_search[7]:
                        #     common_activities = set(current_target_user.activities) & set(user_current_search[7])
                        #     print(f'common_activities:{common_activities}')
                        common_activities = calc_common_param(
                            current_target_user.activities, user_current_search[7]
                        )
                        common_interests = calc_common_param(
                            current_target_user.interests, user_current_search[8]
                        )
                        common_movies = calc_common_param(
                            current_target_user.movies, user_current_search[9]
                        )
                        common_music = calc_common_param(
                            current_target_user.music, user_current_search[10]
                        )
                        common_books = calc_common_param(
                            current_target_user.books, user_current_search[11]
                        )
                        common_quotes = calc_common_param(
                            current_target_user.quotes, user_current_search[12]
                        )
                        common_about = calc_common_param(
                            current_target_user.about, user_current_search[13]
                        )
                        common_home_town = calc_common_param(
                            current_target_user.home_town, user_current_search[14]
                        )

                        points_relation = calc_points(current_status, {1: 5, 6: 15})
                        points_age = calc_points(
                            int(math.fabs(current_target_user.age - current_age)),
                            {0: 20, 1: 17, 2: 15, 3: 12, 4: 10, 5: 5},
                        )
                        points_activities = calc_points(
                            common_activities, {1: 10, 2: 20, 3: 30}
                        )
                        points_interests = calc_points(
                            common_interests, {1: 10, 2: 20, 3: 30}
                        )
                        points_movies = calc_points(
                            common_movies, {1: 10, 2: 13, 3: 15}
                        )
                        points_music = calc_points(common_music, {1: 20, 2: 25, 3: 30})
                        points_books = calc_points(common_books, {1: 10, 2: 15, 3: 20})
                        points_quotes = calc_points(
                            common_quotes, {1: 10, 2: 20, 3: 30}
                        )
                        points_about = calc_points(common_about, {1: 10, 2: 20, 3: 30})
                        points_home_town = calc_points(
                            common_home_town, {1: 20, 2: 25, 3: 30}
                        )
                        points_common_friends = calc_points(
                            user.get("common_count"), {1: 30, 2: 35, 3: 40}
                        )

                        points_auto = (
                            points_age
                            + points_relation
                            + points_activities
                            + points_interests
                            + points_movies
                            + points_music
                            + points_books
                            + points_quotes
                            + points_about
                            + points_home_town
                            + points_common_friends
                        )

                        insert_update_grade_users(
                            connection,
                            current_target_user.user_bd_id,
                            user_id_bd,
                            points_auto=points_auto,
                            num_common_friends=user.get("common_count"),
                        )

                    except TypeError as e:
                        print(f"Ошика типов: {e}")
    if all_users_id_search:
        return all_users_id_search
Example #12
0
def set_current_target_user(connection, vk_api) -> VKUser:
    # записываем все данные пользователя с ВК
    user_target_dict = None
    try:
        user_target_dict = vk_api.users.get(
            fields=[
                "city",
                "bdate",
                "sex",
                "relation",
                "status",
                "activities",
                "interests",
                "music",
                "movies",
                "personal",
                "relation",
                "common_count",
                "has_photo",
                "books",
                "quotes",
                "about",
                "home_town",
            ]
        )[0]
    except requests.exceptions.HTTPError as e:
        print(f"Не удалось получить данные пользователя: {e}")
    if user_target_dict:
        with connection:
            parametrs_user_dict = dict(
                first_name=user_target_dict.get("first_name"),
                last_name=user_target_dict.get("last_name"),
                age=(int(dt.now().year) - int(user_target_dict.get("bdate")[-4:])),
                sex=user_target_dict.get("sex"),
                city=user_target_dict.get("city").get("id")
                if user_target_dict.get("city")
                else None,
                activities=list_from_string(user_target_dict.get("activities")),
                interests=list_from_string(user_target_dict.get("interests")),
                movies=list_from_string(user_target_dict.get("movies")),
                music=list_from_string(user_target_dict.get("music")),
                books=list_from_string(user_target_dict.get("books")),
                quotes=list_from_string(user_target_dict.get("quotes")),
                about=list_from_string(user_target_dict.get("about")),
                home_town=list_from_string(user_target_dict.get("home_town")),
            )
            # фильтр пустых значений:
            param_for_delete_list = []
            for key, value in parametrs_user_dict.items():
                if value is None:
                    param_for_delete_list.append(key)
            for key in param_for_delete_list:
                parametrs_user_dict.pop(key)

            user_in_bd = list(
                insert_update_user_vk(
                    connection,
                    "target_users_vk",
                    user_target_dict.get("id"),
                    **parametrs_user_dict,
                )
            )

        if user_in_bd:
            params_for_update = dict()
            if user_in_bd[6] not in (1, 2):  # пол
                sex_exist = None
                while not sex_exist:
                    sex = input(
                        "Выберете ваш пол: мужской введите - м, женский введите - ж: "
                    ).lower()
                    sex_dict = {"m": 2, "м": 2, "ж": 1}
                    if sex_dict.get(sex):
                        user_in_bd[6] = sex_dict.get(sex)
                        params_for_update.update(sex=user_in_bd[6])
                        sex_exist = True

            if user_in_bd[7] is None:  # город
                while not user_in_bd[7]:
                    params_city = dict(
                        q=input("Введите наименование вашего города: "), country_id=1
                    )
                    city_list = api_reuest(vk_api, "database.getCities", **params_city)
                    if city_list:
                        if city_list.get("count") > 0:
                            city_list_find = city_list.get("items")
                            print("0-Ввести другой город")
                            for number, city in enumerate(city_list_find, 1):
                                city_string = f'{number}-{city.get("title")}'
                                if city.get("area"):
                                    city_string += f', {city.get("area")}'
                                if city.get("region"):
                                    city_string += f', {city.get("region")}'
                                print(city_string)
                            city_number = (
                                posintput(
                                    "Введите номер вашего города: ",
                                    0,
                                    len(city_list.get("items"),),
                                )
                                - 1
                            )
                            if city_number >= 0:
                                user_in_bd[7] = city_list_find[city_number].get("id")
                            params_for_update.update(city=user_in_bd[7])
                        else:
                            print("Не найдено подходящих городов, попробуйте снова")
                    else:
                        print("Поиск города не удался - попробуйте снова")

            if (user_in_bd[8] is None) or (user_in_bd[8] > 150):  # возраст
                user_in_bd[8] = posintput("Введите свой возраст: ", 10, 150)
                params_for_update.update(age=user_in_bd[8])

            if user_in_bd[9] is None:
                while not user_in_bd[9]:
                    user_in_bd[9] = list_from_string(
                        input("Введите через запятую вашу деятельность: ")
                    )
                    if user_in_bd[9]:
                        params_for_update.update(activities=user_in_bd[9])

            if user_in_bd[10] is None:
                while not user_in_bd[10]:
                    user_in_bd[10] = list_from_string(
                        input("Введите через запятую ваши интересы: ")
                    )
                    if user_in_bd[10]:
                        params_for_update.update(interests=user_in_bd[10])

            if user_in_bd[11] is None:
                while not user_in_bd[11]:
                    user_in_bd[11] = list_from_string(
                        input("Введите через запятую ваши любимые фильмы: ")
                    )
                    if user_in_bd[11]:
                        params_for_update.update(movies=user_in_bd[11])

            if user_in_bd[12] is None:
                while not user_in_bd[12]:
                    user_in_bd[12] = list_from_string(
                        input("Введите через запятую вашу любимую музыку: ")
                    )
                    if user_in_bd[12]:
                        params_for_update.update(music=user_in_bd[12])

            if user_in_bd[13] is None:
                while not user_in_bd[13]:
                    user_in_bd[13] = list_from_string(
                        input("Введите через запятую ваши любимые книги: ")
                    )
                    if user_in_bd[13]:
                        params_for_update.update(books=user_in_bd[13])

            if user_in_bd[14] is None:
                while not user_in_bd[14]:
                    user_in_bd[14] = list_from_string(
                        input("Введите через запятую ваши любимые цитаты: ")
                    )
                    if user_in_bd[14]:
                        params_for_update.update(quotes=user_in_bd[14])

            if user_in_bd[15] is None:
                while not user_in_bd[15]:
                    user_in_bd[15] = list_from_string(
                        input("Расскажите немного о себе, кратко через запятую: ")
                    )
                    if user_in_bd[15]:
                        params_for_update.update(about=user_in_bd[15])

            if user_in_bd[16] is None:
                while not user_in_bd[16]:
                    user_in_bd[16] = list_from_string(
                        input("Введите свои любимые или родные города через запятую: ")
                    )
                    if user_in_bd[16]:
                        params_for_update.update(home_town=user_in_bd[16])

            # Записываем то что дозаполнили вручную
            if len(params_for_update) > 0:
                with connection:
                    insert_update_user_vk(
                        connection,
                        "target_users_vk",
                        user_in_bd[1],
                        **params_for_update,
                    )

            return VKUser(
                user_in_bd[1],
                user_in_bd[0],
                user_in_bd[4],
                user_in_bd[5],
                user_in_bd[6],
                user_in_bd[7],
                user_in_bd[8],
                user_in_bd[9],
                user_in_bd[10],
                user_in_bd[11],
                user_in_bd[12],
                user_in_bd[13],
                user_in_bd[14],
                user_in_bd[15],
                user_in_bd[16],
            )