Существует ли особый синтаксис для использования python относительного импорта наряду с подключением? - PullRequest
2 голосов
/ 29 января 2020

В настоящее время я пытаюсь создать API-интерфейс с использованием ConneX. Однако у меня возникают некоторые проблемы при использовании относительного импорта локальных модулей через модуль подключения, который изменяет базовое приложение flask. Вот упрощенный обзор моей файловой структуры:

  • hall_of_fame_api
    • контроллер
      • ____ init____.py
      • rout.py
    • модель
      • ____ init____.py
      • rout.py
    • ____ init____.py
    • config.py
    • create_db.py
    • swagger.yml

Я получаю сообщение об ошибке при попытке запустить python config.py 'в моем терминале. Вот config.py:

import os
import connexion
from flask_sqlalchemy import SQLAlchemy
from flask_marshmallow import Marshmallow

basedir = os.path.abspath(os.path.dirname(__file__))

# Create the Connexion application instance
connex_app = connexion.App(__name__, specification_dir=basedir)

# Get the underlying Flask app instance
app = connex_app.app
connex_app.add_api('swagger.yml')

# Configure the SQLAlchemy part of the app instance
app.config['SQLALCHEMY_ECHO'] = True
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://doadmin:password@nba-player-db-do-user-7027314-0.db.ondigitalocean.com:25060/nba_test_1?sslmode=require'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

# Create the SQLAlchemy db instance
db = SQLAlchemy(app)

# Initialize Marshmallow
ma = Marshmallow(app)

И вот ошибка, которую она выдает:

Failed to add operation for GET /api/players
Failed to add operation for GET /api/players
Traceback (most recent call last):
  File "/usr/local/lib/python3.7/site-packages/connexion/apis/abstract.py", line 209, in add_paths
self.add_operation(path, method)
  File "/usr/local/lib/python3.7/site-packages/connexion/apis/abstract.py", line 173, in add_operation
    pass_context_arg_name=self.pass_context_arg_name
  File "/usr/local/lib/python3.7/site-packages/connexion/operations/__init__.py", line 8, in make_operation
    return spec.operation_cls.from_spec(spec, *args, **kwargs)
  File "/usr/local/lib/python3.7/site-packages/connexion/operations/swagger2.py", line 137, in from_spec
    **kwargs
  File "/usr/local/lib/python3.7/site-packages/connexion/operations/swagger2.py", line 96, in __init__
    pass_context_arg_name=pass_context_arg_name
  File "/usr/local/lib/python3.7/site-packages/connexion/operations/abstract.py", line 96, in __init__
    self._resolution = resolver.resolve(self)
  File "/usr/local/lib/python3.7/site-packages/connexion/resolver.py", line 40, in resolve
    return Resolution(self.resolve_function_from_operation_id(operation_id), operation_id)
  File "/usr/local/lib/python3.7/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 'controller.routes' has no attribute 'read_all'>

Эта ошибка происходит именно из строки 12, где connexion пытается добавить файл swagger.yml , вот что для справки:

swagger: "2.0"
info:
  description: This is the swagger file that goes with our server code
  version: "1.0.0"
  title: Swagger REST Article
consumes:
  - "application/json"
produces:
  - "application/json"

basePath: "/api"

# Paths supported by the server application
paths:
  /players:
    get:
      operationId: "controller.routes.read_all"
      tags:
        - "People"
      summary: "The people data structure supported by the server application"
      description: "Read the list of people"
      responses:
        200:
          description: "Successful read people list operation"
          schema:
            type: "array"
            items:
              properties:
                fname:
                  type: "string"
                lname:
                  type: "string"
                timestamp:
                  type: "string"

Теперь вот где я запутался, потому что в моем файле rout.py есть функция, определенная как read_all (), вот этот файл:

from model.models import Regseason, RegSchema, Playoffs, PlayoffSchema

def read_all():

    return Regseason.query.all()

Я ломал голову над этой ошибкой в ​​течение почти 24 часов, любое руководство будет с благодарностью. Заранее спасибо!

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...