def get_data(self, context): """ Get all data for a page from Firestore. """ if context["section"]: data = page_data.get(context["section"]) else: data = page_data.get(context["page"]) if data is None: return context documents = data.get("documents") collections = data.get("collections") if documents: for item in documents: context[item["name"]] = get_document(item["ref"]) if collections: for item in collections: context[item["name"]] = get_collection( item["ref"], limit=item.get("limit"), order_by=item.get("order_by"), desc=item.get("desc"), filters=item.get("filters"), ) return context
def promotions(request): """Record a promotion, by getting promo code, finding any matching promotion document, and updating the views.""" try: data = loads(request.body) promo_code = data["promo_code"] matches = get_collection("promos/events/promo_stats", filters=[ { "key": "hash", "operation": ">=", "value": promo_code }, { "key": "hash", "operation": "<=", "value": "\uf8ff" }, ]) match = matches[0] promo_hash = match["hash"] timestamp = datetime.now().strftime("%Y-%m-%d_%H-%M-%S") increment_value(f"promos/events/promo_stats/{promo_hash}", "views") add_to_array(f"promos/events/promo_stats/{promo_hash}", "viewed_at", timestamp) # Optional: If user has an account, record which user visited in viewed_by collection. return JsonResponse({"message": {"success": True}}, safe=False) except: return JsonResponse({"message": {"success": False}}, safe=False)
def labs(request, format=None): """Get or update information about labs.""" # Query labs. if request.method == 'GET': limit = request.query_params.get("limit", None) order_by = request.query_params.get("order_by", "state") # TODO: Get any filters from dict(request.query_params) labs = get_collection('labs', order_by=order_by, limit=limit, filters=[]) return Response({ "data": labs}, content_type="application/json") # Update a lab given a valid Firebase token. elif request.method == 'POST': # Check token. try: claims = authenticate(request) except: return Response({"error": "Could not authenticate."}, status=status.HTTP_400_BAD_REQUEST) # Get the posted lab data. lab = request.data org_id = lab["id"] lab["slug"] = slugify(lab["name"]) # TODO: Handle adding labs. # Create uuid, latitude, and longitude, other fields? # Determine any changes. existing_data = get_document(f"labs/{org_id}") changes = [] for key, after in lab: before = existing_data[key] if before != after: changes.append({"key": key, "before": before, "after": after}) # Get a timestamp. timestamp = datetime.now().isoformat() lab["updated_at"] = timestamp # Create a change log. log_entry = { "action": "Updated lab data.", "type": "change", "created_at": lab["updated_at"], "user": claims["uid"], "user_name": claims["display_name"], "user_email": claims["email"], "photo_url": claims["photo_url"], "changes": changes, } update_document(f"labs/{org_id}/logs/{timestamp}", log_entry) # Update the lab. update_document(f"labs/{org_id}", lab) return Response(log_entry, status=status.HTTP_201_CREATED)
def lab_logs(request, org_id, format=None): """Get or create lab logs.""" if request.method == 'GET': data = get_collection(f"labs/{org_id}/logs") return Response({ "data": data}, content_type="application/json") elif request.method == 'POST': # TODO: Create a log. return Response({ "data": "Under construction"}, content_type="application/json")
def lab(request, format=None): """Get or update information about a lab.""" # Query labs. if request.method == 'GET': limit = request.query_params.get("limit", None) order_by = request.query_params.get("order_by", "state") # TODO: Get any filters from dict(request.query_params) labs = get_collection('labs', order_by=order_by, limit=limit, filters=[]) return Response({ "data": labs}, content_type="application/json")
def lab_analyses(request, org_id, format=None): """ Get or update (TODO) lab analyses. """ if request.method == 'GET': data = get_collection(f"labs/{org_id}/analyses") return Response({ "data": data}, content_type="application/json") elif request.method == 'POST': # TODO: Create an analysis. return Response({ "data": "Under construction"}, content_type="application/json")
def get_lab_data(self, context): """ Get a lab's data from Firestore. """ slug = self.kwargs.get("lab") filters = [{"key": "slug", "operation": "==", "value": slug}] labs = get_collection("labs", filters=filters) if labs: context["lab"] = labs[0] else: context["lab"] = {} return context
def mmes(request, format=None): """Get licensee (MME) data.""" if request.method == 'GET': limit = request.query_params.get("limit", None) if limit: limit = int(limit) order_by = request.query_params.get("order_by", "") # TODO: Get any filters from dict(request.query_params) # e.g. {"key": "name", "operation": "==", "value": "xyz"} docs = get_collection('tests/leaf/mmes', order_by=order_by, limit=limit, filters=[]) return Response(docs, content_type="application/json")
def lab_results(request, format=None): """Get lab results data.""" if request.method == 'GET': limit = request.query_params.get("limit", 1000) if limit: limit = int(limit) order_by = request.query_params.get("order_by", "") # TODO: Get any filters from dict(request.query_params) docs = get_collection('tests/leaf/lab_results', order_by=order_by, limit=limit, filters=[]) return Response(docs, content_type="application/json") if request.method == 'POST': print('TODO: Create lab results') return NotImplementedError
def download_lab_data(request): """Download either a free or premium lab data set.""" # Optional: Store allowed data points in Firebase? data_points = { "free": [ "id", "name", "trade_name", "license", "license_url", "license_issue_date", "license_expiration_date", "status", "street", "city", "county", "state", "zip", "description", ], "premium": [ "formatted_address", "timezone", "longitude", "latitude", "capacity", "square_feet", "brand_color", "favicon", "email", "phone", "website", "linkedin", "image_url", "opening_hours", "analyses", ], } # Get promo code for premium data. subscriber = {} tier = "free" try: authorization = request.headers["Authorization"] token = authorization.split(" ")[1] filters = [{"key": "promo_code", "operation": "==", "value": token}] subscriber = get_collection("subscribers", filters=filters)[0] if subscriber: subscriber["subscriber_created_at"] = subscriber["created_at"] subscriber["subscriber_updated_at"] = subscriber["updated_at"] tier = "premium" except: pass # Get lab data. labs = get_collection("labs", order_by="state") data = DataFrame.from_dict(labs, orient="columns") # Restrict data points. if tier == "premium": data = data[data_points["free"] + data_points["premium"]] else: data = data[data_points["free"]] # Convert JSON to CSV. with NamedTemporaryFile(delete=False) as temp: temp_name = temp.name + ".csv" data.to_csv(temp_name, index=False) temp.close() # Post a copy of the data to Firebase storage. now = datetime.now() timestamp = now.strftime("%Y-%m-%d_%H-%M-%S") filename = f"labs_{timestamp}.csv" destination = "public/data/downloads/" ref = destination + filename upload_file(ref, temp_name) # Create an activity log. log_entry = { "created_at": now.isoformat(), "updated_at": now.isoformat(), "data_points": len(data), "tier": tier, "filename": filename, "ref": ref, } log_entry = {**subscriber, **log_entry} update_document(f"logs/downloads/data_downloads/{timestamp}", log_entry) # Return the file to download. return FileResponse(open(temp_name, "rb"), filename=filename)