【问题标题】:Problems with __future__ and swagger_client in PythonPython 中 __future__ 和 swagger_client 的问题
【发布时间】:2018-11-08 21:44:23
【问题描述】:

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 开发人员,我只是第一次看到这个,所以这甚至可能是一个准确的解释。
  • 在 Python 3 中不需要 from __future__ ...。请参阅 how to use from __future__ import print_function
  • 即使我对此发表评论,我也会得到import swagger_client ModuleNotFoundError: No module named 'swagger_client'

标签: python python-3.x swagger python-import strava


【解决方案1】:

1) 第一行有错别字

from __future__ import print_statement
                             ^^^

应该是

from __future__ import print_function

但由于您使用的是 Python 3,因此您实际上并不需要此导入 - 有关详细信息,请参阅 this Q&A

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

  • 将 Strava OpenAPI 定义粘贴到 https://editor.swagger.io 并选择 Generate Client > Python
  • 安装Swagger Codegencommand-line version并运行:

    # 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
    

【讨论】:

  • 作为旁注。该功能被命名为print_function 而不是print_statement。你仍然可以在 python3.x 中导入print_function
  • @MegaIng 谢谢。看起来import print_statement 是 Codegen 生成的示例中的拼写错误 - github.com/swagger-api/swagger-codegen/issues/5692
  • 好的,所以我尽可能按照上面的说明进行操作。最后得到一个名为 SwaggerPythonClient 的文件夹,其中包含一个 swagger_client 文件夹,其中包含 configuration.py 和 rest.py 所以我将内容复制到我的程序目录中。导入错误现在已经消失,但现在我发现了其他问题。如果需要,我可以进行调查并可能会发布一个新问题,但我想在继续之前检查我所做的是否正确。
  • 对于我的上述情况,我最终安装了几个缺少的软件包。我的应用程序现在可以运行了。
  • 我也在努力入门...您愿意解释一下您还安装了哪些缺少的软件包吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-10-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多