3
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

pythonでswagger-codegenしてImportError: No module namedが出た時の対処法

Posted at

背景

swagger-codegenは、特定のフォーマットでAPIを定義すると、
それを叩くためのライブラリをいろんな言語で吐き出してくれるというものです。

RailsのGrapeなんかと相性が良くて、自分もRailsで作ったAPIサーバーを、pythonから叩こうとしたら本題、という感じです。

問題点

swagger-codegenのコードを読めばわかるのですが、
ファイルを生成する時に、本来ファイル名がapi_v1_nameとならなければいけないところが、api::v1::nameのまま生成されてしまい、ファイル名と、importで指定しているpathがうまくかみ合っていません。そのため ImportErrorが出てしまいます。
ちょっとしたミスなのですぐにfixされると思いますが、今すぐ通信できるようにしたいですよね。

対処法

というわけで、関数をoverrideして解決してしまいましょう。
overrideについては「こんなに簡単! Swagger Codegenのカスタマイズ」がとても参考になりました。

custom-script.groovy
@Grab('io.swagger:swagger-codegen-cli:2.1.4')
import io.swagger.codegen.*;
import io.swagger.codegen.languages.*;

class MyPythonClientGen extends PythonClientCodegen {

  @Override
  public String toModelFilename(String name){
    return toVarName(name)
  }

  // CLIへののkick
  public static main(String[] args) {
    SwaggerCodegen.main(args)
  }

}
groovy custom-script.groovy generate -i http://example.com/api/v1/swagger_doc -l MyPythonClientGen -o ./api/ 

これで、
ファイルがapi::v1::nameという名前でなく、api_v1_nameで生成されるようになりました。面倒くさいという方は、手作業でファイル名を直してもいいかもしれませんね。

3
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?