luolingchun / flask-openapi3

Generate REST API and OpenAPI documentation for your Flask project.
https://luolingchun.github.io/flask-openapi3/
MIT License
182 stars 28 forks source link

How to use flask-openapi3 in existing projects based on flask? #163

Open Xyc2016 opened 1 month ago

Xyc2016 commented 1 month ago

I want to use flask-openapi3 in our large and old project based on flask. But it's difficult to migrate the whole project from flask to flask-openapi3. What can I do?

luolingchun commented 1 month ago

I have the following suggestions:

  1. Upgrade Flask to 2.x, Flask-OpenAPI3 no longer supports Flask versions below 2.x.

  2. Use app = OpenAPI(__name__) instead of app = Flask(__name__).

  3. Upgrade modules or APIs incrementally, Flask-OpenAPI3 allows you to coexist Blueprint and APIBlueprint classes, enabling you to upgrade modules or APIs one at a time.

Example code with recommended changes:

app = OpenAPI(__name__)

__version__ = "/v1"
__bp__ = "/admin"
url_prefix = API_PREFIX + __version__ + __bp__
tag = Tag(name="模块1", description="模块1")

bp_admin=Blueprint('admin',__name__)
+api = APIBlueprint(__bp__, __name__, url_prefix=url_prefix, abp_tags=[tag], abp_security=JWT)

@bp_admin.route("/api1", methods=["GET"])
def get_api1():
  ...

-@bp_admin.route("/api2", methods=["GET"])
-def get_api2():
-  ...

+@api.get("/api2")
+def get_api2():
+  ...

app.register_blueprint(bp_admin)
+app.register_api(api)
Xyc2016 commented 1 week ago

谢谢。这个方法很好。 flask-openapi3会一直兼容flask的API吗? 如果是,那我们的旧代码里的flask的相关的代码都一直可以正常工作,也不需要升级到APIBlueprint ,可以和APIBlueprint 一直共存。只有极少代码需要改动,很方便。

luolingchun commented 1 week ago

会的,flask-openapi3继承了Flask的所有功能,理论上完全兼容Flask以及Flask的相关插件