Python中的__future__和swagger_client存在问题

5
Strava API文档提供了以下示例代码,我复制并输入了自己的访问令牌和俱乐部ID:
from __future__ import print_statement
import time
import swagger_client
from swagger_client.rest import ApiException
from pprint import pprint

# Configure OAuth2 access token for authorization: strava_oauth
swagger_client.configuration.access_token = 'MY_ACCESS_TOKEN'

# create an instance of the API class
api_instance = swagger_client.ClubsApi()
id = MY_CLUB_ID # Integer | The identifier of the club.
page = 56 # Integer | Page number. (optional)
perPage = 56 # Integer | Number of items per page. Defaults to 30.     (optional) (default to 30)

try:
    # List Club Activities
    api_response = api_instance.getClubActivitiesById(id, page=page, perPage=perPage)
    pprint(api_response)
except ApiException as e:
    print("Exception when calling ClubsApi->getClubActivitiesById: %s\n" % e)

我尝试运行它,但是出现了错误:

from __future__ import print_statement
SyntaxError: future feature print_statement is not defined

我也发现在导入swagger_client时会遇到同样的问题。我尝试为每个软件包安装程序,但没有任何改变。我看到对于__future__,我应该使用> Python 2.7,但我目前使用的是3.6。

我该如何解决这个问题?


好问题。说实话,我不完全确定它是什么,但我猜它包含的软件包在当前的Python版本中不存在,但将来的版本中会有。我不是Python开发人员,第一次看到这个,所以这可能甚至不是一个准确的解释。 - runnerpaul
在Python 3中,您不需要使用from __future__ ...。请参阅如何使用from __future__ import print_function - Helen
即使我将其注释掉,我仍然会得到以下错误信息import swagger_client ModuleNotFoundError: 找不到名为'swagger_client'的模块 - runnerpaul
1个回答

8

1) 第一行有一个错误。

from __future__ import print_statement
                             ^^^

应该是这样的

from __future__ import print_function

但是,由于你正在使用Python 3,你实际上不需要这个import - 关于详情,请参阅这个Q&A

2) swagger_client 可能是从Strava OpenAPI定义生成的Python客户端。看起来你需要使用Swagger Codegen手动生成它。有几种方法可以做到这一点:

  • Paste the Strava OpenAPI definition into https://editor.swagger.io and select Generate Client > Python.
  • Install the command-line version of Swagger Codegen and run:

    # Windows
    java -jar swagger-codegen-cli-<ver>.jar generate -i https://developers.strava.com/swagger/swagger.json -l python -o ./StravaPythonClient
    
    # Mac
    swagger-codegen generate -i https://developers.strava.com/swagger/swagger.json -l python -o ./StravaPythonClient
    

1
顺便提一下,该功能被命名为“print_function”,而不是“print_statement”。您仍然可以在Python3.x中导入“print_function”。 - MegaIng
@MegaIng 谢谢。看起来 import print_statement 是 Codegen 生成的示例中的一个打字错误 - https://github.com/swagger-api/swagger-codegen/issues/5692。 - Helen
好的,我尽力按照上面的指示操作了。最终得到了一个名为SwaggerPythonClient的文件夹,其中包含一个swagger_client文件夹,里面有configuration.py和rest.py文件,所以我将它们的内容复制到了我的程序目录中。导入错误现在已经消失,但是我发现了其他问题。如果需要,我可以进行调查并发布一个新的问题,但在继续之前想确认一下我所做的是否正确。 - runnerpaul
针对我的问题,我最终安装了几个缺失的软件包。现在我的应用程序可以正常工作了。 - runnerpaul
我也在开始时遇到了困难...你能否解释一下你安装了哪些缺失的包? - LittleNose

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接