@Jasper_Holton's profile photo

How to Make a Dynamic Easy-Reading Theme Based on Sunrise and Sunset This code lets me automatically render pages in either light or dark mode (with light or dark styles) depending on whether the sun is up. I am querying the location and timezone info using an API. This is a great way to make a site easier on the eyes at night. A webpage with a lot of white blank space in it can be a little bit hard to use at night, so it's better to have a context processor that makes the site easier to read at night.

# app/context_processors.py
import pytz
from astral import LocationInfo
from astral.sun import sun
def context_processor(context_data)
    tz = request.user.profile.timezone # Get the timezone
    city = LocationInfo(request.user.profile.city, request.user.profile.country, tz, request.user.profile.lat, request.user.profile.lon) # Using astral to query location by city, country, timezone, latitude and longitude
    city_sun = sun(city.observer, date=datetime.now(pytz.timezone(tz))) # get 
    the city sunlight
    now_time = datetime.now(pytz.timezone(tz)).time() # Get the time now
    if now_time <= city_sun['sunrise'].astimezone(pytz.timezone(tz)).time() or now_time >= city_sun['sunset'].astimezone(pytz.timezone(tz)).time(): # If the sun is down
        context_data['darkmode'] = True # Make the page dark
        context_data['darkmode'] = False # Or otherwise make it light
    return context_data

# users/middleware.py
def simple_middleware(get_response):
    # One-time configuration and initialization.
    def middleware(request):
        User = get_user_model()
        if request.user.is_authenticated and hasattr(request.user, 'profile'):
            user = get_object_or_404(User, pk=request.user.pk)
            # Update last visit time after request finished processing.
            last_ip = request.user.profile.ip
            request.user.profile.ip = get_client_ip(request)
            if request.user.profile.ip != last_ip:
                request.user.profile.timezone = get_timezone(request.user.profile.ip)
                response = requests.get('http://https://ipinfo.io/' + request.user.profile.ip + '/json' ).json() # Get the IP info
                request.user.profile.city = response['city'] # Save it
                request.user.profile.country = response['country']
                request.user.profile.timezone = response['timezone']
                request.user.profile.lat = response['loc'].split(',')[0]
                request.user.profile.lon = response['loc'].split(',')[1]
        response = get_response(request)
        return response
    return middleware

Pinterest logo
Tumblr logo VK logo

https://uglek.com/post/453/ -

© Uglek, 2022

Terms of Use and Privacy Policy