96 lines
2.4 KiB
Python
96 lines
2.4 KiB
Python
from django.conf import settings
|
|
|
|
from core import db
|
|
from core.models import Drug
|
|
|
|
|
|
class QueryError(Exception):
|
|
pass
|
|
|
|
|
|
def parse_size(query_params, sizes):
|
|
if "size" in query_params:
|
|
size = query_params["size"]
|
|
if size not in sizes:
|
|
message = "Size is not permitted"
|
|
message_class = "danger"
|
|
return {"message": message, "class": message_class}
|
|
size = int(size)
|
|
else:
|
|
size = 15
|
|
|
|
return size
|
|
|
|
|
|
def parse_source(user, query_params):
|
|
source = None
|
|
if "source" in query_params:
|
|
source = query_params["source"]
|
|
|
|
# Check validity of source
|
|
if source not in settings.MAIN_SOURCES:
|
|
message = f"Invalid source: {source}"
|
|
message_class = "danger"
|
|
return {"message": message, "class": message_class}
|
|
|
|
if source == "all":
|
|
source = None # the next block will populate it
|
|
|
|
if source:
|
|
sources = [source]
|
|
else:
|
|
# Here we need to populate what "all" means for the user.
|
|
# They may only have access to a subset of the sources.
|
|
# We build a custom source list with ones they have access
|
|
# to, and then remove "all" from the list.
|
|
sources = list(settings.MAIN_SOURCES)
|
|
|
|
# Get rid of "all", it's just a meta-source
|
|
if "all" in sources:
|
|
sources.remove("all")
|
|
|
|
return sources
|
|
|
|
|
|
def run_query(query_params, tags, size, sources, ranges, sort):
|
|
if "query" in query_params:
|
|
query = query_params["query"]
|
|
results = Drug.objects.filter(name__icontains=query)[:size]
|
|
return results
|
|
|
|
|
|
def drug_query(request, query_params, size=None, tags=None):
|
|
db.add_defaults(query_params)
|
|
|
|
print("PARAMS11", query_params)
|
|
print("SIZE", size)
|
|
print("TAGS", tags)
|
|
|
|
# S - Size
|
|
if request.user.is_anonymous:
|
|
sizes = settings.MAIN_SIZES_ANON
|
|
else:
|
|
sizes = settings.MAIN_SIZES
|
|
if not size:
|
|
size = parse_size(query_params, sizes)
|
|
if isinstance(size, dict):
|
|
return size
|
|
|
|
# S - Source
|
|
sources = parse_source(request.user, query_params)
|
|
if isinstance(sources, dict):
|
|
return sources
|
|
|
|
# R - Ranges
|
|
ranges = None
|
|
|
|
# S - Sort
|
|
sort = None
|
|
|
|
# Q/T - Query/Tags
|
|
result = run_query(query_params, tags, size, sources, ranges, sort)
|
|
rtrn = {
|
|
"object_list": result,
|
|
}
|
|
return rtrn
|