Start replacing API petitions with models queries

This commit is contained in:
Santiago L 2023-11-22 11:56:09 +01:00
parent f6b1cf56e3
commit 720c4dd8a2
2 changed files with 43 additions and 27 deletions

View File

@ -6,8 +6,11 @@ from django.http import Http404
from django.urls.exceptions import NoReverseMatch from django.urls.exceptions import NoReverseMatch
from django.utils.translation import gettext_lazy as _ from django.utils.translation import gettext_lazy as _
from .models import (Address, DatabaseService, Domain, Mailbox, SaasService, from orchestra.contrib.domains.models import Domain
UserAccount, WebSite) from orchestra.contrib.mailboxes.models import Mailbox
from orchestra.contrib.websites.models import Website
from .models import Address, DatabaseService, SaasService, UserAccount
DOMAINS_PATH = 'domains/' DOMAINS_PATH = 'domains/'
TOKEN_PATH = '/api-token-auth/' TOKEN_PATH = '/api-token-auth/'
@ -43,14 +46,6 @@ class Orchestra(object):
self.username = username self.username = username
self.user = self.authenticate(self.username, password) self.user = self.authenticate(self.username, password)
def build_absolute_uri(self, path_name):
path = API_PATHS.get(path_name, None)
if path is None:
raise NoReverseMatch(
"Not found API path name '{}'".format(path_name))
return urllib.parse.urljoin(self.base_url, path)
def authenticate(self, username, password): def authenticate(self, username, password):
user = authenticate(self.request, username=username, password=password) user = authenticate(self.request, username=username, password=password)
@ -61,6 +56,21 @@ class Orchestra(object):
# Return an 'invalid login' error message. # Return an 'invalid login' error message.
return None return None
class OrchestraConnector:
def __init__(self, request):
self._request = request
self.user = request.user
assert not self.user.is_anonymous
def build_absolute_uri(self, path_name):
path = API_PATHS.get(path_name, None)
if path is None:
raise NoReverseMatch(
"Not found API path name '{}'".format(path_name))
return urllib.parse.urljoin(self.base_url, path)
def request(self, verb, resource=None, url=None, data=None, render_as="json", querystring=None, raise_exception=True): def request(self, verb, resource=None, url=None, data=None, render_as="json", querystring=None, raise_exception=True):
assert verb in ["HEAD", "GET", "POST", "PATCH", "PUT", "DELETE"] assert verb in ["HEAD", "GET", "POST", "PATCH", "PUT", "DELETE"]
if resource is not None: if resource is not None:
@ -89,18 +99,24 @@ class Orchestra(object):
return status, output return status, output
def retrieve_service_list(self, service_name, querystring=None): def retrieve_service_list(self, model_class, querystring=None):
pattern_name = '{}-list'.format(service_name) qs = model_class.objects.filter(account=self.user)
if pattern_name not in API_PATHS:
raise ValueError("Unknown service {}".format(service_name)) # TODO filter by querystring
_, output = self.request("GET", pattern_name, querystring=querystring)
return output return qs
# pattern_name = '{}-list'.format(service_name)
# if pattern_name not in API_PATHS:
# raise ValueError("Unknown service {}".format(service_name))
# _, output = self.request("GET", pattern_name, querystring=querystring)
# return output
def retrieve_profile(self): def retrieve_profile(self):
status, output = self.request("GET", 'my-account') if self.user.is_anonymous:
if status >= 400:
raise PermissionError("Cannot retrieve profile of an anonymous user.") raise PermissionError("Cannot retrieve profile of an anonymous user.")
return UserAccount.new_from_json(output[0])
return self.user # return UserAccount.new_from_json(output[0])
def retrieve_bill_document(self, pk): def retrieve_bill_document(self, pk):
path = API_PATHS.get('bill-document').format_map({'pk': pk}) path = API_PATHS.get('bill-document').format_map({'pk': pk})
@ -183,8 +199,8 @@ class Orchestra(object):
return status, response return status, response
def retrieve_mailbox_list(self): def retrieve_mailbox_list(self):
mailboxes = self.retrieve_service_list(Mailbox.api_name) qs = self.retrieve_service_list(Mailbox)
return [Mailbox.new_from_json(mailbox_data) for mailbox_data in mailboxes] return qs
def delete_mailbox(self, pk): def delete_mailbox(self, pk):
path = API_PATHS.get('mailbox-detail').format_map({'pk': pk}) path = API_PATHS.get('mailbox-detail').format_map({'pk': pk})
@ -210,7 +226,7 @@ class Orchestra(object):
return Domain.new_from_json(domain_json) return Domain.new_from_json(domain_json)
def retrieve_domain_list(self): def retrieve_domain_list(self):
output = self.retrieve_service_list(Domain.api_name) output = self.retrieve_service_list(Domain)
websites = self.retrieve_website_list() websites = self.retrieve_website_list()
domains = [] domains = []
@ -239,8 +255,8 @@ class Orchestra(object):
return domains return domains
def retrieve_website_list(self): def retrieve_website_list(self):
output = self.retrieve_service_list(WebSite.api_name) qs = self.retrieve_service_list(Website)
return [WebSite.new_from_json(website_data) for website_data in output] return qs
def filter_websites_by_domain(self, websites, domain_id): def filter_websites_by_domain(self, websites, domain_id):
matching = [] matching = []

View File

@ -52,11 +52,11 @@ class ExtendedPaginationMixin:
class UserTokenRequiredMixin(LoginRequiredMixin): class UserTokenRequiredMixin(LoginRequiredMixin):
# TODO XXX adapt this code
def get_context_data(self, **kwargs): def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs) context = super().get_context_data(**kwargs)
self.orchestra = api.OrchestraConnector(self.request)
context.update({ context.update({
# TODO XXX 'profile': self.orchestra.retrieve_profile(),
# 'profile': self.orchestra.retrieve_profile(),
}) })
return context return context