【问题标题】:How to access authentication by Strava API using Python?如何使用 Python 通过 Strava API 访问身份验证?
【发布时间】:2020-07-07 11:00:40
【问题描述】:

我正在启动一个小型 python 脚本(不是应用程序),只要在所需文件夹中创建我的 *.fit 活动文件,就可以将它们上传到 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 和其他人开发的几个源代码(例如toravir's "rk2s (RunKeeper 2 Strava)" project on GitHub)。我抓住了一些像stravalib、swagger_client、request、json等python模块以及像OAuth2这样的概念可能与step2有关> 但我还是不能把所有东西放在一起......

有经验的可以给我一些关于step2实现的建议吗?或者任何相关的读数都是完美的!

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

提前非常感谢你:)

【问题讨论】:

    标签: python api oauth-2.0 access-token strava


    【解决方案1】:

    我认为您需要使用 OAuth 进行身份验证才能上传您的活动,这几乎需要您有一个 Web 服务器设置,Strava 可以在您“授权”后发回该服务器。我只是使用 Rails 和 Heroku 设置了身份验证部分。

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

    【讨论】:

      【解决方案2】:

      实际上,如果您转到API Settings,您可以在那里获取您的访问令牌并刷新令牌。我还会查看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()
      

      您可能需要进一步挖掘该库以找出上传片段。

      【讨论】:

        【解决方案3】:

        这是有关如何访问 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
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-04-29
          • 1970-01-01
          • 1970-01-01
          • 2013-02-09
          • 1970-01-01
          相关资源
          最近更新 更多