簡體   English   中英

如何使用python登錄由google + API認證的網站?

[英]How to login into an website which is authenticated by google + API using python?

如何使用 python 代碼登錄某個網站, ie www.example.com/auth/gmail ,它利用 google+ API 進行用戶登錄。 現在我想使用 python 代碼使用我的憑據(Gmail 或什么?)登錄。 請幫助我如何解決這個問題。

謝謝

這里有一個使用 google-api-python-client 的示例 首先,您必須在 google 開發者控制台上創建您的客戶端機密。

第一次執行代碼時,您必須授權腳本使用您的 gmail 帳戶,然后您可以將憑據保存在示例中的文件中,並在以后的執行中使用它,而無需此身份驗證

from googleapiclient.discovery import build
from oauth2client import client
from googleapiclient.errors import HttpError
import base64
from email.mime.text import MIMEText
from apiclient import errors
from oauth2client import client
import httplib2
from googleapiclient.discovery import build


def getCredentials(secrets, scope,filename):
    flow = client.flow_from_clientsecrets(
            secrets,
            scope=scope,
            redirect_uri='urn:ietf:wg:oauth:2.0:oob')
    auth_uri = flow.step1_get_authorize_url()
    webbrowser.open(auth_uri)
    auth_code = raw_input('Enter the auth code: ')
    credentials = flow.step2_exchange(auth_code)
    saveJson(filename,credentials.to_json())


def saveJson(filename, object):
    with open(filename, 'w') as f:
        json.dump(object, f)

def openJson(filename):
    with open(filename, 'r') as f:
        object = json.load(f)
    return object

if __name__=='__main__':
    client_secrets = 'client_secrets.json' #client secrets to use the API
    credentials = 'auth_credentials.json'
    if(firstRun) #create a file with the auth credentials
        scope = 'https://www.googleapis.com/auth/gemail.send'
        getCredentials(secrets,scope,credentials)

    cre = client.Credentials.new_from_json(openJson(credentials))
    http_auth = cre.authorize(httplib2.Http())
    gmail = build('gmail', 'v1', http=http_auth)
    #gmail.doSomething

這是舊的(沙箱)並且完成得非常快,因此您必須重構代碼

import re
import sys
import imaplib
import getpass
import email
import datetime
import string
import get_mail_search
from sys import stdout

M = imaplib.IMAP4_SSL('imap.gmail.com')
class Get_mail(object):
    """docstring for Get_mail"""
    def __init__(self, *args):
        super(Get_mail, self).__init__()
        c=1
        self.login(c)
        self.toast_msg()

        raw_input()
    def toast_msg(self, *args):
        """docstring for Get_mail"""
        M = self.mailbox()
        stdout.write("\n{}\n".format(get_mail_search.search_help_info))
        serach_input = raw_input()
        rv, data = M.search(None, serach_input)
        if rv != 'OK':
            print "No messages found!"
        id_ls = data[0].split()
        rev_id_ls = [i for i in reversed(id_ls)]
        if rev_id_ls:
            for o in rev_id_ls:
                try:
                    msg_content = self.process_mailbox(M, o)
                    _date_ = msg_content[0]
                    _from_ = msg_content[1]
                    _to_   = msg_content[2]
                    _subject_ = msg_content[3]
                    _msg_   = msg_content[4]
                    stdout.write("$$$$$$$$$$$\nDate: {}\nFrom: {}\nTo: {}\nSubject: {}\nMSG: {}\n".format(_date_,_from_,_to_,_subject_,_msg_))
                except Exception, e:
                    pass
        else:
            stdout.write("No {} Mail Found!".format(serach_input))
            raw_input()
            self.toast_msg()

    def login(self, try_c, *args):
        """docstring for Get_mail"""
        try:
            stdout.write("\nMail:\n")
            mail = raw_input()
            if mail:
                M.login(str(mail), getpass.getpass())
            else:
                sys.exit(1)
        except imaplib.IMAP4.error:
            if try_c<=3:
                stdout.write("Versuch: {}/3\n".format(try_c))
                stdout.write("Die eingegebene E-Mail-Adresse und das Passwort stimmen nicht uberein. Nochmal versuchen")
                try_c+=1
                self.login(try_c)
            else:
                sys.exit(1)
    def mailbox(self, *args):
        """docstring for Get_mail"""
        rv, mailboxes = M.list()
        if rv == 'OK':
            for menu in mailboxes:
                print('{}'.format(menu))
            rv, data = M.select("inbox")
            if rv == 'OK':
                return M
    def eval_decode(self, header, *args):
        """docstring for Get_mail"""
        return email.Header.decode_header(header)[0]

    def process_mailbox(self, M, num, *args):
        """docstring for Get_mail"""
        rv, header = M.fetch(num, '(RFC822)')
        if rv != 'OK':
            print "ERROR getting message", num
        header_msg = email.message_from_string(header[0][1])
        if header_msg.is_multipart():
            body=[payload.get_payload(decode=True) for payload in header_msg.get_payload()]
        else:
            body=payload.get_payload(decode=True)
        from_decode = self.eval_decode(header_msg['From'])
        subject_decode = self.eval_decode(header_msg['Subject'])
        date_decode = self.eval_decode(header_msg['Date'])
        to_decode = self.eval_decode(header_msg['To'])
        return (date_decode[0], from_decode[0], to_decode[0], subject_decode[0], str(body[0]))
def run():
    try:
        Get_mail()
    except KeyboardInterrupt:
        M.close()
        M.logout()
        sys.exit(1)
run()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM