Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

models.py and documents.py expand #56

Merged
merged 13 commits into from
Sep 8, 2023
5 changes: 5 additions & 0 deletions api/documents.py
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,11 @@ class Django:
'name',
'birthday',
'content',
'size',
'weight',
'gender',
'is_neutered',
'rer'
]


Expand Down
15 changes: 15 additions & 0 deletions api/management/commands/callback/recordCallBack.py
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

不建議去直接 Raise Exception (Exception 太泛用對於程式來說太過於籠統) 後續要製作處理 Exception 的 Handler 會成為技術負債

Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

這個我改就好 只是跟你說一下

Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,12 @@ def temperatureAndHumidityCallBack(topic: str, body: str, ch=None, method=None,
logger.info("[Humidity] Received " + str(data["Humidity"]))
# ch.basic_ack(delivery_tag=method.delivery_tag)
# machine = models.Machine.objects.get(name=data["machineId"])

# Check for abnormal temperature
temperature = float(data["Temperature"])
if temperature > 27 or temperature < 20:
raise Exception("溫度異常")

try:
machine = models.Machine.objects.get(name=topic.split("/")[1])
except models.Machine.DoesNotExist:
Expand All @@ -44,10 +50,19 @@ def temperatureAndHumidityCallBack(topic: str, body: str, ch=None, method=None,
def weightCallBack(topic: str, body: str, ch=None, method=None, properties=None):
data = json.loads(body)
logger.info("[Weight] Received " + str(data["Weight"]))

weight = float(data["Weight"])
if weight < 0:
raise Exception("進食問題")

# ch.basic_ack(delivery_tag=method.delivery_tag)


def waterCallBack(topic: str, body: str, ch=None, method=None, properties=None):
data = json.loads(body)
logger.info("[Water] Received " + str(data["Water"]))

water = float(data["Water"])
if water < 0:
raise Exception("攝取水量問題")
# ch.basic_ack(delivery_tag=method.delivery_tag)
6 changes: 5 additions & 1 deletion api/management/commands/recordListener.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
from django.core.management.base import BaseCommand
from PetMonitoringSystemBackend.settings import RABBITMQ_CONFIG
from api.management.commands.callback import recordCallBack, machineCallBack
from api.models import Pet


class Command(BaseCommand):
def handle(self, *args, **options):
from api.utils.Rabbitmqserver import RabbitmqServer
from api.management.commands.callback import recordCallBack,machineCallBack
from api.management.commands.callback import recordCallBack, machineCallBack
if RABBITMQ_CONFIG["enable"]:
rabbitmqClient = RabbitmqServer(
username=RABBITMQ_CONFIG["username"],
Expand All @@ -16,10 +18,12 @@ def handle(self, *args, **options):
)

rabbitmqClient.connect()

# Listen Record
rabbitmqClient.expense("distance/#", recordCallBack.distanceCallBack)
rabbitmqClient.expense("temperature/#", recordCallBack.temperatureAndHumidityCallBack)
rabbitmqClient.expense("weight/#", recordCallBack.weightCallBack)
rabbitmqClient.expense("water/#", recordCallBack.waterCallBack)
# Listen Machine
rabbitmqClient.expense("machine/status/#", machineCallBack.machineCallBack)

12 changes: 12 additions & 0 deletions api/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,11 +18,22 @@ def __str__(self):


class Pet(models.Model):
GENDER_CHOICES = [
('male', 'Male'),
('female', 'Female'),
('unknown', 'Unknown'),
]

name = models.CharField(max_length=256, verbose_name="寵物名稱")
keeper = models.ForeignKey(to=User, on_delete=models.CASCADE, verbose_name="寵物照顧人")
type = models.ForeignKey(to=PetType, on_delete=models.CASCADE, verbose_name="寵物種類")
birthday = models.DateField(verbose_name="寵物生日", blank=True, null=True, default=datetime.date.today)
content = models.TextField(verbose_name="寵物敘述")
size = models.CharField(max_length=256, verbose_name="寵物大小") # 新增寵物大小欄位
weight = models.DecimalField(max_digits=5, decimal_places=2, verbose_name="寵物重量") # 新增寵物重量欄位
gender = models.CharField(max_length=10, choices=GENDER_CHOICES, default='unknown', verbose_name="性別") # 新增性別欄位
is_neutered = models.BooleanField(default=False, verbose_name="是否結紮") # 新增結紮欄位
der = models.DecimalField(max_digits=6, decimal_places=2, default=0, verbose_name="每日能量需求") # der欄位
image = models.ImageField(upload_to=upload_to, blank=True, null=True)

# External Columns
Expand All @@ -33,6 +44,7 @@ def __str__(self):
return f'{self.name} 照顧人:{self.keeper.username}: 寵物種類{self.type.typename}'



class Machine(models.Model):
name = models.CharField(max_length=255, verbose_name="機器名稱")
onlineStatus = models.BooleanField(default=False, verbose_name="上線狀態")
Expand Down
8 changes: 4 additions & 4 deletions api/serializers.py
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

PetSerializer 對於 Create Method 進行 Override 是否也會需要對 Pet Model 的 create() 進行 Override

Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ class PetRequestSerializer(serializers.ModelSerializer):

class Meta:
model = Pet
fields = ['id', 'name', 'keeper', 'type', 'birthday', 'content', 'image']
fields = ['id', 'name', 'keeper', 'type', 'birthday', 'content', 'image', 'size', 'weight', 'gender', 'is_neutered']
read_only_fields = ('id',)


Expand All @@ -34,7 +34,7 @@ class PetSerializer(serializers.ModelSerializer):

class Meta:
model = Pet
fields = ['id', 'name', 'keeper', 'type', 'birthday', 'content', 'image']
fields = ['id', 'name', 'keeper', 'type', 'birthday', 'content', 'image', 'size', 'weight', 'gender', 'is_neutered']
read_only_fields = ('id',)
depth = 1

Expand All @@ -45,10 +45,10 @@ class PetUploadImageSerializer(serializers.ModelSerializer):
class Meta:
model = Pet
fields = ['id', 'image']
read_only_fields = ('id', 'name', 'keeper', 'type', 'birthday', 'content')
read_only_fields = ('id', 'name', 'keeper', 'type', 'birthday', 'content', 'size', 'weight', 'gender', 'is_neutered')
depth = 1


class MachineSerializer(serializers.ModelSerializer):
class Meta:
model = Machine
Expand Down
49 changes: 48 additions & 1 deletion api/views/petViews.py
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

這邊可以參考目前 Master branch 的寫法,先製作 Serializer(DTO 的概念),就不需要自行定義輸入資料

Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

這些 low moderate high 已經說明在 Model 裡面 Django Model 是否會對於這些不相對應的值進行處理?

Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

still a problem

Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,53 @@ class PetCountAPIView(APIView):
def get(self, request: Request, *args, **kwargs):
pet_dict = dict()
for i in models.PetType.objects.all():
petDict[i.typename] = models.Pet.objects.filter(type=i.id).count()
return Response(data=petDict, status=status.HTTP_200_OK)


def petResponseConverter(pet: models.Pet):
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

不需要這個 改用 Serializer 處理

if pet is not None:
result = dict(
id=pet.id,
name=pet.name,
keeper=userResponseConverter(pet.keeper),
type_id=petTypeResponseConverter(pet.type),
birthday=pet.birthday,
content=pet.content
)
else:
result = ""
return result


def petTypeResponseConverter(petType: models.PetType):
if petType is not None:
result = dict(
id=petType.id,
typename=petType.typename,
description=petType.description
)
else:
result = ""
return result


def calculate_resting_energy_requirement(weight):
fan9704 marked this conversation as resolved.
Show resolved Hide resolved
return 70 * (weight ** 0.75)


def calculate_daily_energy_requirement(weight, activity_level):
activity_levels = {
'low': 1.2,
'moderate': 1.4,
'high': 1.6,
}

if activity_level not in activity_levels:
raise ValueError("Invalid activity level")

levels = activity_levels[activity_level]
return levels * calculate_resting_energy_requirement(weight)
pet_dict[i.typename] = models.Pet.objects.filter(type=i.id).count()
return Response(data=pet_dict, status=status.HTTP_200_OK)

Expand Down Expand Up @@ -107,4 +154,4 @@ def post(self, request: Request, pk: int):
return Response(data={'error': 'Pet not found'}, status=status.HTTP_404_NOT_FOUND)
pet.image = request.FILES.get("image")
pet.save()
return Response(data=PetSerializer(pet).data, status=status.HTTP_200_OK)
return Response(data=PetSerializer(pet).data, status=status.HTTP_200_OK