Source code for basic_pages.views
"""
Basic Pages Views
This module contains views for basic pages in the application.
"""
from django.shortcuts import render
from django.conf import settings
from django.core.mail import send_mail
from django.shortcuts import reverse
from django.views.generic import FormView
from django.views.generic import TemplateView
from django.http import HttpResponse
from django.http import JsonResponse
from django import forms
from .forms import ContactForm
from datetime import timedelta
import datetime
import json
import requests
import os
[docs]
class HomeView(TemplateView):
"""
A view that displays the home page.
Attributes:
template_name (str): The name of the template to render.
"""
template_name = "home_page.html"
def get_context_data(self, **kwargs):
"""
Update the context dictionary with additional data for rendering.
Args:
kwargs: Additional keyword arguments passed to the view.
Returns:
dict: A dictionary containing the updated context.
"""
context = super().get_context_data(**kwargs)
# You can add any additional context data here if needed
context['page_title'] = 'Home'
return context
def get_success_url(self):
"""
Return the URL to redirect to after a successful action.
Returns:
str: The URL of the success page.
"""
return reverse("success_page")
[docs]
class DemoView(TemplateView):
"""
A view that displays the demo page.
Attributes:
template_name (str): The name of the template to render.
"""
template_name = "demo_page.html"
def get_context_data(self, **kwargs):
"""
Update the context dictionary with additional data for rendering.
Args:
kwargs: Additional keyword arguments passed to the view.
Returns:
dict: A dictionary containing the updated context.
"""
context = super().get_context_data(**kwargs)
# You can add any additional context data here if needed
return context
def get_success_url(self):
"""
Return the URL to redirect to after a successful action.
Returns:
str: The URL of the success page.
"""
return reverse("success_page")
class ApiView(TemplateView):
"""
"""
def post(self, request):
post_msg = request.POST["msg"]
style = request.POST["style"]
prompt_list = []
prompt_list.append("Please use about 8 words in chat format and a")
prompt_list.append(style)
prompt_list.append("attitude respond to :")
prompt_list.append(post_msg)
promptText = ' '.join(prompt_list)
key = os.environ['AI_API_KEY']
url = "https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-flash-latest:generateContent?key=" + key
msg = {}
msg["contents"] = {}
msg["contents"]["parts"] = {}
msg["contents"]["parts"]["text"] = promptText
response = requests.post(url, json=msg)
response_dict = response.json()
response_text = response_dict["candidates"][0]["content"]["parts"][0]["text"]
return JsonResponse({'msg': response_text})
[docs]
class AboutView(TemplateView):
"""
A Django class-based view that renders the 'about_page.html' template.
Attributes:
template_name (str): The name of the template to render, which is set to "about_page.html".
"""
template_name = "about_page.html"
def get_context_data(self, **kwargs):
"""
Override the default context data for this view.
This method adds any additional context data needed for rendering the 'about_page.html' template.
It extends the base class's context data by calling `super().get_context_data(**kwargs)` and then
can append or modify context variables as required.
Args:
**kwargs: Arbitrary keyword arguments passed to the view.
Returns:
dict: A dictionary containing the context data for the template.
"""
context = super().get_context_data(**kwargs)
# You can add any additional context data here if needed
return context
[docs]
class SuccessView(TemplateView):
"""
A Django class-based view that renders the 'success_page.html' template.
Attributes:
template_name (str): The name of the template to render, which is set to "success_page.html".
"""
template_name = "success_page.html"
# TODO - get msg info and put on page for confirmation
[docs]
class CookieManager:
"""
A utility class for managing cookies.
Methods:
set_cookie(response, key, value, days_expire=7): Sets a cookie in the given HTTP response.
"""
@staticmethod
def set_cookie(
response,
key,
value,
days_expire=7,
):
"""
Sets a cookie in the given HTTP response.
Args:
response (HttpResponse): The HTTP response object to which the cookie will be added.
key (str): The name of the cookie.
value (str): The value of the cookie.
days_expire (int, optional): The number of days until the cookie expires. Defaults to 7 days.
Returns:
None
"""
if days_expire is None:
max_age = 365 * 24 * 60 * 60 # One year
else:
max_age = days_expire * 24 * 60 * 60
expires = datetime.datetime.strftime(
datetime.datetime.utcnow() + timedelta(seconds=max_age),
"%a, %d-%b-%Y %H:%M:%S GMT",
)
response.set_cookie(
key,
value,
max_age=max_age,
expires=expires,
domain=settings.SESSION_COOKIE_DOMAIN,
secure=settings.SESSION_COOKIE_SECURE or None,
)
# Usage example:
# response = HttpResponse("Setting cookie")
# CookieManager.set_cookie(response, "my_key", "my_value")