Что означают эти две строки в этом коде? - PullRequest
0 голосов
/ 31 марта 2019

Что означают ":" и "+2" в [:http_payload.index("\r\n\r\n")+2]? Что означает "(" / ")" и "[1]" в .split("/")[1]?

def get_http_headers(http_payload):
    try:
        # split the headers off if it is HTTP traffic
        headers_raw = http_payload[:http_payload.index("\r\n\r\n")+2]

        # break out the headers
        headers = dict(re.findall(r"(?P<name>.*?): (? P<value>.*?)\r\n", headers_raw))

    except:
        return None

    return headers

def extract_image(headers, http_payload):
    image = None
    image_type = None

    try:
        if "image" in headers["Content-Type"]:
            # grab the image type and image body
            image_type = headers["Content-Type"].split("/")[1]

            image = http_payload[http_payload.index("\r\n\r\n")+4:]



            except:
                pass
    except:
        return None, None

    return image, image_type

1 Ответ

1 голос
/ 31 марта 2019

http_payload[:http_payload.index("\r\n\r\n")+2] ломтики строка http_payload, так что только заголовок строки до первого появления "\ r \ n \ r \ n" и первого "\ r \ n" остается. .index() метод строки вернет индекс первого появления шаблона в строке.

Пример:

test = "abcdefg"
# slicing:
print(test[1:3])  # will output 'bc'

# index:
print(test.index('bc'))  # will output 1 (index of start of substring 'bc')

# either start or end (or both) of the slice can be left out, so the following is equivalent:
print(test[:2] == test[0:2])  # will output True

.split("/")[1] будет разбивать строку на символы "/" и возвращать список, из которого осуществляется доступ к элементу с индексом 1. Смотрите следующий код для примера:

test = "/this/is/a/path"
print(test.split("/"))  # will output ["this", "is", "a", "path"]
print(test.split("/")[0])  # will output "is" since element of index 1 of the resulting list is accessed.
...