如何使用 Python 通过 Strava API 访问身份验证?

How to access authentication by Strava API using Python?

我正在启动一个小 python 脚本(不是应用程序),只要在所需文件夹中创建我的 *.fit activity 文件,它就可以将它们上传到 Strava 上。

我打算做的主要步骤是:

1. monitor *.fit file system modifications
2. access authentication to Strava to enable my program to upload files
   (This tool will be personal use only, thus I expect no need to authenticate every time uploading)
3. upload the file to my Strava account
4. automatically doing this fixed routine with the help of Windows Task Scheduler
   (For example, there will be 4-5 new riding activities generated in my computer folder, I expect this tool can automatically upload all of them once a week so that I do not need to manually complete the task.)

对于step2,虽然通读了Strava Authentication Documentation and several source codes other peoples have developed (e.g. toravir's "rk2s (RunKeeper 2 Strava)" project on GitHub),但我真的不知道如何实施。我抓住了一些 python 模块,如 stravalib、swagger_client、request、json 等,以及 [=26= 等概念]OAuth2 可能与 step2 有关,但我仍然无法将所有内容放在一起...

哪位有经验的可以给我一些实施step2的建议?或任何相关阅读将是完美的!

对于本项目其他部分的建议也将受到欢迎和赞赏。

非常感谢您:)

我认为您需要使用 OAuth 进行身份验证才能上传您的 activity,这几乎需要您设置一个 Web 服务器设置,Strava 可以 post 在您 [=15] 之后返回=].我只是使用 Rails & Heroku 设置了身份验证部分。

这个 link 有一个很好的流程图,说明了需要发生的事情。 https://developers.strava.com/docs/authentication/

实际上,如果您转到 API Settings you can get your access token and refresh token there. I would also check out the Python Strava Library,但看起来您可以执行以下操作:

from stravalib.client import Client
access_token = 'your_access_token_from_your_api_application_settings_page'
refresh_token = 'your_refresh_token_from_your_api_application_settings_page' 

client = Client()

athlete = client.get_athlete()

您可能需要深入了解该库才能找出上传的片段。

这是有关如何访问 Strava 的代码示例 API,请查看此 gist 或使用以下代码:

import time
import pickle
from fastapi import FastAPI
from fastapi.responses import RedirectResponse
from stravalib.client import Client

CLIENT_ID = 'GET FROM STRAVA API SITE'
CLIENT_SECRET = 'GET FROM STRAVA API SITE'
REDIRECT_URL = 'http://localhost:8000/authorized'

app = FastAPI()
client = Client()

def save_object(obj, filename):
    with open(filename, 'wb') as output:  # Overwrites any existing file.
        pickle.dump(obj, output, pickle.HIGHEST_PROTOCOL)

def load_object(filename):
    with open(filename, 'rb') as input:
        loaded_object = pickle.load(input)
        return loaded_object


def check_token():
    if time.time() > client.token_expires_at:
        refresh_response = client.refresh_access_token(client_id=CLIENT_ID, client_secret=CLIENT_SECRET, refresh_token=client.refresh_token)
        access_token = refresh_response['access_token']
        refresh_token = refresh_response['refresh_token']
        expires_at = refresh_response['expires_at']
        client.access_token = access_token
        client.refresh_token = refresh_token
        client.token_expires_at = expires_at

@app.get("/")
def read_root():
    authorize_url = client.authorization_url(client_id=CLIENT_ID, redirect_uri=REDIRECT_URL)
    return RedirectResponse(authorize_url)


@app.get("/authorized/")
def get_code(state=None, code=None, scope=None):
    token_response = client.exchange_code_for_token(client_id=CLIENT_ID, client_secret=CLIENT_SECRET, code=code)
    access_token = token_response['access_token']
    refresh_token = token_response['refresh_token']
    expires_at = token_response['expires_at']
    client.access_token = access_token
    client.refresh_token = refresh_token
    client.token_expires_at = expires_at
    save_object(client, 'client.pkl')
    return {"state": state, "code": code, "scope": scope}

try:
    client = load_object('client.pkl')
    check_token()
    athlete = client.get_athlete()
    print("For {id}, I now have an access token {token}".format(id=athlete.id, token=client.access_token))

    # To upload an activity
    # client.upload_activity(activity_file, data_type, name=None, description=None, activity_type=None, private=None, external_id=None)
except FileNotFoundError:
    print("No access token stored yet, visit http://localhost:8000/ to get it")
    print("After visiting that url, a pickle file is stored, run this file again to upload your activity")

下载该文件,安装要求,然后运行它(假设文件名为 main):

pip install stravalib
pip install fastapi
pip install uvicorn
uvicorn main:app --reload