Dive into Code

Discover code snippets, tutorials, and programming insights

Django

Convert request object to dict in django

<p>The provided Python function `request_to_dict(request)` is a utility function used to convert a Django request object (presumably an HTTP request) into a dictionary containing relevant information about the request. It …

python
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
def request_to_dict(request):
    # Initialize an empty dictionary
    data = {}

    # Get the GET parameters
    for key in request.GET.keys():
        data[key] = request.GET.get(key)

    # Get the POST parameters
    for key in request.POST.keys():
        data[key] = request.POST.get(key)

    data['method'] = request.method
    data['path'] = request.path
    data['user_agent'] = request.META.get('HTTP_USER_AGENT')
    data['ip_address'] = request.META.get('REMOTE_ADDR')
    return data
Python

example multi level dict in python

<ol> <li><code>my_dict</code> is the main dictionary that contains two key-value pairs.</li> <li>The keys in the <code>my_dict</code> are <code>level1_key1</code> and <code>level1_key2</code>.</li> <li>The values corresponding to each key in <code>my_dict</code> are also …

python
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
my_dict = {
    "level1_key1": {
        "level2_key1": "value1",
        "level2_key2": "value2"
    },
    "level1_key2": {
        "level2_key3": "value3",
        "level2_key4": "value4"
    }
}
Python

Generate random hex color code in python

<p>Is a Python script that generates random hexadecimal color codes and prints them repeatedly with a one-second delay. The <code>get_random_color()</code> function generates a random color by randomly selecting characters from …

python
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
import random
import time

def get_random_color():
    letters = '0123456789ABCDEF'
    color = '#'
    for i in range(6):
        color += letters[random.randint(0, 15)]
    return color

while True:
    color = get_random_color()
    print(color)
    time.sleep(1)
jQuery

Get url params as json object in jquery

<p>This code defines a JavaScript function called <code>getUrlParametersAsJson()</code> that extracts URL parameters from the current page&#39;s URL and returns them as a JavaScript object (JSON format).</p> <p>Here&#39;s a step-by-step explanation …

javascript
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
function getUrlParametersAsJson() {
  var urlParams = window.location.search.substring(1);
  var paramArray = urlParams.split('&');
  var params = {};

  $.each(paramArray, function(index, param) {
    var keyValue = param.split('=');
    var key = decodeURIComponent(keyValue[0]);
    var value = decodeURIComponent(keyValue[1]);
    params[key] = value;
  });

  return params;
}

// Usage
var jsonParams = getUrlParametersAsJson();
console.log(jsonParams);