Использование Falcon с Django ORM - PullRequest
0 голосов
/ 15 марта 2020

Обновление :

Кажется, что это некоторая проблема с sqlite, когда я переключился на локальный сервер Postgresql, все работало как задумано, без каких-либо необходимых изменений.


Я пытаюсь сравнить несколько веб-фреймворков (Falcon / FastAPI, et c ...) с одним требованием, используя ORM Django в качестве нашего метода взаимодействия с наша БД (причина на данный момент не актуальна). В данный момент я сосредотачиваюсь на Falcon, но я уже столкнулся с препятствием.

Я настроил приложение Django для части ORM, но каждый раз, когда я пытаюсь получить доступ модель из приложения Falcon, я получаю ошибку OperationalError('no such table: db_customer').

Таблица (db_customer) есть, и я могу получить к ней доступ через dbshell или python код, который ссылки на мой django файл настроек напрямую через DJANGO_SETTINGS_MODULE.

** Пожалуйста, игнорируйте ошибки логического кода, это просто и быстро, чтобы проверить жизнеспособность и производительность **

Это мой каталог дерево: проект Github

app
 - api/
     - customer_resource.py
 - db/
     - dal/
         - customer_actions.py
     - migrations/
     - apps.py
     - manage.py
     - models.py
     - settings.py
     - sqlite.db
 - main.py

Вот мои файлы:

models.py

import json
import django
django.setup()

from django.db.models import Model, BooleanField, CharField, URLField, DateTimeField


class Customer(Model):
    name = CharField(max_length=100, db_index=True)
    domain = URLField(max_length=255, null=True)
    join_date = DateTimeField(auto_created=True, auto_now_add=True, null=True)
    is_active = BooleanField(default=True)

    def to_dict(self):
        return {
            'id': self.id,
            'name': self.domain,
            'join_date': self.join_date,
            'is_active': self.is_active
        }

    def to_json(self):
        return json.dumps(self.to_dict())

settings.py

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': 'sqlite.db',
    }
}

INSTALLED_APPS = (
    'db.apps.DbConfig',
    )

SECRET_KEY = 'jsd9sdyo78dTQ2G3HL2QMP9qjoj2dodimqpSCDu'

dal / customer_actions.py

from db.models import Customer


def get_customer(**kwargs):
    return Customer.objects.get(**kwargs)


def create_customer(**kwargs):
    customer = Customer(**kwargs)
    customer.save()
    return customer


def update_customer(customer_id, **kwargs):
    Customer.objects.filter(id=customer_id).update(**kwargs)
    return get_customer(customer_id=customer_id)


def delete_customer(customer_id):
    Customer.objects.delete(id=customer_id)

api / customer_resource.py

import falcon as falcon
from db.dal import customer_actions


class CustomerResource:
    def on_get(self, req, resp, customer_id=None):
        resp.status = falcon.HTTP_200
        try:
            customer = customer_actions.get_customer(customer_id=customer_id)
            resp.add_header({'Content-Type': 'application/json'})
            resp.media = customer.to_dict()
        except Exception as e:
            resp.status = falcon.HTTP_500
            resp.media = {"error": str(e)}

    def on_delete(self, req, resp, customer_id=None):
        try:
            customer_actions.delete_customer(customer_id=customer_id)
            resp.media = {"success": True}
        except Exception as e:
            resp.status = falcon.HTTP_500
            resp.media = {"error": str(e)}

    def on_put(self, req, resp, customer_id=None):
        resp.status = falcon.HTTP_200
        try:
            customer_data_to_update = req.media
            customer = customer_actions.update_customer(customer_id, **customer_data_to_update)
            resp.add_header({'Content-Type': 'application/json'})
            resp.media = customer.to_dict()
        except Exception as e:
            print(e)
            resp.status = falcon.HTTP_500
            resp.media = {"error": str(e)}

    def on_post(self, req, resp, customer_id=None):
        resp.status = falcon.HTTP_200
        try:
            customer_data = req.media
            customer = customer_actions.create_customer(**customer_data)
            resp.add_header({'Content-Type': 'application/json'})
            resp.media = customer.to_dict()
        except Exception as e:
            resp.status = falcon.HTTP_500
            resp.media = {"error": str(e)}

main.py

import os

from django.core.wsgi import get_wsgi_application
get_wsgi_application()

from api.customer_resource import CustomerResource
import falcon

app = falcon.API()
app.add_route("/customer", CustomerResource())
app.add_route("/customer/{customer_id}", CustomerResource())


# Normally this would run under gunicorn and not from a python module
# from wsgiref import simple_server
# if __name__ == '__main__':
#     with simple_server.make_server('', os.getenv('PORT', 5000), app) as httpd:
#         httpd.serve_forever()
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...