File size: 1,699 Bytes
0632cd1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
from sqladmin import ModelView, action
from sqladmin import Admin

from fastapi import Request, Response
from fastapi.responses import RedirectResponse
from fastapi.templating import Jinja2Templates

import logging

from project.bot.models import MessagePair

template = Jinja2Templates(directory='templates')

logger = logging.getLogger(__name__)


class MessagePairAdmin(ModelView, model=MessagePair):
    category = 'Message History'
    column_list = [MessagePair.user_message, MessagePair.bot_response, MessagePair.country]
    is_async = True
    icon = "fa-solid fa-message"
    name = "Message Pair"
    name_plural = "Message pairs"
    column_searchable_list = [MessagePair.user_message, MessagePair.bot_response, MessagePair.country]
    column_export_list = ['user_message', 'bot_response', 'country']
    can_edit = False
    can_create = False
    column_default_sort = ('id', True)
    column_formatters = {
        MessagePair.bot_response: lambda m, a: m.bot_response[:50] + '...' if len(m.bot_response) > 50
        else m.bot_response}


class AdminCustom(Admin):

    async def login(self, request: Request) -> Response:
        assert self.authentication_backend is not None

        context = {"request": request, "error": ""}

        if request.method == "GET":
            return template.TemplateResponse("login_admin.html", context)

        ok = await self.authentication_backend.login(request)
        if not ok:
            context["error"] = "Invalid credentials."
            return template.TemplateResponse(
                "login_admin.html", context, status_code=400
            )

        return RedirectResponse(request.url_for("admin:index"), status_code=302)