1
from oauth2client.client import OAuth2WebServerFlow 
from oauth2client.tools import run_flow 
from oauth2client.file import Storage 
import requests  

CLIENT_ID = '9453asfasfaksdfh860b1osoiveogstt.apps.googleusercontent.com' 
CLIENT_SECRET = '6gRid8wF7TW8asdfasdftX' 


flow = OAuth2WebServerFlow(client_id=CLIENT_ID, 
          client_secret=CLIENT_SECRET, 
          scope='https://www.googleapis.com/auth/admin.directory.user https://www.googleapis.com/auth/admin.directory.user.readonly', 
          redirect_uri='http://example.com/auth_return') 

storage = Storage('creds.data') #token details stored here 
credentials = run_flow(flow, storage) 
tokenhere=credentials.access_token #tokens generated 

#send get request with token generated using requests 
r=requests.get("https://www.googleapis.com/admin/directory/v1/users?domain=mydomain.ocm",headers={'Authorization': 'Bearer {token}'.format(token=tokenhere)})  
result=r.json() 

이것은 Google에서 성공적으로 인증하고 사용자를 가져온 방법입니다.

이제 이것을 실행합니다. 확인을 위해 Google 계정을 선택하는 페이지와 승인을위한 동의 화면을 보여줍니다.Gmail에서 한 번 인증하는 방법 및 생성 된 토큰을 사용 하시겠습니까?

하지만 문제는 내가 이것을 실행할 때마다 발생합니다.

다음 번에 우리가 해당 단계를 반복해서 수행 할 필요는 없지만 오히려 직접 토큰을 전달하거나 저장된 하나를 사용하는 것이 좋습니다.

어떻게 실제로 구현 되나요? 정확한 단서는 없습니다. 누군가 나를 안내 해줘. 어떻게 그리고 어디서 그 부분을 할 수 있습니다. 지금은 인증 된 토큰을 확인하고 얻는 데 성공했습니다. 내가 너무 콘솔에서 직접 토큰을 가져 오기 위해 노력하고 있어요 때문에 차이가있을 수 있습니다 토큰을 얻고있다 방법은 그 목적을 위해 하나 개의 모듈을 사용하고 내가 올바르게해야 이해한다면, 따라서 너무

답변

0

보이는 한 : EXTRA

여기 세분화

from oauth2client.client import OAuth2WebServerFlow 
from oauth2client.tools import run_flow 
from oauth2client.file import Storage 
import requests 
import os 


CLIENT_ID = '9453asfasfaksdfh860b1osoiveogstt.apps.googleusercontent.com' 
CLIENT_SECRET = '6gRid8wF7TW8asdfasdftX' 

def get_new_token(): 
    flow = OAuth2WebServerFlow(client_id=CLIENT_ID, 
           client_secret=CLIENT_SECRET, 
           scope='https://www.googleapis.com/auth/admin.directory.user https://www.googleapis.com/auth/admin.directory.user.readonly', 
           redirect_uri='http://example.com/auth_return') 
    storage = Storage('creds.data') #token details stored here 
    credentials = run_flow(flow, storage) 
    tokenhere=credentials.access_token #tokens generated 
    return tokenhere 

def retrieve_saved_token(): 
    if os.path.exists('creds.data'): 
     with open('creds.data') as creds: 
      tokenhere = creds.read() # Change to reflect how the token data is reflected in your 'creds.data' file 
    return tokenhere 

def request_page(tokenhere): 
    r = requests.get("https://www.googleapis.com/admin/directory/v1/users?domain=mydomain.com", 
        headers={'Authorization': 'Bearer {token}'.format(token=tokenhere)}) 
    result = r.json() 

try: 
    tokenhere = retrieve_saved_token() 
    request_page(tokenhere) 
except: 
    tokenhere = get_new_token() 
    request_page(tokenhere) 

내가 (SECURITY) 기능을 비활성화로 논리를 이동 그냥 더 객체 지향 할

을 수행 있었는지의 모든 구성 요소 : 당신이 찾고있는 할 것 이온 :

def retrieve_saved_token(): 
    if os.path.exists('creds.data'): 
     with open('creds.data') as creds: 
      tokenhere = creds.read() # Change to reflect how the token data is reflected in your 'creds.data' file 
    return tokenhere 

마지막으로 우리는 논리가 실제로 실행되는 부분에 도착 :

def get_new_token(): 
    flow = OAuth2WebServerFlow(client_id=CLIENT_ID, 
           client_secret=CLIENT_SECRET, 
           scope='https://www.googleapis.com/auth/admin.directory.user https://www.googleapis.com/auth/admin.directory.user.readonly', 
           redirect_uri='http://example.com/auth_return') 
    storage = Storage('creds.data') #token details stored here 
    credentials = run_flow(flow, storage) 
    tokenhere=credentials.access_token #tokens generated 
    return tokenhere 

def request_page(tokenhere): 
    r = requests.get("https://www.googleapis.com/admin/directory/v1/users?domain=mydomain.com", 
        headers={'Authorization': 'Bearer {token}'.format(token=tokenhere)}) 
    result = r.json() 

은 또한 토큰 파일이 존재하는 경우 저장된 토큰을 검색하기 위해 새로운 기능을 추가했습니다.

먼저 파일에서 토큰을 검색하려고 시도합니다. 파일이 존재하지 않으면 예외가 발생하고 예외 논리에 도달하게됩니다. try 논리가 쓰여지는 방식은 그것이 성공적으로 토큰을 검색하는 경우에도 catch되지만 해당 토큰이 만료되면 요청 논리가 예외를 발생시켜야합니다. 예외 논리에서

그렇습니다 나는 당신이 단지 원하지 않는다고 가정하고 1

그 토큰

try: 
    tokenhere = retrieve_saved_token() 
    request_page(tokenhere) 
except: 
    tokenhere = get_new_token() 
    request_page(tokenhere) 

EDIT로 페이지를 새로운 토큰을 받고 요청의 원래 논리 페이지를 요청할뿐만 아니라 페이지의 데이터를 조작 할 수도 있습니다. 그렇게하기 위해 여러분은 생성 한 json 객체 'result'에서 태그를 찾아 페이지에서 데이터를 가져 오는 또 다른 함수를 사용할 수 있습니다. 아래 코드에서이 함수를 'do_something_with_request_function()'이라고 부릅니다.

첫 번째 시도/예외는 토큰 파일이 있는지 확인한 다음 토큰 파일을 가져 와서 사용하면 토큰 파일을 사용하고 사용하지 않으면 새 토큰을 생성합니다.

만료 된 토큰을 전달할 기회가있는 경우를 제외하고 두 번째 시도가 있습니다. 그래서 두 가지 시나리오를 가정 해 보겠습니다.
시나리오 1 : 유효한 토큰을 전달하면 요청에 필요한 페이지가 나타납니다.페이지의 데이터를 구문 분석하는 데 사용하는 메소드는 해당 페이지에있는 특정 필드를 찾으며 모든 것이 올바르게 작동합니다.
시나리오 2 : 유효하지 않은 토큰을 전달하면 만료/유효하지 않은 토큰에 대한 오류 페이지가 표시됩니다. 해당 페이지를 json으로 구문 분석하고 데이터 조작을 시도하는 메소드는 실제 페이지에 정상적으로 존재하는 값을 찾지 못하면 오류가 발생합니다. 이렇게하면 코드가 except 블록으로 건너 뛸 수 있습니다.
except 블록은 새 토큰을 생성하고이를 전달하여 페이지를 다시 요청하고 데이터를 올바르게 처리합니다.

try: 
    tokenhere = retrieve_saved_token() 
except: 
    tokenhere = get_new_token() 
try: 
    request_page(tokenhere) 
    do_something_with_request_function(result) 
except: 
    tokenhere = get_new_token() 
    request_page(tokenhere) 
    do_something_with_request_function(result) 
+0

그래서 저장된 위치에서 토큰을 가져 오는 것이 좋습니다. 그러나 토큰에 대해서는 어떻게 처리 할 것인가, 그 일을 처리 할 수있는 방법은 무엇입니까? –

+0

논평을 통해 논리를 변경했습니다. 새 코드는 ** EDIT 1 **에 나열됩니다. 이것은 토큰이 만료되는 시나리오를 처리해야합니다. – HackerShark

+0

이것으로 우리는 재 인증해야합니다. 새로 고침 토큰을 사용하지 않으면 새로운 토큰을 생성한다는 것은 사용자가 한번 재 인증 한 것을 의미합니다. 오른쪽 –