flask подключение add_api дает ошибку: AttributeError: модуль 'agreement_api.controllers.agreement_controller' не имеет атрибута 'read_agreements' - PullRequest
0 голосов
/ 04 августа 2020

Я играюсь с flask и подключением , чтобы настроить доступ к REST API для моего приложения.

Сценарий № 1: Если я запустил мое приложение с помощью инструмента запуска / отладки Pycharm Все работает нормально (приложение flask запускается, включая API из моего файла agreement_api/openapi/specification.yaml).

Сценарий № 2: Но выполняется python agreement_api/app.py ( основной скрипт, содержащий экземпляр приложения) через терминал выдает ошибку при связывании API спецификации "не существует, но поверьте мне, что это так (потому что сценарий № 1 работает нормально и нет опечаток и т. д. c) Моя структура каталогов следующая:

  • Project
    • соглашение_api
      • контроллеры
        • соглашение_controller.py
      • модели
      • openapi
        • спецификация.yaml
      • app.py
    • Dockerfile
    • Pipfile
    • Лицензия
    • ...

agreement_controller.py

....
def read_agreements():
    agreements = Agreement.query.order_by(Agreement.agreement_status).all()

    agreement_schema = AgreementSchema(many=True)
    return agreement_schema.dump(agreements), 200
....

спецификация.yaml

servers:
  - url: /api
paths:
  /agreement:
    get:
      tags:
        - Agreement
      summary: Read the list of agreements
      description: Read the list of agreements
      x-openapi-router-controller: agreement_api.controllers.agreement_controller
      operationId: read_agreements

app.py


# Get the application instance
_, connexion_app = create_app()

app = connexion_app.app  # Flask instance initialized by Connexion

DB = SQLAlchemy(app)
DB.create_all()

MA = Marshmallow(app)

connexion_app.add_api("specification.yaml")

(То же самое при запуске flask приложение в контейнере Docker.)

Есть ли проблема с моей структурой каталогов или мне не хватает чего-то другого? Раньше я не задавал много вопросов (это должно быть заметно по моей плохой проработке / объяснению / стилю, поэтому не стесняйтесь спрашивать меня любые подробности, если требуется)

, если кого-то интересует трассировка стека ошибок:

Failed to add operation for GET /api/agreement
Failed to add operation for GET /api/agreement
Traceback (most recent call last):
  File "/home/abdullah/.local/share/virtualenvs/user_agreement_flask_api-7tGsycJK/lib/python3.6/site-packages/connexion/apis/abstract.py", line 209, in add_paths
    self.add_operation(path, method)
  File "/home/abdullah/.local/share/virtualenvs/user_agreement_flask_api-7tGsycJK/lib/python3.6/site-packages/connexion/apis/abstract.py", line 173, in add_operation
    pass_context_arg_name=self.pass_context_arg_name
  File "/home/abdullah/.local/share/virtualenvs/user_agreement_flask_api-7tGsycJK/lib/python3.6/site-packages/connexion/operations/__init__.py", line 8, in make_operation
    return spec.operation_cls.from_spec(spec, *args, **kwargs)
  File "/home/abdullah/.local/share/virtualenvs/user_agreement_flask_api-7tGsycJK/lib/python3.6/site-packages/connexion/operations/openapi.py", line 138, in from_spec
    **kwargs
  File "/home/abdullah/.local/share/virtualenvs/user_agreement_flask_api-7tGsycJK/lib/python3.6/site-packages/connexion/operations/openapi.py", line 89, in __init__
    pass_context_arg_name=pass_context_arg_name
  File "/home/abdullah/.local/share/virtualenvs/user_agreement_flask_api-7tGsycJK/lib/python3.6/site-packages/connexion/operations/abstract.py", line 96, in __init__
    self._resolution = resolver.resolve(self)
  File "/home/abdullah/.local/share/virtualenvs/user_agreement_flask_api-7tGsycJK/lib/python3.6/site-packages/connexion/resolver.py", line 40, in resolve
    return Resolution(self.resolve_function_from_operation_id(operation_id), operation_id)
  File "/home/abdullah/.local/share/virtualenvs/user_agreement_flask_api-7tGsycJK/lib/python3.6/site-packages/connexion/resolver.py", line 66, in resolve_function_from_operation_id
    raise ResolverError(str(e), sys.exc_info())
connexion.exceptions.ResolverError: <ResolverError: module 'agreement_api.controllers.agreement_controller' has no attribute 'read_agreements'>

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "agreement_api/app.py", line 62, in <module>
    validator_map={"body": RequestBodyValidator},
  File "/home/abdullah/.local/share/virtualenvs/user_agreement_flask_api-7tGsycJK/lib/python3.6/site-packages/connexion/apps/flask_app.py", line 57, in add_api
    api = super(FlaskApp, self).add_api(specification, **kwargs)
  File "/home/abdullah/.local/share/virtualenvs/user_agreement_flask_api-7tGsycJK/lib/python3.6/site-packages/connexion/apps/abstract.py", line 156, in add_api
    options=api_options.as_dict())
  File "/home/abdullah/.local/share/virtualenvs/user_agreement_flask_api-7tGsycJK/lib/python3.6/site-packages/connexion/apis/abstract.py", line 111, in __init__
    self.add_paths()
  File "/home/abdullah/.local/share/virtualenvs/user_agreement_flask_api-7tGsycJK/lib/python3.6/site-packages/connexion/apis/abstract.py", line 216, in add_paths
    self._handle_add_operation_error(path, method, err.exc_info)
  File "/home/abdullah/.local/share/virtualenvs/user_agreement_flask_api-7tGsycJK/lib/python3.6/site-packages/connexion/apis/abstract.py", line 231, in _handle_add_operation_error
    raise value.with_traceback(traceback)
  File "/home/abdullah/.local/share/virtualenvs/user_agreement_flask_api-7tGsycJK/lib/python3.6/site-packages/connexion/resolver.py", line 61, in resolve_function_from_operation_id
    return self.function_resolver(operation_id)
  File "/home/abdullah/.local/share/virtualenvs/user_agreement_flask_api-7tGsycJK/lib/python3.6/site-packages/connexion/utils.py", line 111, in get_function_from_name
    module = importlib.import_module(module_name)
  File "/usr/lib/python3.6/importlib/__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 994, in _gcd_import
  File "<frozen importlib._bootstrap>", line 971, in _find_and_load
  File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 665, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 678, in exec_module
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
  File "/home/abdullah/Documents/projects/mine/user_agreement_flask_api/agreement_api/controllers/agreement_controller.py", line 3, in <module>
    from agreement_api.app import DB
  File "/home/abdullah/Documents/projects/mine/user_agreement_flask_api/agreement_api/app.py", line 62, in <module>
    validator_map={"body": RequestBodyValidator},
  File "/home/abdullah/.local/share/virtualenvs/user_agreement_flask_api-7tGsycJK/lib/python3.6/site-packages/connexion/apps/flask_app.py", line 57, in add_api
    api = super(FlaskApp, self).add_api(specification, **kwargs)
  File "/home/abdullah/.local/share/virtualenvs/user_agreement_flask_api-7tGsycJK/lib/python3.6/site-packages/connexion/apps/abstract.py", line 156, in add_api
    options=api_options.as_dict())
  File "/home/abdullah/.local/share/virtualenvs/user_agreement_flask_api-7tGsycJK/lib/python3.6/site-packages/connexion/apis/abstract.py", line 111, in __init__
    self.add_paths()
  File "/home/abdullah/.local/share/virtualenvs/user_agreement_flask_api-7tGsycJK/lib/python3.6/site-packages/connexion/apis/abstract.py", line 216, in add_paths
    self._handle_add_operation_error(path, method, err.exc_info)
  File "/home/abdullah/.local/share/virtualenvs/user_agreement_flask_api-7tGsycJK/lib/python3.6/site-packages/connexion/apis/abstract.py", line 231, in _handle_add_operation_error
    raise value.with_traceback(traceback)
  File "/home/abdullah/.local/share/virtualenvs/user_agreement_flask_api-7tGsycJK/lib/python3.6/site-packages/connexion/resolver.py", line 61, in resolve_function_from_operation_id
    return self.function_resolver(operation_id)
  File "/home/abdullah/.local/share/virtualenvs/user_agreement_flask_api-7tGsycJK/lib/python3.6/site-packages/connexion/utils.py", line 120, in get_function_from_name
    function = deep_getattr(module, attr_path)
  File "/home/abdullah/.local/share/virtualenvs/user_agreement_flask_api-7tGsycJK/lib/python3.6/site-packages/connexion/utils.py", line 68, in deep_getattr
    return functools.reduce(getattr, attrs, obj)
AttributeError: module 'agreement_api.controllers.agreement_controller' has no attribute 'read_agreements'
  

1 Ответ

0 голосов
/ 05 августа 2020

Получил решение самостоятельно ...

На самом деле мне просто нужно выполнить правильную команду, как указано здесь ...

т.е. вместо выполнения python app.py, мне нужно запустить flask run и моя проблема решена.

...