1
Fork 0
mirror of https://github.com/RYGhub/royalnet.git synced 2024-11-23 19:44:20 +00:00
royalnet/royalpack/stars/api_diario_random.py

37 lines
1 KiB
Python
Raw Permalink Normal View History

from typing import *
2020-06-26 14:13:11 +00:00
import royalnet.constellation.api as rca
import royalnet.utils as ru
from ..tables import *
from sqlalchemy import func
2020-06-26 14:13:11 +00:00
class ApiDiarioRandomStar(rca.ApiStar):
path = "/api/diario/random/v1"
parameters = {
2020-06-22 17:27:11 +00:00
"get": {
"amount": "The number of diario entries to get."
}
}
tags = ["diario"]
2020-06-26 14:13:11 +00:00
@rca.magic
async def get(self, data: rca.ApiData) -> ru.JSON:
2020-06-22 17:27:11 +00:00
"""Get random diario entries."""
DiarioT = self.alchemy.get(Diario)
try:
amount = int(data["amount"])
except ValueError:
2020-06-26 14:13:11 +00:00
raise rca.InvalidParameterError("'amount' is not a valid int.")
entries: List[Diario] = await ru.asyncify(
data.session
.query(DiarioT)
.order_by(func.random())
.limit(amount)
.all
)
if len(entries) < amount:
2020-06-26 14:13:11 +00:00
raise rca.NotFoundError("Not enough diario entries.")
return list(map(lambda e: e.json(), entries))