swagger-api / swagger-codegen

swagger-codegen contains a template-driven engine to generate documentation, API clients and server stubs in different languages by parsing your OpenAPI / Swagger definition.
http://swagger.io
Apache License 2.0
16.94k stars 6.03k forks source link

How to properly initialize Connexion and SQLAlchemy in Flask generated __main__.py #7307

Open jcantu-usgs opened 6 years ago

jcantu-usgs commented 6 years ago
Description

So far I have had absolutely no success in getting SQLAlchemy to work properly with your Flask generated code. Can someone tell me what the appropriate __main__.py initialization code would look like for using SQLAlchemy along with Connexion in your generated code? I've also scoured the internet trying to find a project using your generated Flask code with SQLAlchemy and I haven't found anything resembling your project structure.

Swagger-codegen version

2.0

Related issues/PRs

https://github.com/zalando/connexion/issues/557#issuecomment-354974644

wing328 commented 6 years ago

cc @taxpon @frol @mbohlool @cbornet @kenjones-cisco

mdhedley commented 6 years ago

Not sure if I understand this correctly, but I just wrestled with something similar last night, and was able to get it figured out. You can use the flask-sqlalchemy extension to handle sqlalchemy for you, and then you can simply initialize it with SQLAlchemy(app.app) in your main. If you're keeping your models outside of main, then you need to follow the instructions here: https://stackoverflow.com/questions/9692962/flask-sqlalchemy-import-context-issue/9695045#9695045

Again you need to referrence app.app, the flask app, in the init. I can write a simple blogpost on this topic, and put a simple sample out if that would help, if there's a more formal documentation location for this let me know and I'd be happy to fill it in.

wing328 commented 6 years ago

@mdhedley I think your instruction is pretty good as a starting point. If more users still have questions, we can add more instruction to the wiki page (e.g. faq): https://github.com/swagger-api/swagger-codegen/wiki

wiwengweng commented 5 years ago

Not sure if I understand this correctly, but I just wrestled with something similar last night, and was able to get it figured out. You can use the flask-sqlalchemy extension to handle sqlalchemy for you, and then you can simply initialize it with SQLAlchemy(app.app) in your main. If you're keeping your models outside of main, then you need to follow the instructions here: https://stackoverflow.com/questions/9692962/flask-sqlalchemy-import-context-issue/9695045#9695045

Again you need to referrence app.app, the flask app, in the init. I can write a simple blogpost on this topic, and put a simple sample out if that would help, if there's a more formal documentation location for this let me know and I'd be happy to fill it in.

such a great idea, :D and I am recently getting in touch with swagger-codegen, and also thinking about this. The data model in generated python code is something like 'swagger data model', that is all about 'get/set' method. I don't know need to rewrite some code, to accept SQLAlchemy as a data model?? I hope someone are still fighting for this, or any other solutions??

nicop311 commented 3 years ago

Should I use swagger-codegen, is this reliable? Should I use FastAPI instead of what swagger-codegen generates for Python server?

Like the original author, I don't understand how to use python-flask-SQLAlchemy with the source code "boilerplate server stub" generated by swagger-codegen and which uses Python-flask + zalando/connexion for server.

I cannot find example of swagger-codegen python server with a database, even the swagger-codegen petstore python-flask example does not use a DB.

For python-zalando-connexion and integration with DB and SQLAlchemy ORM , I found this but it does not use the swagger-codegen python directory structure: connexion/examples/openapi3/sqlalchemy/

Here is what I wanted to achieve:

But after a few days of struggling with this, I am now wondering if swagger-codegen is a relevant and reliable tool to use?? Or if I should do everything by hand, and maybe even switch to FastAPI instead ?

My source of inspiration

For the Python-flask and SQLAlchemy best practices, I was inspired by tutorials like this. But they do not follow the swagger-codegen structure :

I think that by following these tutorials, I implemented most of what @mdhedley suggested in the above post above.

But I am still struggling with the way swagger-codegen handles models, and how I could use the base_models_.py from swagger-codegen which defines its own class Model(object):.

The following is my Flask/Connexion App factory code. It is not working with the DB and SQLAlchemy right now.

#!/usr/bin/env python3
import connexion
from flask_sqlalchemy import SQLAlchemy
from my_api.config import Config

# Create the SQLAlchemy db instance
db = SQLAlchemy()

def init_app():
    """Initialize the core application.

    Use zalando/connexion to read OpenAPI/Swagger file.

    Return: A Flask Application Instance.
    """
    # Create the connexion (OpenAPI) application instance
    connex_app = connexion.App(__name__, specification_dir='./swagger/')
    app = connex_app.app
    app.json_encoder = encoder.JSONEncoder
    app.config.from_object(Config)

    # Initialize Plugins
    db.init_app(app)

    connex_app.add_api('swagger.yaml',
                arguments={'title': 'My API'}, 
                pythonic_params=True,
                options=options)

    # This part does not work for the moment. The db creation fails.
    with app.app_context(): # Should this be the connexion or flask app instance ?
        db.create_all()    
        return app

I need to understand how to use base_model_ the base model class.

# file my_api.application.models.base_model_.py
class Model(object):
# An ORM model for an SQL table "domains":
from my_api.application.models.base_model_ import Model
class Domain(Model):

Instead of class Domain(my_api.application.models.base_model_.Model): I should refer somewhere to my DB object db = SQLAlchemy().

Some thoughs about python being the problem rather than swagger-codegen

Maybe the swagger-codegen python server stub is not the best to achieve creating a CRUD API with a database. But I can not choose which other language supported by swagger-codegen is the most relevant for my needs.