def device_from_request(request):
    """
    Determine's the device name from the request by first looking for an
    overridding cookie, and if not found then matching the user agent.
    Used at both the template level for choosing the template to load and
    also at the cache level as a cache key prefix.
    """
    from shuyucms.conf import settings
    try:
        user_agent = request.META['HTTP_USER_AGENT'].lower()
    except KeyError:
        pass
    else:
        try:
            user_agent = user_agent.decode('utf-8')
        except AttributeError:
            pass
        for device, ua_strings in settings.DEVICE_USER_AGENTS:
            for ua_string in ua_strings:
                if ua_string.lower() in user_agent:
                    return device
    return ''
