1

我想db在应用程序的端点处理程序中访问对象connexion

目前我将它附加到current_appapp.py 中:

import connexion
from flask import current_app
from flask_sqlalchemy import SQLAlchemy


connexion_app = connexion.App(__name__, specification_dir="./")
connexion_app.add_api("swagger.yaml")
db = SQLAlchemy(connexion_app.app)

with connexion_app.app.app_context():
    current_app.db = db


if __name__ == "__main__":
    connexion_app.run(host="0.0.0.0", port=5000, debug=True)

然后在 handlers.py 中访问它

from flask import current_app


def cars():
    data = current_app.db.query(...)
    return data

这是正确的方法还是我应该更喜欢 Flask 的g上下文变量current_app?它们都是上下文变量,但何时使用有点令人困惑。

由于无法from app import db在 handlers.py 中执行

  ...
    connexion_app.add_api("swagger.yaml")
  File "/home/user/.virtualenvs/my_venv/lib/python3.6/site-packages/connexion/apps/flask_app.py", line 54, in add_api
    api = super(FlaskApp, self).add_api(specification, **kwargs)
  File "/home/user/.virtualenvs/my_venv/lib/python3.6/site-packages/connexion/apps/abstract.py", line 155, in add_api
    options=api_options.as_dict())
  File "/home/user/.virtualenvs/my_venv/lib/python3.6/site-packages/connexion/apis/abstract.py", line 108, in __init__
    self.add_paths()
  File "/home/user/.virtualenvs/my_venv/lib/python3.6/site-packages/connexion/apis/abstract.py", line 213, in add_paths
    self._handle_add_operation_error(path, method, err.exc_info)
  File "/home/user/.virtualenvs/my_venv/lib/python3.6/site-packages/connexion/apis/abstract.py", line 227, in _handle_add_operation_error
    six.reraise(*exc_info)
  File "/home/user/.virtualenvs/my_venv/lib/python3.6/site-packages/six.py", line 693, in reraise
    raise value
  File "/home/user/.virtualenvs/my_venv/lib/python3.6/site-packages/connexion/resolver.py", line 61, in resolve_function_from_operation_id
    return self.function_resolver(operation_id)
  File "/home/user/.virtualenvs/my_venv/lib/python3.6/site-packages/connexion/utils.py", line 96, in get_function_from_name
    function = deep_getattr(module, attr_path)
  File "/home/user/.virtualenvs/my_venv/lib/python3.6/site-packages/connexion/utils.py", line 55, in deep_getattr
    return functools.reduce(getattr, attr.split('.'), obj)
AttributeError: module 'api.handlers' has no attribute 'cars'

connexion_app.add_api("swagger.yaml")这可能是由循环依赖或由相关机制触发的那种东西引起的。


这是我swagger.yml的仅供参考。

swagger: "2.0"

info:
  description: my API
  version: "1.0.0"
  title: my API

consumes:
  - application/json
produces:
  - application/json

basePath: /api

paths:
   /cars/:
      get:
        operationId: api.handlers.cars
        responses:
          200:
            description: .
            schema:
              type: object
4

0 回答 0