Last active
February 13, 2018 17:02
-
-
Save Den1al/99c530c7d623a1378e10f9e788cb2889 to your computer and use it in GitHub Desktop.
Working with HTTP Headers in Pandas can be tricky, this snippet usually works for me to handle that task.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# author: @Daniel_Abeles | |
# date: 10/05/2017 | |
import numpy as np | |
import pandas as pd | |
class Headers(object): | |
''' Represents a header list ''' | |
__slots__ = ['_headers', '_key'] | |
def __init__(self, headers_string, delim='[NL]'): | |
self._headers = tuple(headers_string.split(delim)[:-1]) | |
self._key = headers_string | |
def __hash__(self): | |
return hash(self._key) | |
def __repr__(self): | |
return repr(self._headers) | |
def __eq__(self, other): | |
return hash(self) == hash(other) | |
def __iter__(self): | |
return iter(self._headers) | |
def __getitem__(self, header_name): | |
if isinstance(header_name, int): | |
return self._headers[header_name] | |
for header in self._headers: | |
name, _, value = header.partition(': ') | |
if name == header_name: | |
return value | |
raise KeyError(f'The header name: "{header_name}" does not exists!') | |
@staticmethod | |
def from_string(headers_string, delim='[NL]'): | |
if headers_string is np.nan: | |
return np.nan | |
return Headers(headers_string) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment