Ejemplo n.º 1
0
def login():
    data = request.get_json()
    try:
        someone = AuthService.instance().login(data['username'], data['password'])
        now = datetime.utcnow()
        payload = {
            'exp': expiration,
            'iat': now,
            'sub': someone.id,
            'username': someone.username
        }
        token = functions.get_token(payload)

        active_session = SessionService.instance().get(someone.id)
        if active_session and active_session.expiration > now:
            token = active_session.token
        elif active_session:
            SessionService.instance().delete(someone.id)
            SessionService.instance().set(someone.id, token, expiration)
        else:
            SessionService.instance().set(someone.id, token, expiration)

        return shortcuts.success('Welcome inside !', token=token)
    except Exception as e:
        LoggerService.instance().debug(e)
        return shortcuts.error('Invalid login !'), 401
Ejemplo n.º 2
0
def my_login(request):
    if request.method == 'GET':
        return render(request, 'login.html')

    if request.method == 'POST':
        form = MyLoginForm(request.POST)
        if form.is_valid():
            # 1. 只校验的字段username和password的长度,必填等信息
            # 2. 用户名必须存在my_user表中
            username = form.cleaned_data['username']
            password = form.cleaned_data['password']
            user = MyUser.objects.get(username=username)
            # 校验密码是否一致
            if not check_password(password, user.password):
                pwd_error = '密码错误'
                return render(request, 'login.html', {'pwd_error': pwd_error})
            # 用户名和密码验证成功了,需要使用cookie+token进行登录身份标识
            res = HttpResponseRedirect(reverse('user:my_index'))
            token = get_token()
            res.set_cookie('token', token, max_age=86400)
            # res.delete_cookie('token')
            # 后端保存token参数值,用于用户下次访问时进行判断
            out_time = datetime.utcnow() + timedelta(days=1)
            my_token = MyUserToken.objects.filter(user_id=user.id).first()
            if my_token:
                my_token.token = token
                my_token.out_time = out_time
                my_token.save()
            else:
                MyUserToken.objects.create(token=token,
                                           user=user,
                                           out_time=out_time)
            return res

        errors = form.errors
        return render(request, 'login.html', {'errors': errors})
        csv_reader = csv.reader(fd, delimiter=',')
        old_library = []
        for row in csv_reader:
            old_library.append(row)

        # Armazenando ids registrados no espelho local
        local_id_list = list(list(zip(*old_library))[0])
    except FileNotFoundError:
        local_id_list = []
    except IndexError:
        local_id_list = []

    # recuperando ids de faixas da biblioteca remota
    Constants.init()
    sp = spotipy.Spotify(auth=get_token())

    tracks_info = execute_spotify_command(
        sp, spotipy.client.Spotify.current_user_saved_tracks, (limit, ))
    remote_id_list = [item['track']['id'] for item in tracks_info]

    # Definição de ids para inserção e deleção
    ids_to_insert = [
        item for item in remote_id_list if item not in local_id_list
    ]
    ids_to_delete = [
        item for item in local_id_list if item not in remote_id_list
    ]

    # Extração de features para novas inserções
    ids_to_insert_split_in_chunks = [
Ejemplo n.º 4
0
        # Realiza o cálculo da distância somente entre até 1000 músicas aleatoriamente escolhidas dentro da biblioteca
        random.shuffle(songs_ids)
        candidates = songs_ids[:1000]

        # Escolha das 50 músicas mais parecidas com a música base
        sorted_songs_ids = sorted(
            songs_ids,
            key=lambda item: get_song_distance(infos[item], infos[base_song_id
                                                                  ], weights))
        ids_to_new_playlist = [base_song_id] + sorted_songs_ids[:49]

        # Formatação da URL para criação da playlist
        Constants.init()
        payload1 = {'name': 'shuffle_{}'.format(base_song_id)}
        sp = spotipy.Spotify(get_token())
        response = sp._post(
            "https://api.spotify.com/v1/users/{}/playlists".format(
                Constants.username),
            payload=payload1)
        playlist_id = response['id']

        # Formatação de URL para adição de músicas à playlist recém criada
        uris_to_new_playlist = [
            "spotify:track:" + item for item in ids_to_new_playlist
        ]
        payload2 = {'uris': uris_to_new_playlist}

        sp._post("https://api.spotify.com/v1/playlists/{}/tracks".format(
            playlist_id),
                 payload=payload2)