Невозможно выполнить аутентификацию с помощью python minds api - PullRequest
0 голосов
/ 10 декабря 2018

Я пытаюсь получить доступ к социальному сайту minds.com через этот python api , установив модуль локально с помощью python3 setup.py install && pipenv run python и следуя инструкциям для входа в систему.

Тем не менее, я получаю это сообщение об ошибке при попытке аутентификации:

(По какой-то причине Stackoverflow не позволяет мне публиковать журнал ошибок Python, потому что он не имеет отступов, поэтому здесь это https://pastebin.com/0sWa1hmY)

Код, который, кажется, вызывается из API Python, выглядит следующим образом:

minds / api.py

# -*- coding: utf-8 -*-
from pprint import pprint

from requests.utils import dict_from_cookiejar, cookiejar_from_dict

from minds.connections import XSRFSession
from minds.exceptions import AuthenticationError
from minds.profile import Profile
from minds.utils import add_url_kwargs
from minds.endpoints import *
from minds.sections import NewsfeedAPI, ChannelAPI, NotificationsAPI, 
PostingAPI, InteractAPI


class Minds(NewsfeedAPI, ChannelAPI, NotificationsAPI, PostingAPI, ...):
    _xsrf_retries = 5

    def __init__(self, profile: Profile = None, login=True):
        self.con = XSRFSession()
        self.profile = profile
        if self.profile:
            if profile.cookie:
                self.con.cookies = cookiejar_from_dict(profile.cookie)
            if profile.proxy:
                self.con.proxies = {'https': profile.proxy, 'http':\
                profile.proxy}
        self._establish_xsrf()
        if self.profile and login and not self.is_authenticated:
            if profile.username and profile.password:
                self.authenticate(profile.username, profile.password)

(...)

def authenticate(self, username, password, save_profile=True) -> dict:
    """
    Authenticate current instance with given user
    :param: save_profile: whether to save profile locally
    """
    auth = {
        'username': username,
        'password': password
    }
    resp = self.con.post(AUTHENTICATE_URL, json=auth)
    self.user = resp.json()
    if self.user['status'] == 'failed':
        raise AuthenticationError("Couldn't log in with the ...")
    self.guid = self.user['user']['guid']
    if save_profile:
        Profile(
            username=username,
            password=password,
            cookie=self.get_cookies(),
            proxy=self.con.proxies.get('https'),
        ).save()
    return resp.json()

Python API, похоже, не поддерживается, но я думаю, что minds.com недавно использует jsonwebtokens для аутентификации. Что-то не хватает в api для поддержки jwt?

1 Ответ

0 голосов
/ 11 декабря 2018

После сравнения с запросом браузера снова и снова.Причина, по которой произошла ошибка, заключается в том, что вы указали неправильный тип контента, но на самом деле вам нужно отправить данные в формате json (кажется, веб-сайт шутит).Так что вам нужно указать headers["content-type"] = "text/plain".В противном случае веб-сайт ответит 500.

Примечание. Чтобы избежать широкого обсуждения, я могу ответить только на эту ошибку.

Измените код на приведенный ниже, но только одна строка отличается от исходного кода :).

def authenticate(self, username, password, save_profile=True) -> dict:
    """
    Authenticate current instance with given user
    :param: save_profile: whether to save profile locally
    """
    auth = {
        'username': username,
        'password': password
    }
    self.con.headers["content-type"] = "text/plain" ####
    resp = self.con.post(AUTHENTICATE_URL, json=auth)
    self.user = resp.json()
    if self.user['status'] == 'failed':
        raise AuthenticationError("Couldn't log in with the given credentials")
    self.guid = self.user['user']['guid']
    if save_profile:
        Profile(
            username=username,
            password=password,
            cookie=self.get_cookies(),
            proxy=self.con.proxies.get('https'),
        ).save()
    return resp.json()
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...