首先,我不是一個Python大師,因爲你可能會告訴...所以我們走吧。使用python請求訪問ASANA數據
我想使用Asana的API來拉取數據與Python請求(項目,任務等),並使用Oauth 2.0進行身份驗證...我一直在試圖找到一個簡單的Python腳本來有東西從開始,但我沒有運氣,我找不到一個體面和簡單的例子!
我已經創建了應用程序並獲得了我的client_secret和client_secret。但我真的不知道在哪裏或如何開始...有人可以幫我嗎?
import sys, os, requests
sys.path.append(os.path.dirname(os.path.dirname(__file__)))
import asana
import json
from six import print_
import requests_oauthlib
from requests_oauthlib import OAuth2Session
client_id=os.environ['ASANA_CLIENT_ID'],
client_secret=os.environ['ASANA_CLIENT_SECRET'],
# this special redirect URI will prompt the user to copy/paste the code.
# useful for command line scripts and other non-web apps
redirect_uri='urn:ietf:wg:oauth:2.0:oob'
if 'ASANA_CLIENT_ID' in os.environ:
#Creates a client with previously obtained Oauth credentials#
client = asana.Client.oauth(
#Asana Client ID and Secret, set as a Windows environments to avoid hardcoding variables into the script#
client_id=os.environ['ASANA_CLIENT_ID'],
client_secret=os.environ['ASANA_CLIENT_SECRET'],
# this special redirect URI will prompt the user to copy/paste the code.
# useful for command line scripts and other non-web apps
redirect_uri='urn:ietf:wg:oauth:2.0:oob'
)
print ("authorized=", client.session.authorized)
# get an authorization URL:
(url, state) = client.session.authorization_url()
try:
# in a web app you'd redirect the user to this URL when they take action to
# login with Asana or connect their account to Asana
import webbrowser
webbrowser.open(url)
except Exception as e:
print_("Open the following URL in a browser to authorize:")
print_(url)
print_("Copy and paste the returned code from the browser and press enter:")
code = sys.stdin.readline().strip()
# exchange the code for a bearer token
token = client.session.fetch_token(code=code)
#print_("token=", json.dumps(token))
print_("authorized=", client.session.authorized)
me = client.users.me()
print "Hello " + me['name'] + "\n"
params = {'client_id' : client_id, 'redirect_uri' : redirect_uri, 'response_type' : token,}
print_("*************** Request begings *******************"+"\n")
print_("r = requests.get('https://app.asana.com/api/1.0/users/me)" + "\n")
r = requests.get('https://app.asana.com/api/1.0/users/me', params)
print_(r)
print_(r.json)
print_(r.encoding)
workspace_id = me['workspaces'][0]['id']
print_("My workspace ID is" + "\n")
print_(workspace_id)
print_(client.options)
我不確定如何在Asana中使用請求庫。他們的python文檔沒有幫助我。我試圖拉出可用的項目和它們的代碼顏色,以便稍後將它們繪製到Web瀏覽器中(對於不同項目及其各自顏色的高級視圖 - 綠色,黃色或紅色)
當我在瀏覽器中引入了url(https://app.asana.com/api/1.0/users/me),它給了我一個關於數據的json響應,但是當我試圖對腳本做同樣的處理時,它會給我一個401(未授權)響應。
有人知道我在想什麼/做錯了嗎?
謝謝!!!
我看到你使用asana oauth庫。但不是來自requests-oauthlib庫的OAuth2Session。我想你應該按照這裏給出的例子 - https://requests-oauthlib.readthedocs.io/en/latest/oauth2_workflow.html#backend-application-flow – iamkhush