<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
 def post(request):
 """Sets a key to a value on the currently logged in users preferences :param key: Key to set :type key: str :param val: Value to set :type val: primitive :returns: json """

    data = request.POST or json.loads(request.body)['body']
    key = data.get('key', None)
    val = data.get('val', None)
    res = Result()
    if key is not None and val is not None:
        obj, created = UserPref.objects.get_or_create(user=request.user)
        if created:
            obj.data = json.dumps(DefaultPrefs.copy())
            obj.save()
        try:
            val = json.loads(val)
        except (TypeError, ValueError):
            pass
        obj.setKey(key, val)
        obj.save()
        res.append(obj.json())

    return JsonResponse(res.asDict())