from collections import namedtuple
from yaml import safe_load
from uber_rides.client import UberRidesClient
from uber_rides.session import OAuth2Credential
from uber_rides.session import Session
from builtins import input
from yaml import safe_dump
import utils
from example.utils import import_app_credentials
from uber_rides.auth import AuthorizationCodeGrant
from uber_rides.client import UberRidesClient
from uber_rides.errors import ClientError
from uber_rides.errors import ServerError
from uber_rides.errors import UberIllegalState
CREDENTIALS_FILENAME = 'config.rider.yaml'
# where your OAuth 2.0 credentials are stored
STORAGE_FILENAME = 'session_store.yaml'
filename=CREDENTIALS_FILENAME
with open(filename, 'r') as config_file:
config = safe_load(config_file)
client_id = config['client_id']
client_secret = config['client_secret']
redirect_url = config['redirect_url']
credentials = {
'client_id': client_id,
'client_secret': client_secret,
'redirect_url': redirect_url,
'scopes': set(config['scopes']),
}
auth_flow = AuthorizationCodeGrant(
credentials.get('client_id'),
credentials.get('scopes'),
credentials.get('client_secret'),
credentials.get('redirect_url'),
)
auth_url = auth_flow.get_authorization_url()
print(auth_url)
session = auth_flow.get_session("http://127.0.0.1/?state=AWBraIpW7HErfj2pMl0RTV4G1gN93yDN&code=7KyJcFsWk68ZHRjUGuOyR571Y75NPk#_")
client = UberRidesClient(session, sandbox_mode=True)
credential = session.oauth2credential
with open(storage_filename, 'w') as yaml_file:
yaml_file.write(safe_dump(credential, default_flow_style=False))
输出:+++++++ ERROR +++++++++++++++
https://login.uber.com/oauth/v2/authorize?scope=profile+places+request+request_receipt+all_trips+history&state=dO0Lo8gjVuTdIZo6UPIOfFpWKmQ133xu&redirect_uri=http%3A%2F%2F127.0.0.1%2F&response_type=code&client_id=Ws4Za7kSxIdQdpxcZnL2WC9L8NVl3UBT
Traceback (most recent call last):
File "ride.py", line 53, in <module>
session = auth_flow.get_session("http://127.0.0.1/?state=AWBraIpW7HErfj2pMl0RTV4G1gN93yDN&code=7KyJcFsWk68ZHRjUGuOyR571Y75NPk#_")
File "/usr/local/lib/python2.7/dist-packages/uber_rides/auth.py", line 294, in get_session
authorization_code = self._verify_query(query_params)
File "/usr/local/lib/python2.7/dist-packages/uber_rides/auth.py", line 255, in _verify_query
raise UberIllegalState(error_message)
uber_rides.errors.UberIllegalState: CSRF Error. Expected dO0Lo8gjVuTdIZo6UPIOfFpWKmQ133xu, got AWBraIpW7HErfj2pMl0RTV4G1gN93yDN
在这种情况下授权代码和状态代码不匹配,这里是解释...
在.py文件的这一部分中发布授权URL请求时:
auth_url = auth_flow.get_authorization_url()
print(auth_url)
将URL粘贴到浏览器中并手动完成验收。
最近,包含状态代码的响应URL在Python应用程序中是硬编码的,因为它是在.py文件的这一部分中完成的:
session = auth_flow.get_session("http://127.0.0.1/?state=AWBraIpW7HErfj2pMl0RTV4G1gN93yDN&code=7KyJcFsWk68ZHRjUGuOyR571Y75NPk#_")
任何进一步执行的Python应用程序都会发布另一个授权URL的请求,因此状态代码会随之更改。有关将Uber API请求集成到Python代码中的更多信息,请访问here。
您需要找到一种方法来自动执行授权过程并在单个.py代码迭代中传输.get_session url。