id
int64
0
843k
repository_name
stringlengths
7
55
file_path
stringlengths
9
332
class_name
stringlengths
3
290
human_written_code
stringlengths
12
4.36M
class_skeleton
stringlengths
19
2.2M
total_program_units
int64
1
9.57k
total_doc_str
int64
0
4.2k
AvgCountLine
float64
0
7.89k
AvgCountLineBlank
float64
0
300
AvgCountLineCode
float64
0
7.89k
AvgCountLineComment
float64
0
7.89k
AvgCyclomatic
float64
0
130
CommentToCodeRatio
float64
0
176
CountClassBase
float64
0
48
CountClassCoupled
float64
0
589
CountClassCoupledModified
float64
0
581
CountClassDerived
float64
0
5.37k
CountDeclInstanceMethod
float64
0
4.2k
CountDeclInstanceVariable
float64
0
299
CountDeclMethod
float64
0
4.2k
CountDeclMethodAll
float64
0
4.2k
CountLine
float64
1
115k
CountLineBlank
float64
0
9.01k
CountLineCode
float64
0
94.4k
CountLineCodeDecl
float64
0
46.1k
CountLineCodeExe
float64
0
91.3k
CountLineComment
float64
0
27k
CountStmt
float64
1
93.2k
CountStmtDecl
float64
0
46.1k
CountStmtExe
float64
0
90.2k
MaxCyclomatic
float64
0
759
MaxInheritanceTree
float64
0
16
MaxNesting
float64
0
34
SumCyclomatic
float64
0
6k
1,500
72squared/redpipe
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/72squared_redpipe/test.py
test.HashedStringTestCase.Data
class Data(redpipe.HashedString): keyspace = 'my_index' shard_count = 3
class Data(redpipe.HashedString): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
31
3
0
3
3
2
0
3
3
2
0
4
0
0
1,501
72squared/redpipe
72squared_redpipe/redpipe/futures.py
redpipe.futures.Future
class Future(Generic[T]): """ An object returned from all our Pipeline calls. """ __slots__ = ['_result'] def set(self, data: T): """ Write the data into the object. Note that I intentionally did not declare `result` in the constructor. I want an error to happen if you try to access it before it is set. :param data: any python object :return: None """ self._result: T = data # noqa @property def result(self) -> T: """ Get the underlying result. Usually one of the data types returned by redis-py. :return: None, str, int, list, set, dict """ try: return self._result except AttributeError: pass raise ResultNotReady('Wait until after the pipeline executes.') def IS(self, other) -> bool: """ Allows you to do identity comparisons on the underlying object. :param other: Mixed :return: bool """ return self.result is other def isinstance(self, other) -> bool: """ allows you to check the instance type of the underlying result. :param other: :return: """ return isinstance(self.result, other) def id(self): """ Get the object id of the underlying result. """ return id(self.result) def __repr__(self) -> str: """ Magic method in python used to override the behavor of repr(future) :return: str """ try: return repr(self.result) except ResultNotReady: return repr(None) def __str__(self) -> str: """ Magic method in python used to override the behavor of str(future) :return: """ return str(self.result) def __lt__(self, other) -> bool: """ Magic method in python used to override the behavor of future < other :param other: Any python object, usually numeric :return: bool """ return self.result < other def __le__(self, other) -> bool: """ Magic method in python used to override the behavor of future <= other :param other: Any python object, usually numeric :return: bool """ return self.result <= other def __gt__(self, other) -> bool: """ Magic method in python used to override the behavor of future > other :param other: Any python object, usually numeric :return: bool """ return self.result > other def __ge__(self, other) -> bool: """ Magic method in python used to override the behavor of future >= other :param other: Any python object, usually numeric :return: bool """ return self.result >= other def __hash__(self): """ Magic method in python used to override the behavor of hash(future) :return: int """ return hash(self.result) def __eq__(self, other) -> bool: """ Magic method in python used to override the behavor of future == other :param other: Any python object :return: bool """ return self.result == other def __ne__(self, other) -> bool: """ Magic method in python used to override the behavor of future != other :param other: Any python object :return: bool """ return self.result != other def __bool__(self) -> bool: """ Magic method in python used to override the behavor of bool(future) :return: bool """ return bool(self.result) __nonzero__ = __bool__ def __bytes__(self): """ Magic method in python used to coerce object: bytes(future) :return: bytes """ return bytes(self.result) def __call__(self, *args, **kwargs): """ Magic method in python used to invoke a future: future(*args, **kwargs) :param args: tuple :param kwargs: dict :return: Unknown, defined by object """ return self.result(*args, **kwargs) def __len__(self): """ Magic method in python used to determine length: len(future) :return: int """ return len(self.result) def __iter__(self): """ Magic method in python to support iteration. Example: .. code-block:: python future = Future() future.set([1, 2, 3]) for row in future: print(row) :return: iterable generator """ for item in self.result: yield item def __contains__(self, item): """ Magic python method supporting: `item in future` :param item: any python object :return: bool """ return item in self.result def __reversed__(self): """ Magic python method to emulate: reversed(future) :return: list """ return reversed(self.result) def __getitem__(self, item): """ Used to emulate dictionary access of an element: future[key] :param item: usually str, key name of dict. :return: element, type unknown """ return self.result[item] def __int__(self): """ Magic method in python to coerce to int: int(future) :return: """ return int(self.result) def __float__(self): """ Magic method in python to coerce to float: float(future) :return: float """ return float(self.result) def __round__(self, ndigits=0): """ Magic method in python to round: round(future, 1) :param ndigits: int :return: float, int """ return round(self.result, ndigits=ndigits) def __add__(self, other): """ support addition: result = future + 1 :param other: int, float, str, list :return: int, float, str, list """ return self.result + other def __sub__(self, other): """ support subtraction: result = future - 1 :param other: int, float, str, list :return: int, float, str, list """ return self.result - other def __mul__(self, other): """ support multiplication: result = future * 2 :param other: int, float, str, list :return: int, float, str, list """ return self.result * other def __mod__(self, other): """ support modulo: result = future % 2 :param other: int, float, str, list :return: int, float, str, list """ return self.result % other def __truediv__(self, other): """ support division: result = future / 2 for python 3 :param other: int, float :return: int, float """ return self.result / other __div__ = __truediv__ def __floordiv__(self, other): """ support floor division: result = future // 2 :param other: int, float :return: int, float """ return self.result // other def __pow__(self, power, modulo=None): """ supports raising to a power: result = pow(future, 3) :param power: int :param modulo: :return: int, float """ return pow(self.result, power, modulo) def __lshift__(self, other): """ bitwise operation: result = future << other """ return self.result << other def __rshift__(self, other): """ bitwise operation: result = future >> other """ return self.result >> other def __and__(self, other): """ bitwise operation: result = future & other """ return self.result & other def __xor__(self, other): """ bitwise operation: result = future ^ other """ return self.result ^ other def __or__(self, other): """ bitwise operation: result = future | other """ return self.result | other def __radd__(self, other): """ addition operation: result = other + future """ return other + self.result def __rsub__(self, other): """ subtraction operation: result = other - future """ return other - self.result def __rmul__(self, other): """ multiplication operation: result = other * future """ return self.result * other def __rmod__(self, other): """ use as modulo: result = other * future """ return other % self.result def __rtruediv__(self, other): """ use as divisor: result = other / future python 3 """ return other / self.result __rdiv__ = __rtruediv__ def __rfloordiv__(self, other): """ floor divisor: result other // future """ return other // self.result def __rpow__(self, other): """ reverse power: other ** future """ return other ** self.result def __rlshift__(self, other): """ result = other << future """ return other << self.result def __rrshift__(self, other): """ result = other >> future """ return other >> self.result def __rand__(self, other): """ result = other & future """ return other & self.result def __rxor__(self, other): """ result = other ^ future """ return other ^ self.result def __ror__(self, other): """ result = other | future """ return other | self.result def __getattr__(self, name, default=None): """ access an attribute of the future: future.some_attribute or getattr(future, name, default) :param name: attribute name :param default: a value to be used if no attribute is found :return: """ if name[0] == '_': raise AttributeError(name) return getattr(self.result, name, default) def __getstate__(self): """ used for getting object state to serialize when pickling :return: object """ return {'result': self.result} def __setstate__(self, state): """ used for restoring object state when pickling :param state: object :return: None """ self._result = state['result'] # this helps with duck-typing. # when grabbing the property for json encoder, # we can look for this unique attribute which is an alias for result # and we can be reasonably sure it is not accidentally grabbing # some other type of object. _redpipe_future_result = result
class Future(Generic[T]): ''' An object returned from all our Pipeline calls. ''' def set(self, data: T): ''' Write the data into the object. Note that I intentionally did not declare `result` in the constructor. I want an error to happen if you try to access it before it is set. :param data: any python object :return: None ''' pass @property def result(self) -> T: ''' Get the underlying result. Usually one of the data types returned by redis-py. :return: None, str, int, list, set, dict ''' pass def IS(self, other) -> bool: ''' Allows you to do identity comparisons on the underlying object. :param other: Mixed :return: bool ''' pass def isinstance(self, other) -> bool: ''' allows you to check the instance type of the underlying result. :param other: :return: ''' pass def id(self): ''' Get the object id of the underlying result. ''' pass def __repr__(self) -> str: ''' Magic method in python used to override the behavor of repr(future) :return: str ''' pass def __str__(self) -> str: ''' Magic method in python used to override the behavor of str(future) :return: ''' pass def __lt__(self, other) -> bool: ''' Magic method in python used to override the behavor of future < other :param other: Any python object, usually numeric :return: bool ''' pass def __le__(self, other) -> bool: ''' Magic method in python used to override the behavor of future <= other :param other: Any python object, usually numeric :return: bool ''' pass def __gt__(self, other) -> bool: ''' Magic method in python used to override the behavor of future > other :param other: Any python object, usually numeric :return: bool ''' pass def __ge__(self, other) -> bool: ''' Magic method in python used to override the behavor of future >= other :param other: Any python object, usually numeric :return: bool ''' pass def __hash__(self): ''' Magic method in python used to override the behavor of hash(future) :return: int ''' pass def __eq__(self, other) -> bool: ''' Magic method in python used to override the behavor of future == other :param other: Any python object :return: bool ''' pass def __ne__(self, other) -> bool: ''' Magic method in python used to override the behavor of future != other :param other: Any python object :return: bool ''' pass def __bool__(self) -> bool: ''' Magic method in python used to override the behavor of bool(future) :return: bool ''' pass def __bytes__(self): ''' Magic method in python used to coerce object: bytes(future) :return: bytes ''' pass def __call__(self, *args, **kwargs): ''' Magic method in python used to invoke a future: future(*args, **kwargs) :param args: tuple :param kwargs: dict :return: Unknown, defined by object ''' pass def __len__(self): ''' Magic method in python used to determine length: len(future) :return: int ''' pass def __iter__(self): ''' Magic method in python to support iteration. Example: .. code-block:: python future = Future() future.set([1, 2, 3]) for row in future: print(row) :return: iterable generator ''' pass def __contains__(self, item): ''' Magic python method supporting: `item in future` :param item: any python object :return: bool ''' pass def __reversed__(self): ''' Magic python method to emulate: reversed(future) :return: list ''' pass def __getitem__(self, item): ''' Used to emulate dictionary access of an element: future[key] :param item: usually str, key name of dict. :return: element, type unknown ''' pass def __int__(self): ''' Magic method in python to coerce to int: int(future) :return: ''' pass def __float__(self): ''' Magic method in python to coerce to float: float(future) :return: float ''' pass def __round__(self, ndigits=0): ''' Magic method in python to round: round(future, 1) :param ndigits: int :return: float, int ''' pass def __add__(self, other): ''' support addition: result = future + 1 :param other: int, float, str, list :return: int, float, str, list ''' pass def __sub__(self, other): ''' support subtraction: result = future - 1 :param other: int, float, str, list :return: int, float, str, list ''' pass def __mul__(self, other): ''' support multiplication: result = future * 2 :param other: int, float, str, list :return: int, float, str, list ''' pass def __mod__(self, other): ''' support modulo: result = future % 2 :param other: int, float, str, list :return: int, float, str, list ''' pass def __truediv__(self, other): ''' support division: result = future / 2 for python 3 :param other: int, float :return: int, float ''' pass def __floordiv__(self, other): ''' support floor division: result = future // 2 :param other: int, float :return: int, float ''' pass def __pow__(self, power, modulo=None): ''' supports raising to a power: result = pow(future, 3) :param power: int :param modulo: :return: int, float ''' pass def __lshift__(self, other): ''' bitwise operation: result = future << other ''' pass def __rshift__(self, other): ''' bitwise operation: result = future >> other ''' pass def __and__(self, other): ''' bitwise operation: result = future & other ''' pass def __xor__(self, other): ''' bitwise operation: result = future ^ other ''' pass def __or__(self, other): ''' bitwise operation: result = future | other ''' pass def __radd__(self, other): ''' addition operation: result = other + future ''' pass def __rsub__(self, other): ''' subtraction operation: result = other - future ''' pass def __rmul__(self, other): ''' multiplication operation: result = other * future ''' pass def __rmod__(self, other): ''' use as modulo: result = other * future ''' pass def __rtruediv__(self, other): ''' use as divisor: result = other / future python 3 ''' pass def __rfloordiv__(self, other): ''' floor divisor: result other // future ''' pass def __rpow__(self, other): ''' reverse power: other ** future ''' pass def __rlshift__(self, other): ''' result = other << future ''' pass def __rrshift__(self, other): ''' result = other >> future ''' pass def __rand__(self, other): ''' result = other & future ''' pass def __rxor__(self, other): ''' result = other ^ future ''' pass def __ror__(self, other): ''' result = other | future ''' pass def __getattr__(self, name, default=None): ''' access an attribute of the future: future.some_attribute or getattr(future, name, default) :param name: attribute name :param default: a value to be used if no attribute is found :return: ''' pass def __getstate__(self): ''' used for getting object state to serialize when pickling :return: object ''' pass def __setstate__(self, state): ''' used for restoring object state when pickling :param state: object :return: None ''' pass
54
53
7
1
2
4
1
1.98
1
8
1
0
52
1
52
54
455
96
121
61
67
239
120
60
67
2
1
1
56
1,502
72squared/redpipe
72squared_redpipe/redpipe/keyspaces.py
redpipe.keyspaces.HashedString
class HashedString(metaclass=HashedStringMeta): _core: Callable shard_count = 64 @classmethod def core(cls, pipe: Optional[PipelineInterface] = None): return cls._core(pipe) # typing: ignore @classmethod def shard(cls, key: str): key = "%s" % key keyhash = hashlib.md5(key.encode('utf-8')).hexdigest() return int(keyhash, 16) % cls.shard_count @classmethod def _parse_values(cls, values, extra=None): return _parse_values(values, extra) def __init__(self, pipe: Optional[PipelineInterface] = None): """ Creates a new keyspace. Optionally pass in a pipeline object. If you pass in a pipeline, all commands to this instance will be pipelined. :param pipe: optional Pipeline or NestedPipeline """ self._pipe = pipe @property def pipe(self) -> PipelineInterface: """ Get a fresh pipeline() to be used in a `with` block. :return: Pipeline or NestedPipeline with autoexec set to true. """ return autoexec(self._pipe) def get(self, key: str) -> Future: """ Return the value of the key or None if the key doesn't exist :param key: str the name of the redis key :return: Future() """ with self.pipe as pipe: return self.core(pipe=pipe).hget(self.shard(key), key) def delete(self, key: str, *args) -> Future[int]: keys = self._parse_values(key, args) response = Future[int]() with self.pipe as pipe: core = self.core(pipe=pipe) tracking = [] for k in keys: tracking.append(core.hdel(self.shard(k), k)) def cb(): response.set(sum(tracking)) pipe.on_execute(cb) return response def set(self, name: str, value: str, nx: bool = False) -> Future: """ Set the value at key ``name`` to ``value`` ``nx`` if set to True, set the value at key ``name`` to ``value`` if it does not already exist. :return: Future() """ with self.pipe as pipe: core = self.core(pipe=pipe) method = core.hsetnx if nx else core.hset return method(self.shard(name), name, value) def setnx(self, name, value) -> Future: """ Set the value as a string in the key only if the key doesn't exist. :param name: str the name of the redis key :param value: :return: Future() """ with self.pipe as pipe: return self.core(pipe=pipe).hsetnx(self.shard(name), name, value) def strlen(self, name: str) -> Future: """ Return the number of bytes stored in the value of the key :param name: str the name of the redis key :return: Future() """ with self.pipe as pipe: return self.core(pipe=pipe).hstrlen(self.shard(name), name) def incr(self, name: str, amount: int = 1) -> Future: """ increment the value for key by 1 :param name: str the name of the redis key :param amount: int :return: Future() """ with self.pipe as pipe: return self.core(pipe=pipe).hincrby( self.shard(name), name, amount=amount) def incrby(self, name: str, amount: int = 1) -> Future: """ increment the value for key by value: int :param name: str the name of the redis key :param amount: int :return: Future() """ with self.pipe as pipe: return self.core(pipe=pipe).hincrby( self.shard(name), name, amount=amount) def incrbyfloat(self, name: str, amount: float = 1.0) -> Future: """ increment the value for key by value: float :param name: str the name of the redis key :param amount: int :return: Future() """ with self.pipe as pipe: return self.core(pipe=pipe).hincrbyfloat( self.shard(name), name, amount=amount) def __getitem__(self, name: str) -> Future: """ magic python method that makes the class behave like a dictionary. use to access elements. :param name: :return: """ return self.get(name) def __setitem__(self, name: str, value: str) -> None: """ magic python method that makes the class behave like a dictionary. use to set elements. :param name: :param value: :return: """ self.set(name, value) def mget(self, keys: Union[str, typing.List[str]], *args: str) -> Future: """ Returns a list of values ordered identically to ``keys`` """ with self.pipe as pipe: f = Future[Any]() core = self.core(pipe=pipe) keys = [k for k in self._parse_values(keys, args)] mapping = {k: core.hget(self.shard(k), k) for k in keys} def cb(): f.set([mapping[k] for k in keys]) pipe.on_execute(cb) return f def scan_iter(self, match=None, count=None) -> Iterable: """ Make an iterator using the hscan command so that the client doesn't need to remember the cursor position. ``match`` allows for filtering the keys by pattern ``count`` allows for hint the minimum number of returns """ core = self.core() for i in range(0, self.shard_count - 1): cursor = 0 while True: res = core.hscan(i, cursor=cursor, match=match, count=count) cursor, elements = res if elements: for k, v in elements.items(): yield k, v if cursor == 0: break
class HashedString(metaclass=HashedStringMeta): @classmethod def core(cls, pipe: Optional[PipelineInterface] = None): pass @classmethod def shard(cls, key: str): pass @classmethod def _parse_values(cls, values, extra=None): pass def __init__(self, pipe: Optional[PipelineInterface] = None): ''' Creates a new keyspace. Optionally pass in a pipeline object. If you pass in a pipeline, all commands to this instance will be pipelined. :param pipe: optional Pipeline or NestedPipeline ''' pass @property def pipe(self) -> PipelineInterface: ''' Get a fresh pipeline() to be used in a `with` block. :return: Pipeline or NestedPipeline with autoexec set to true. ''' pass def get(self, key: str) -> Future: ''' Return the value of the key or None if the key doesn't exist :param key: str the name of the redis key :return: Future() ''' pass def delete(self, key: str, *args) -> Future[int]: pass def cb(): pass def set(self, name: str, value: str, nx: bool = False) -> Future: ''' Set the value at key ``name`` to ``value`` ``nx`` if set to True, set the value at key ``name`` to ``value`` if it does not already exist. :return: Future() ''' pass def setnx(self, name, value) -> Future: ''' Set the value as a string in the key only if the key doesn't exist. :param name: str the name of the redis key :param value: :return: Future() ''' pass def strlen(self, name: str) -> Future: ''' Return the number of bytes stored in the value of the key :param name: str the name of the redis key :return: Future() ''' pass def incr(self, name: str, amount: int = 1) -> Future: ''' increment the value for key by 1 :param name: str the name of the redis key :param amount: int :return: Future() ''' pass def incrby(self, name: str, amount: int = 1) -> Future: ''' increment the value for key by value: int :param name: str the name of the redis key :param amount: int :return: Future() ''' pass def incrbyfloat(self, name: str, amount: float = 1.0) -> Future: ''' increment the value for key by value: float :param name: str the name of the redis key :param amount: int :return: Future() ''' pass def __getitem__(self, name: str) -> Future: ''' magic python method that makes the class behave like a dictionary. use to access elements. :param name: :return: ''' pass def __setitem__(self, name: str, value: str) -> None: ''' magic python method that makes the class behave like a dictionary. use to set elements. :param name: :param value: :return: ''' pass def mget(self, keys: Union[str, typing.List[str]], *args: str) -> Future: ''' Returns a list of values ordered identically to ``keys`` ''' pass def cb(): pass def scan_iter(self, match=None, count=None) -> Iterable: ''' Make an iterator using the hscan command so that the client doesn't need to remember the cursor position. ``match`` allows for filtering the keys by pattern ``count`` allows for hint the minimum number of returns ''' pass
24
13
9
1
4
4
1
0.89
1
8
2
1
14
1
17
31
196
40
83
52
59
74
76
39
56
6
3
4
26
1,503
72squared/redpipe
72squared_redpipe/redpipe/tasks.py
redpipe.tasks.TaskManager
class TaskManager(object): """ standardized interface for processing async vs synchronous tasks. """ task = AsynchronousTask @classmethod def set_task_type(cls, task): cls.task = task @classmethod def promise(cls, fn, *args, **kwargs): """ Used to build a task based on a callable function and the arguments. Kick it off and start execution of the task. :param fn: callable :param args: tuple :param kwargs: dict :return: SynchronousTask or AsynchronousTask """ task = cls.task(target=fn, args=args, kwargs=kwargs) task.start() return task @classmethod def wait(cls, *tasks): """ Wait for all tasks to finish completion. :param tasks: tulple of tasks, AsynchronousTask or SynchronousTask. :return: list of the results from each task. """ return [f.result for f in tasks]
class TaskManager(object): ''' standardized interface for processing async vs synchronous tasks. ''' @classmethod def set_task_type(cls, task): pass @classmethod def promise(cls, fn, *args, **kwargs): ''' Used to build a task based on a callable function and the arguments. Kick it off and start execution of the task. :param fn: callable :param args: tuple :param kwargs: dict :return: SynchronousTask or AsynchronousTask ''' pass @classmethod def wait(cls, *tasks): ''' Wait for all tasks to finish completion. :param tasks: tulple of tasks, AsynchronousTask or SynchronousTask. :return: list of the results from each task. ''' pass
7
3
8
1
3
4
1
1.23
1
0
0
0
0
0
3
3
34
5
13
9
6
16
10
6
6
1
1
0
3
1,504
72squared/redpipe
72squared_redpipe/redpipe/tasks.py
redpipe.tasks.SynchronousTask
class SynchronousTask(object): """ Iterate through each backend sequentially. Fallback method if you aren't comfortable with threads. """ def __init__(self, target, args=None, kwargs=None): if args is None: args = () if kwargs is None: kwargs = {} self._target = target self._args = args self._kwargs = kwargs self._exception = None self._result = None def run(self): # noinspection PyBroadException try: self._result = self._target(*self._args, **self._kwargs) except Exception as e: self._exception = e finally: # Avoid a refcycle if the thread is running a function with # an argument that has a member that points to the thread. del self._target, self._args, self._kwargs start = run @property def result(self): if self._exception is not None: raise self._exception return self._result
class SynchronousTask(object): ''' Iterate through each backend sequentially. Fallback method if you aren't comfortable with threads. ''' def __init__(self, target, args=None, kwargs=None): pass def run(self): pass @property def result(self): pass
5
1
8
0
7
1
2
0.29
1
1
0
0
3
5
3
3
36
5
24
12
19
7
22
10
18
3
1
1
7
1,505
72squared/redpipe
72squared_redpipe/redpipe/tasks.py
redpipe.tasks.AsynchronousTask
class AsynchronousTask(threading.Thread): """ use threads to talk to multiple redis backends simulaneously. Should decrease latency for the case when sending commands to multiple redis backends in one `redpipe.pipeline`. """ def __init__(self, target, args=None, kwargs=None): super(AsynchronousTask, self).__init__() if args is None: args = () if kwargs is None: kwargs = {} self._target = target self._args = args self._kwargs = kwargs self._exception = None self._result = None def run(self): # noinspection PyBroadException try: self._result = self._target(*self._args, **self._kwargs) except Exception as e: self._exception = e finally: # Avoid a refcycle if the thread is running a function with # an argument that has a member that points to the thread. del self._target, self._args, self._kwargs @property def result(self): if self.is_alive(): self.join() if self._exception is not None: raise self._exception return self._result
class AsynchronousTask(threading.Thread): ''' use threads to talk to multiple redis backends simulaneously. Should decrease latency for the case when sending commands to multiple redis backends in one `redpipe.pipeline`. ''' def __init__(self, target, args=None, kwargs=None): pass def run(self): pass @property def result(self): pass
5
1
9
0
8
1
3
0.31
1
2
0
0
3
5
3
28
38
4
26
11
21
8
24
9
20
3
1
1
8
1,506
72squared/redpipe
72squared_redpipe/redpipe/structs.py
redpipe.structs.StructMeta
class StructMeta(type): """ Data binding of a redpipe.Hash to the core of the Struct object. Creates it dynamically on class construction. uses the keyspace and connection fields Meta Classes are strange beasts. """ def __new__(mcs, name, bases, d): if name in ['Struct'] and d.get('__module__', '') == 'redpipe.structs': return type.__new__(mcs, name, bases, d) class StructHash(Hash): keyspace = d.get('keyspace', name) connection = d.get('connection', None) fields = d.get('fields', {}) keyparse = d.get('keyparse', TextField) valueparse = d.get('valueparse', TextField) memberparse = d.get('memberparse', TextField) keyspace_template = d.get('keyspace_template', '%s{%s}') d['core'] = StructHash return type.__new__(mcs, name, bases, d)
class StructMeta(type): ''' Data binding of a redpipe.Hash to the core of the Struct object. Creates it dynamically on class construction. uses the keyspace and connection fields Meta Classes are strange beasts. ''' def __new__(mcs, name, bases, d): pass class StructHash(Hash):
3
1
16
3
13
0
2
0.43
1
1
1
1
1
0
1
14
24
4
14
10
11
6
14
10
11
2
2
1
2
1,507
72squared/redpipe
72squared_redpipe/redpipe/structs.py
redpipe.structs.Struct
class Struct(metaclass=StructMeta): """ load and store structured data in redis using OOP patterns. If you pass in a dictionary-like object, redpipe will write all the values you pass in to redis to the key you specify. By default, the primary key name is `_key`. But you should override this in your Struct with the `key_name` property. .. code-block:: python class Beer(redpipe.Struct): fields = {'name': redpipe.TextField} key_name = 'beer_id' beer = Beer({'beer_id': '1', 'name': 'Schlitz'}) This will store the data you pass into redis. It will also load any additional fields to hydrate the object. **RedPipe** does this in the same pipelined call. If you need a stub record that neither loads or saves data, do: .. code-block:: python beer = Beer({'beer_id': '1'}, no_op=True) You can later load the fields you want using, load. If you pass in a string we assume it is the key of the record. redpipe loads the data from redis: .. code-block:: python beer = Beer('1') assert(beer['beer_id'] == '1') assert(beer['name'] == 'Schlitz') If you need to load a record but only specific fields, you can say so. .. code-block:: python beer = Beer('1', fields=['name']) This will exclude all other fields. **RedPipe** cares about pipelining and efficiency, so if you need to bundle a bunch of reads or writes together, by all means do so! .. code-block:: python beer_ids = ['1', '2', '3'] with redpipe.pipeline() as pipe: beers = [Beer(i, pipe=pipe) for i in beer_ids] print(beers) This will pipeline all 3 together and load them in a single pass from redis. The following methods all accept a pipe: * __init__ * update * incr * decr * pop * remove * clear * delete You can pass a pipeline into them to make sure that the network i/o is combined with another pipeline operation. The other methods on the object are about accessing the data already loaded. So you shouldn't need to pipeline them. One more thing ... suppose you are storing temporary data and you want it to expire after a few days. You can easily make that happen just by changing the object definition: .. code-block:: python class Beer(redpipe.Struct): fields = {'name': redpipe.TextField} key_name = 'beer_id' ttl = 24 * 60 * 60 * 3 This makes sure that any set operations on the Struct will set the expiry at the same time. If the object isn't modified for more than the seconds specified in the ttl (stands for time-to-live), then the object will be expired from redis. This is useful for temporary objects. """ __slots__ = ['key', '_data'] keyspace: Optional[str] = None connection: Optional[str] = None key_name: str = '_key' fields: Dict[Any, Field] = {} required: Set[str] = set() # set as 'defined', 'all', or ['a', b', 'c'] default_fields: Union[str, List[str]] = 'all' field_attr_on: bool = False ttl: Optional[int] = None def __init__(self, _key_or_data: Union[str, Dict], pipe: Optional[PipelineInterface] = None, fields: Union[str, List[str], None] = None, no_op: bool = False, nx: bool = False): """ class constructor :param _key_or_data: :param pipe: :param fields: :param no_op: bool :param nx: bool """ self._data = {} with self._pipe(pipe=pipe) as p: # first we try treat the first arg as a dictionary. # this is if we are passing in data to be set into the redis hash. # if that doesn't work, we assume it must be the name of the key. if isinstance(_key_or_data, str): self.key = _key_or_data else: try: # force type to dict. # this blows up if it's a string. coerced = dict(_key_or_data) # look for the primary key in the data # won't work if we don't have this. keyname = self.key_name # track the primary key # it's the name of the key only. # the keyspace we defined will transform it into the full # name of the key. self.key = coerced[keyname] # remove it from our data set. # we don't write this value into redis. del coerced[keyname] # no op flag means don't write or read from the db. # if so, we just set the dictionary. # this is useful if we are cloning the object # or rehydrating it somehow. if no_op: self._data = coerced return required_found = self.required.intersection(coerced.keys()) if len(required_found) != len(self.required): raise InvalidOperation( 'missing required field(s): %s' % list(self.required - required_found) ) self.update(coerced, pipe=p, nx=nx) # we wind up here if a dictionary was passed in, but it # didn't contain the primary key except KeyError: # can't go any further, blow up. raise InvalidOperation( 'must specify primary key when cloning a struct') # normally we ask redis for the data from redis. # if the no_op flag was passed we skip it. if not no_op: self.load(fields=fields, pipe=p) def load(self, fields: Union[str, List[str], None] = None, pipe: Optional[PipelineInterface] = None) -> None: """ Load data from redis. Allows you to specify what fields to load. This method is also called implicitly from the constructor. :param fields: 'all', 'defined', or array of field names :param pipe: Pipeline(), NestedPipeline() or None :return: None """ if fields is None: fields = self.default_fields if fields == 'all': return self._load_all(pipe=pipe) if fields == 'defined': fields = [k for k in self.fields.keys()] if not fields: return with self._pipe(pipe) as p: # get the list of fields. # it returns a numerically keyed array. # when that happens we match up the results # to the keys we requested. ref = self.core(pipe=p).hmget(self.key, fields) def cb(): """ This callback fires when the root pipeline executes. At that point, we hydrate the response into this object. :return: None """ for i, v in enumerate(ref.result): k = fields[i] # redis will return all of the fields we requested # regardless of whether or not they are set. # if the value is None, it's not set in redis. # Use that as a signal to remove that value from local. if v is None: self._data.pop(k, None) # as long as the field is not the primary key, # map it into the local data strucure elif k != self.key_name: self._data[k] = v # attach the callback to the pipeline. p.on_execute(cb) def _load_all(self, pipe: Optional[PipelineInterface] = None ) -> None: """ Load all data from the redis hash key into this local object. :param pipe: optional pipeline :return: None """ with self._pipe(pipe) as p: ref = self.core(pipe=p).hgetall(self.key) def cb(): if not ref.result: return for k, v in ref.result.items(): if k != self.key_name: self._data[k] = v p.on_execute(cb) def incr(self, field: str, amount: int = 1, pipe: Optional[PipelineInterface] = None) -> Future: """ Increment a field by a given amount. Return the future Also update the field. :param field: :param amount: :param pipe: :return: """ with self._pipe(pipe) as p: core = self.core(pipe=p) # increment the key new_amount = core.hincrby(self.key, field, amount) self._expire(pipe=p) # we also read the value of the field. # this is a little redundant, but otherwise we don't know exactly # how to format the field. # I suppose we could pass the new_amount through the formatter? ref = core.hget(self.key, field) def cb(): """ Once we hear back from redis, set the value locally in the object. :return: """ self._data[field] = ref.result p.on_execute(cb) return new_amount def decr(self, field: str, amount: int = 1, pipe: Optional[PipelineInterface] = None) -> Future: """ Inverse of incr function. :param field: :param amount: :param pipe: :return: Pipeline, NestedPipeline, or None """ return self.incr(field, amount * -1, pipe=pipe) def update(self, changes: Dict[str, Any], pipe: Optional[PipelineInterface] = None, nx: bool = False): """ update the data in the Struct. This will update the values in the underlying redis hash. After the pipeline executes, the changes will be reflected here in the local struct. If any values in the changes dict are None, those fields will be removed from redis and the instance. The changes should be a dictionary representing the fields to change and the values to change them to. If you pass the nx flag, only sets the fields if they don't exist yet. :param changes: dict :param pipe: Pipeline, NestedPipeline, or None :param nx: bool :return: None """ if not changes: return # can't remove the primary key. # maybe you meant to delete the object? # look at delete method. if self.key_name in changes: raise InvalidOperation('cannot update the redis key') # sort the change set into updates and deletes. # the deletes are entries with None as the value. # updates are everything else. deletes = [k for k, v in changes.items() if IS(v, None)] updates = {k: v for k, v in changes.items() if k not in deletes} with self._pipe(pipe) as pipe: core = self.core(pipe=pipe) set_method = core.hsetnx if nx else core.hset def build(k, v): """ Internal closure so we can set the field in redis and set up a callback to write the data into the local instance data once we hear back from redis. :param k: the member of the hash key :param v: the value we want to set :return: None """ res = set_method(self.key, k, v) def cb(): """ Here's the callback. Now that the data has been written to redis, we can update the local state. :return: None """ if not nx or res == 1: self._data[k] = v # attach the callback. pipe.on_execute(cb) # all the other stuff so far was just setup for this part # iterate through the updates and set up the calls to redis # along with the callbacks to update local state once the # changes come back from redis. for k, v in updates.items(): build(k, v) # pass off all the delete operations to the remove call. # happens in the same pipeline. self.remove(deletes, pipe=pipe) self._expire(pipe=pipe) def remove(self, fields, pipe=None): """ remove some fields from the struct. This will remove data from the underlying redis hash object. After the pipe executes successfully, it will also remove it from the current instance of Struct. :param fields: list or iterable, names of the fields to remove. :param pipe: Pipeline, NestedPipeline, or None :return: None """ # no fields specified? It's a no op. if not fields: return # can't remove the primary key. # maybe you meant to call the delete method? if self.key_name in fields: raise InvalidOperation('cannot remove the redis key') removed_required_fields = self.required.intersection(fields) if len(removed_required_fields): raise InvalidOperation('cannot remove required field(s): %s' % list(removed_required_fields)) with self._pipe(pipe) as pipe: # remove all the fields specified from redis. core = self.core(pipe=pipe) core.hdel(self.key, *fields) self._expire(pipe=pipe) # set up a callback to remove the fields from this local object. def cb(): """ once the data has been removed from redis, Remove the data here. :return: """ for k in fields: self._data.pop(k, None) # attach the callback. pipe.on_execute(cb) def copy(self): """ like the dictionary copy method. :return: """ return self.__class__(dict(self)) @property def persisted(self): """ Not certain I want to keep this around. Is it useful? :return: """ return True if self._data else False def clear(self, pipe=None): """ delete the current redis key. :param pipe: :return: """ with self._pipe(pipe) as pipe: self.core(pipe=pipe).delete(self.key) def cb(): self._data = {} pipe.on_execute(cb) def get(self, item, default=None): """ works like the dict get method. :param item: :param default: :return: """ return self._data.get(item, default) def pop(self, name, default=None, pipe=None): """ works like the dictionary pop method. IMPORTANT! This method removes the key from redis. If this is not the behavior you want, first convert your Struct data to a dict. :param name: :param default: :param pipe: :return: """ f = Future() with self._pipe(pipe) as pipe: c = self.core(pipe) ref = c.hget(self.key, name) c.hdel(self.key, name) self._expire(pipe=pipe) def cb(): f.set(default if ref.result is None else ref.result) self._data.pop(name) pipe.on_execute(cb) return f @classmethod def delete(cls, keys, pipe=None): """ Delete one or more keys from the Struct namespace. This is a class method and unlike the `clear` method, can be invoked without instantiating a Struct. :param keys: the names of the keys to remove from the keyspace :param pipe: Pipeline, NestedPipeline, or None :return: None """ with cls._pipe(pipe) as pipe: core = cls.core(pipe) core.delete(*keys) def _expire(self, pipe=None): """ delete the current redis key. :param pipe: :return: """ if self.ttl: self.core(pipe=pipe).expire(self.key, self.ttl) @classmethod def _pipe(cls, pipe: Optional[PipelineInterface] = None ) -> PipelineInterface: """ Internal method for automatically wrapping a pipeline and turning it into a nested pipeline with the correct connection and one that automatically executes as it exits the context. :param pipe: Pipeline, NestedPipeline or None :return: Pipeline or NestedPipeline """ return autoexec(pipe, name=cls.connection) def __getitem__(self, item: str) -> Any: """ magic python method to make the object behave like a dictionary. You can access data like so: .. code-block:: python user = User('1') assert(user['name'] == 'bill') assert(user['_key'] == '1') The primary key is also included in this. If you have defined the name of the primary key, you use that name. Otherwise it defaults to `_key`. If the data doesn't exist in redis, it will raise a KeyError. I thought about making it return None, but if you want that behavior, use the `get` method. :param item: the name of the element in the dictionary :return: the value of the element. """ if item == self.key_name: return self.key return self._data[item] def __delitem__(self, key: str) -> None: """ Explicitly prevent deleting data from the object via the `del` command. .. code-block:: python del user['name'] # raises InvalidOperation exception! The reason is because I want you to use the `remove` method instead. That way you can pipeline the removal of the redis field with something else. Also, you probably want to avoid a scenario where you accidentally delete data from redis without meaning to. :param key: the name of the element to remove from the dict. :raise: InvalidOperation """ tpl = 'cannot delete %s from %s indirectly. Use the delete method.' raise InvalidOperation(tpl % (key, self)) def __setitem__(self, key: str, value: Any) -> None: """ Explicitly prevent setting data into this dictionary-like object. Example: .. code-block:: python user = User('1') user['name'] = 'Bob' # raises InvalidOperation exception RedPipe does not support this because you should be using the `update` method to change properties on the object where you can pipeline the operation with other calls to redis. It also avoids the problem where you accidentally change data if you were confused and thought you were just manipulating a regular dictionary. :param key: the name of the element in this pseudo dict. :param value: the value to set it to :raise: InvalidOperation """ tpl = 'cannot set %s key on %s indirectly. Use the update method.' raise InvalidOperation(tpl % (key, self)) def __getattr__(self, item: str) -> Any: """ magic python method -- returns fields as an attribute of the object. This is off by default. You can enable it by setting `field_attr_on = True` on your struct. Then you can access data like so: .. code-block:: python user = User('1') assert(user.name == 'bill') :param item: str :return: mixed """ try: if self.field_attr_on: if item == self.key_name: return self.key return self._data[item] except KeyError: if item in self.fields: return None raise AttributeError( "'%s' object has no attribute '%s'" % ( self.__class__.__name__, item)) def __setattr__(self, key, value) -> None: """ magic python method to control setting attributes on the object. :param key: :param value: :return: """ if self.field_attr_on and key in self.fields: tpl = 'cannot set %s.%s directly. Use the update method.' raise InvalidOperation(tpl % (self, key)) if key in self.__slots__ or key in self.__dict__: return super(Struct, self).__setattr__(key, value) raise AttributeError("'%s' object has no attribute '%s'" % (self.__class__.__name__, key)) def __iter__(self) -> Iterable[str]: """ Make the `Struct` iterable, like a dictionary. When you iterate on a dict, it yields the keys of the dictionary. Emulating the same behavior here. :return: generator, a list of key names in the Struct """ for k in self.keys(): yield k def __len__(self) -> int: """ How many elements in the Struct? This includes all the fields returned from redis + the key. :return: int """ return len(dict(self)) def __contains__(self, item): if item == self.key_name: return True return item in self._data def iteritems(self) -> Iterable[Tuple[str, Any]]: """ Support for the python 2 iterator of key/value pairs. This includes the primary key name and value. Example: .. code-block:: python u = User('1') data = {k: v for k, v in u.iteritems()} Or: .. code-block:: python u = User('1') for k, v in u.iteritems(): print("%s: %s" % (k, v) :return: generator, a list of key/value pair tuples """ yield self.key_name, self.key for k, v in self._data.items(): yield k, v def items(self) -> List[Tuple[str, Any]]: """ We return the list of key/value pair tuples. Similar to iteritems but in list form instead of as a generator. The reason we do this is because python2 code probably expects this to be a list. Not sure if I could care, but just covering my bases. Example: .. code-block:: python u = User('1') data = {k: v for k, v in u.items()} Or: .. code-block:: python u = User('1') for k, v in u.items(): print("%s: %s" % (k, v) :return: list, containing key/value pair tuples. """ return [row for row in self.iteritems()] def __eq__(self, other: Any): """ Test for equality with another python object. Example: ..code-block:: python u = User('1') assert(u == {'_key': '1', 'name': 'Bob'}) assert(u == User('1')) The object you pass in should be a dict or an object that can be coerced into a dict, like another Struct. Returns True if all the keys and values match up. :param other: can be another dictionary, or a Struct. :return: bool """ if self is other: return True try: if dict(self) == dict(other): return True except (TypeError, ValueError): pass return False def keys(self) -> List[str]: """ Get a list of all the keys in the Struct. This includes the primary key name, and all the elements that are set into redis. Note: even if you define fields on the Struct, those keys won't be returned unless the fields are actually written into the redis hash. .. code-block:: python u = User('1') assert(u.keys() == ['_key', 'name']) :return: list """ return [row[0] for row in self.items()] def __str__(self): """ A simple string representation of the object. Contins the class name, and the primary key. Doesn't print out all the data. The reason is because there could be some really complex data types in there or some really big values. Printing that out, especially in the context of an exception seems like a bad idea. :return: str """ return "<%s:%s>" % (self.__class__.__name__, self.key) def __repr__(self): """ Emulate the behavior of a dict when it is passed to repr. :return: str """ return repr(dict(self)) def __getstate__(self): """ Used for pickling the Struct. :return: tuple of key, and internal `_data` """ return self.key, self._data, def __setstate__(self, state): """ used for unplickling the Struct. :param state: :return: """ self.key = state[0] self._data = state[1] @property def _redpipe_struct_as_dict(self): """ A special namespaced property used for json encoding. We use duck-typing and look for this property (which no other type of object should have) so that we can try to json serialize it by coercing it into a dict. :return: dict """ return dict(self)
class Struct(metaclass=StructMeta): ''' load and store structured data in redis using OOP patterns. If you pass in a dictionary-like object, redpipe will write all the values you pass in to redis to the key you specify. By default, the primary key name is `_key`. But you should override this in your Struct with the `key_name` property. .. code-block:: python class Beer(redpipe.Struct): fields = {'name': redpipe.TextField} key_name = 'beer_id' beer = Beer({'beer_id': '1', 'name': 'Schlitz'}) This will store the data you pass into redis. It will also load any additional fields to hydrate the object. **RedPipe** does this in the same pipelined call. If you need a stub record that neither loads or saves data, do: .. code-block:: python beer = Beer({'beer_id': '1'}, no_op=True) You can later load the fields you want using, load. If you pass in a string we assume it is the key of the record. redpipe loads the data from redis: .. code-block:: python beer = Beer('1') assert(beer['beer_id'] == '1') assert(beer['name'] == 'Schlitz') If you need to load a record but only specific fields, you can say so. .. code-block:: python beer = Beer('1', fields=['name']) This will exclude all other fields. **RedPipe** cares about pipelining and efficiency, so if you need to bundle a bunch of reads or writes together, by all means do so! .. code-block:: python beer_ids = ['1', '2', '3'] with redpipe.pipeline() as pipe: beers = [Beer(i, pipe=pipe) for i in beer_ids] print(beers) This will pipeline all 3 together and load them in a single pass from redis. The following methods all accept a pipe: * __init__ * update * incr * decr * pop * remove * clear * delete You can pass a pipeline into them to make sure that the network i/o is combined with another pipeline operation. The other methods on the object are about accessing the data already loaded. So you shouldn't need to pipeline them. One more thing ... suppose you are storing temporary data and you want it to expire after a few days. You can easily make that happen just by changing the object definition: .. code-block:: python class Beer(redpipe.Struct): fields = {'name': redpipe.TextField} key_name = 'beer_id' ttl = 24 * 60 * 60 * 3 This makes sure that any set operations on the Struct will set the expiry at the same time. If the object isn't modified for more than the seconds specified in the ttl (stands for time-to-live), then the object will be expired from redis. This is useful for temporary objects. ''' def __init__(self, _key_or_data: Union[str, Dict], pipe: Optional[PipelineInterface] = None, fields: Union[str, List[str], None] = None, no_op: bool = False, nx: bool = False): ''' class constructor :param _key_or_data: :param pipe: :param fields: :param no_op: bool :param nx: bool ''' pass def load(self, fields: Union[str, List[str], None] = None, pipe: Optional[PipelineInterface] = None) -> None: ''' Load data from redis. Allows you to specify what fields to load. This method is also called implicitly from the constructor. :param fields: 'all', 'defined', or array of field names :param pipe: Pipeline(), NestedPipeline() or None :return: None ''' pass def cb(): ''' This callback fires when the root pipeline executes. At that point, we hydrate the response into this object. :return: None ''' pass def _load_all(self, pipe: Optional[PipelineInterface] = None ) -> None: ''' Load all data from the redis hash key into this local object. :param pipe: optional pipeline :return: None ''' pass def cb(): pass def incr(self, field: str, amount: int = 1, pipe: Optional[PipelineInterface] = None) -> Future: ''' Increment a field by a given amount. Return the future Also update the field. :param field: :param amount: :param pipe: :return: ''' pass def cb(): ''' Once we hear back from redis, set the value locally in the object. :return: ''' pass def decr(self, field: str, amount: int = 1, pipe: Optional[PipelineInterface] = None) -> Future: ''' Inverse of incr function. :param field: :param amount: :param pipe: :return: Pipeline, NestedPipeline, or None ''' pass def update(self, changes: Dict[str, Any], pipe: Optional[PipelineInterface] = None, nx: bool = False): ''' update the data in the Struct. This will update the values in the underlying redis hash. After the pipeline executes, the changes will be reflected here in the local struct. If any values in the changes dict are None, those fields will be removed from redis and the instance. The changes should be a dictionary representing the fields to change and the values to change them to. If you pass the nx flag, only sets the fields if they don't exist yet. :param changes: dict :param pipe: Pipeline, NestedPipeline, or None :param nx: bool :return: None ''' pass def build(k, v): ''' Internal closure so we can set the field in redis and set up a callback to write the data into the local instance data once we hear back from redis. :param k: the member of the hash key :param v: the value we want to set :return: None ''' pass def cb(): ''' Here's the callback. Now that the data has been written to redis, we can update the local state. :return: None ''' pass def remove(self, fields, pipe=None): ''' remove some fields from the struct. This will remove data from the underlying redis hash object. After the pipe executes successfully, it will also remove it from the current instance of Struct. :param fields: list or iterable, names of the fields to remove. :param pipe: Pipeline, NestedPipeline, or None :return: None ''' pass def cb(): ''' once the data has been removed from redis, Remove the data here. :return: ''' pass def copy(self): ''' like the dictionary copy method. :return: ''' pass @property def persisted(self): ''' Not certain I want to keep this around. Is it useful? :return: ''' pass def clear(self, pipe=None): ''' delete the current redis key. :param pipe: :return: ''' pass def cb(): pass def get(self, item, default=None): ''' works like the dict get method. :param item: :param default: :return: ''' pass def pop(self, name, default=None, pipe=None): ''' works like the dictionary pop method. IMPORTANT! This method removes the key from redis. If this is not the behavior you want, first convert your Struct data to a dict. :param name: :param default: :param pipe: :return: ''' pass def cb(): pass @classmethod def delete(cls, keys, pipe=None): ''' Delete one or more keys from the Struct namespace. This is a class method and unlike the `clear` method, can be invoked without instantiating a Struct. :param keys: the names of the keys to remove from the keyspace :param pipe: Pipeline, NestedPipeline, or None :return: None ''' pass def _expire(self, pipe=None): ''' delete the current redis key. :param pipe: :return: ''' pass @classmethod def _pipe(cls, pipe: Optional[PipelineInterface] = None ) -> PipelineInterface: ''' Internal method for automatically wrapping a pipeline and turning it into a nested pipeline with the correct connection and one that automatically executes as it exits the context. :param pipe: Pipeline, NestedPipeline or None :return: Pipeline or NestedPipeline ''' pass def __getitem__(self, item: str) -> Any: ''' magic python method to make the object behave like a dictionary. You can access data like so: .. code-block:: python user = User('1') assert(user['name'] == 'bill') assert(user['_key'] == '1') The primary key is also included in this. If you have defined the name of the primary key, you use that name. Otherwise it defaults to `_key`. If the data doesn't exist in redis, it will raise a KeyError. I thought about making it return None, but if you want that behavior, use the `get` method. :param item: the name of the element in the dictionary :return: the value of the element. ''' pass def __delitem__(self, key: str) -> None: ''' Explicitly prevent deleting data from the object via the `del` command. .. code-block:: python del user['name'] # raises InvalidOperation exception! The reason is because I want you to use the `remove` method instead. That way you can pipeline the removal of the redis field with something else. Also, you probably want to avoid a scenario where you accidentally delete data from redis without meaning to. :param key: the name of the element to remove from the dict. :raise: InvalidOperation ''' pass def __setitem__(self, key: str, value: Any) -> None: ''' Explicitly prevent setting data into this dictionary-like object. Example: .. code-block:: python user = User('1') user['name'] = 'Bob' # raises InvalidOperation exception RedPipe does not support this because you should be using the `update` method to change properties on the object where you can pipeline the operation with other calls to redis. It also avoids the problem where you accidentally change data if you were confused and thought you were just manipulating a regular dictionary. :param key: the name of the element in this pseudo dict. :param value: the value to set it to :raise: InvalidOperation ''' pass def __getattr__(self, item: str) -> Any: ''' magic python method -- returns fields as an attribute of the object. This is off by default. You can enable it by setting `field_attr_on = True` on your struct. Then you can access data like so: .. code-block:: python user = User('1') assert(user.name == 'bill') :param item: str :return: mixed ''' pass def __setattr__(self, key, value) -> None: ''' magic python method to control setting attributes on the object. :param key: :param value: :return: ''' pass def __iter__(self) -> Iterable[str]: ''' Make the `Struct` iterable, like a dictionary. When you iterate on a dict, it yields the keys of the dictionary. Emulating the same behavior here. :return: generator, a list of key names in the Struct ''' pass def __len__(self) -> int: ''' How many elements in the Struct? This includes all the fields returned from redis + the key. :return: int ''' pass def __contains__(self, item): pass def iteritems(self) -> Iterable[Tuple[str, Any]]: ''' Support for the python 2 iterator of key/value pairs. This includes the primary key name and value. Example: .. code-block:: python u = User('1') data = {k: v for k, v in u.iteritems()} Or: .. code-block:: python u = User('1') for k, v in u.iteritems(): print("%s: %s" % (k, v) :return: generator, a list of key/value pair tuples ''' pass def items(self) -> List[Tuple[str, Any]]: ''' We return the list of key/value pair tuples. Similar to iteritems but in list form instead of as a generator. The reason we do this is because python2 code probably expects this to be a list. Not sure if I could care, but just covering my bases. Example: .. code-block:: python u = User('1') data = {k: v for k, v in u.items()} Or: .. code-block:: python u = User('1') for k, v in u.items(): print("%s: %s" % (k, v) :return: list, containing key/value pair tuples. ''' pass def __eq__(self, other: Any): ''' Test for equality with another python object. Example: ..code-block:: python u = User('1') assert(u == {'_key': '1', 'name': 'Bob'}) assert(u == User('1')) The object you pass in should be a dict or an object that can be coerced into a dict, like another Struct. Returns True if all the keys and values match up. :param other: can be another dictionary, or a Struct. :return: bool ''' pass def keys(self) -> List[str]: ''' Get a list of all the keys in the Struct. This includes the primary key name, and all the elements that are set into redis. Note: even if you define fields on the Struct, those keys won't be returned unless the fields are actually written into the redis hash. .. code-block:: python u = User('1') assert(u.keys() == ['_key', 'name']) :return: list ''' pass def __str__(self): ''' A simple string representation of the object. Contins the class name, and the primary key. Doesn't print out all the data. The reason is because there could be some really complex data types in there or some really big values. Printing that out, especially in the context of an exception seems like a bad idea. :return: str ''' pass def __repr__(self): ''' Emulate the behavior of a dict when it is passed to repr. :return: str ''' pass def __getstate__(self): ''' Used for pickling the Struct. :return: tuple of key, and internal `_data` ''' pass def __setstate__(self, state): ''' used for unplickling the Struct. :param state: :return: ''' pass @property def _redpipe_struct_as_dict(self): ''' A special namespaced property used for json encoding. We use duck-typing and look for this property (which no other type of object should have) so that we can try to json serialize it by coercing it into a dict. :return: dict ''' pass
45
37
20
4
6
10
2
1.84
1
15
3
0
30
2
32
46
853
198
231
101
173
424
204
80
163
6
3
4
80
1,508
72squared/redpipe
72squared_redpipe/redpipe/pipelines.py
redpipe.pipelines.PipelineInterface
class PipelineInterface(Protocol): def execute(self) -> None: ... def on_execute(self, callback: Callable) -> None: ... def reset(self) -> None: ... def __getattr__(self, item: str): ... def __enter__(self): ... def __exit__(self, exc_type, exc_val, exc_tb) -> None: ...
class PipelineInterface(Protocol): def execute(self) -> None: pass def on_execute(self, callback: Callable) -> None: pass def reset(self) -> None: pass def __getattr__(self, item: str): pass def __enter__(self): pass def __exit__(self, exc_type, exc_val, exc_tb) -> None: pass
7
0
1
0
1
0
1
0
1
1
0
0
6
0
6
30
13
6
7
7
6
0
13
7
6
1
5
0
6
1,509
72squared/redpipe
72squared_redpipe/redpipe/pipelines.py
redpipe.pipelines.Pipeline
class Pipeline(object): """ Wrapper for redispy pipeline object. It returns a reference that contains a result once the pipeline executes. This allows us to be able to pipeline lots of calls within nested functions and not have to wait for the execute call. Don't instantiate this class directly. Instead, use the redpipe.pipeline(pipe) function which will set up this object correctly. """ __slots__ = ['connection_name', 'autoexec', '_stack', '_callbacks', '_pipelines', '_exit_handler'] def __init__(self, name: Optional[str], autoexec: bool = False, # noqa exit_handler: Optional[Callable] = None): """ Instantiate a new base pipeline object. This pipeline will be responsible for executing all the others that potentially get attached to it, including other named pipelines and any commands from nested pipelines. :param name: str The name of the connection :param autoexec: bool, whether or not to implicitly execute the pipe. """ self.connection_name: Optional[str] = name self._stack: List[Tuple[str, Tuple, Dict, Future]] = [] self._callbacks: List[Callable] = [] self.autoexec: bool = autoexec self._pipelines: Dict[str, Union[Pipeline, NestedPipeline]] = {} self._exit_handler: Optional[Callable] = exit_handler def __getattr__(self, item: str): """ when you call a command like `pipeline().incr('foo')` it winds up here. the item would be 'incr', because python can't find that attribute. We build a custom function for it on the fly. :param item: str, the name of the function we are wrapping. :return: callable """ def command(*args, **kwargs): """ track all the arguments passed to this function along with the function name (item). That way when pipe.execute() happens, we'll be able to run it. Return a Future object that will eventually contain the result of a redis call. :param args: array :param kwargs: dict :return: Future """ future = Future() self._stack.append((item, args, kwargs, future)) return future return command @staticmethod def supports_redpipe_pipeline() -> bool: return True def _pipeline(self, name) -> PipelineInterface: """ Don't call this function directly. Used by the NestedPipeline class when it executes. :param name: :return: """ if name == self.connection_name: return self try: return self._pipelines[name] except KeyError: pipe = Pipeline(name=name, autoexec=True) self._pipelines[name] = pipe return pipe def execute(self) -> None: """ Invoke the redispy pipeline.execute() method and take all the values returned in sequential order of commands and map them to the Future objects we returned when each command was queued inside the pipeline. Also invoke all the callback functions queued up. :return: None """ stack = self._stack callbacks = self._callbacks promises = [] if stack: def process(): """ take all the commands and pass them to redis. this closure has the context of the stack :return: None """ # get the connection to redis pipe = ConnectionManager.get(self.connection_name) # keep track of all the commands call_stack = [] # build a corresponding list of the futures futures = [] # we need to do this because we need to make sure # all of these are callable. # there shouldn't be any non-callables. for item, args, kwargs, future in stack: f = getattr(pipe, item) if callable(f): futures.append(future) call_stack.append((f, args, kwargs)) # here's where we actually pass the commands to the # underlying redis-py pipeline() object. for f, args, kwargs in call_stack: f(*args, **kwargs) # execute the redis-py pipeline. # map all of the results into the futures. for i, v in enumerate(pipe.execute()): futures[i].set(v) promises.append(process) # collect all the other pipelines for other named connections attached. promises += [p.execute for p in self._pipelines.values()] if len(promises) == 1: promises[0]() else: # if there are no promises, this is basically a no-op. TaskManager.wait(*[TaskManager.promise(p) for p in promises]) for cb in callbacks: cb() def __enter__(self) -> PipelineInterface: """ magic method to allow us to use in context like this: with Pipeline(redis.Redis().pipeline()) as pipe: ref = pipe.set('foo', 'bar') pipe.execute() we are overriding the behavior in redispy. :return: Pipeline instance """ return self def __exit__(self, exc_type, exc_val, exc_tb) -> None: """ context manager cleanup method. :param exc_type: :param exc_val: :param exc_tb: :return: """ try: if exc_type is None and self.autoexec: self.execute() finally: self.reset() cb = self._exit_handler if cb: cb() def reset(self) -> None: """ cleanup method. get rid of the stack and callbacks. :return: """ self._stack = [] self._callbacks = [] pipes = self._pipelines self._pipelines = {} for pipe in pipes.values(): pipe.reset() def on_execute(self, callback: Callable) -> None: """ attach a callback to be called when the pipe finally executes. :param callback: :return: """ self._callbacks.append(callback) def _inject_callbacks(self, callbacks) -> None: self._callbacks[0:0] = callbacks
class Pipeline(object): ''' Wrapper for redispy pipeline object. It returns a reference that contains a result once the pipeline executes. This allows us to be able to pipeline lots of calls within nested functions and not have to wait for the execute call. Don't instantiate this class directly. Instead, use the redpipe.pipeline(pipe) function which will set up this object correctly. ''' def __init__(self, name: Optional[str], autoexec: bool = False, # noqa exit_handler: Optional[Callable] = None): ''' Instantiate a new base pipeline object. This pipeline will be responsible for executing all the others that potentially get attached to it, including other named pipelines and any commands from nested pipelines. :param name: str The name of the connection :param autoexec: bool, whether or not to implicitly execute the pipe. ''' pass def __getattr__(self, item: str): ''' when you call a command like `pipeline().incr('foo')` it winds up here. the item would be 'incr', because python can't find that attribute. We build a custom function for it on the fly. :param item: str, the name of the function we are wrapping. :return: callable ''' pass def command(*args, **kwargs): ''' track all the arguments passed to this function along with the function name (item). That way when pipe.execute() happens, we'll be able to run it. Return a Future object that will eventually contain the result of a redis call. :param args: array :param kwargs: dict :return: Future ''' pass @staticmethod def supports_redpipe_pipeline() -> bool: pass def _pipeline(self, name) -> PipelineInterface: ''' Don't call this function directly. Used by the NestedPipeline class when it executes. :param name: :return: ''' pass def execute(self) -> None: ''' Invoke the redispy pipeline.execute() method and take all the values returned in sequential order of commands and map them to the Future objects we returned when each command was queued inside the pipeline. Also invoke all the callback functions queued up. :return: None ''' pass def process(): ''' take all the commands and pass them to redis. this closure has the context of the stack :return: None ''' pass def __enter__(self) -> PipelineInterface: ''' magic method to allow us to use in context like this: with Pipeline(redis.Redis().pipeline()) as pipe: ref = pipe.set('foo', 'bar') pipe.execute() we are overriding the behavior in redispy. :return: Pipeline instance ''' pass def __exit__(self, exc_type, exc_val, exc_tb) -> None: ''' context manager cleanup method. :param exc_type: :param exc_val: :param exc_tb: :return: ''' pass def reset(self) -> None: ''' cleanup method. get rid of the stack and callbacks. :return: ''' pass def on_execute(self, callback: Callable) -> None: ''' attach a callback to be called when the pipe finally executes. :param callback: :return: ''' pass def _inject_callbacks(self, callbacks) -> None: pass
14
11
19
2
8
9
2
1.16
1
9
5
0
9
6
10
10
199
29
79
39
62
92
72
35
59
5
1
2
24
1,510
72squared/redpipe
72squared_redpipe/redpipe/pipelines.py
redpipe.pipelines.NestedPipeline
class NestedPipeline(object): """ Keep track of a parent pipeline object (either a `Pipeline` object or another `NestedPipeline` object. Queue the commands and pass them to the parent on execute. Don't instantiate this class directly. Instead, use the redpipe.pipeline(pipe) function which will set up this object correctly. """ __slots__ = ['connection_name', 'parent', 'autoexec', '_stack', '_callbacks', '_exit_handler'] def __init__(self, parent: PipelineInterface, name: Optional[str] = None, autoexec: bool = False, # noqa exit_handler: Optional[Callable] = None): """ Similar interface to the Pipeline object, but with the ability to also track a parent pipeline object. :param parent: Pipeline() or NestedPipeline() :param name: str, the name of the connection :param autoexec: bool, implicitly call execute? """ self.connection_name: Optional[str] = name self.parent: PipelineInterface = parent self._stack: List[Tuple[str, Tuple, Dict, Future]] = [] self._callbacks: List[Callable] = [] self.autoexec: bool = autoexec self._exit_handler: Optional[Callable] = exit_handler @staticmethod def supports_redpipe_pipeline() -> bool: """ used by the `redpipe.pipeline()` function to determine if it can be nested inside other pipeline objects. Do not call directly. :return: """ return True def __getattr__(self, item): """ when you call a command like `pipeline(pipe).incr('foo')` it winds up here. the item would be 'incr', because python can't find that attribute. We build a custom function for it on the fly. :param item: str, the name of the function we are wrapping. :return: callable """ def command(*args, **kwargs): """ track all the arguments passed to this function along with the function name (item). That way when pipe.execute() happens, we'll be able to run it. Return a Future object that will eventually contain the result of a redis call. :param args: array :param kwargs: dict :return: Future """ future = Future() self._stack.append((item, args, kwargs, future)) return future return command def _pipeline(self, name): """ Don't call directly. Used by other NestedPipeline objects. :param name: :return: """ return getattr(self.parent, '_pipeline')(name) def execute(self): """ execute the commands inside the nested pipeline. This causes all queued up commands to be passed upstream to the parent, including callbacks. The state of this pipeline object gets cleaned up. :return: """ stack = self._stack callbacks = self._callbacks self._stack = [] self._callbacks = [] deferred = [] build = self._nested_future pipe = self._pipeline(self.connection_name) for item, args, kwargs, ref in stack: f = getattr(pipe, item) deferred.append(build(f(*args, **kwargs), ref)) inject_callbacks = getattr(self.parent, '_inject_callbacks') inject_callbacks(deferred + callbacks) def on_execute(self, callback): """ same purpose as the Pipeline().on_execute() method. In this case, it queues them so that when the nested pipeline executes, :param callback: callable :return: None """ self._callbacks.append(callback) def _inject_callbacks(self, callbacks): self._callbacks[0:0] = callbacks @staticmethod def _nested_future(r, future): """ A utility function to map one future result into another future via callback. :param r: :param future: :return: """ def cb(): future.set(r.result) return cb def reset(self): self._stack = [] self._callbacks = [] def __enter__(self): return self def __exit__(self, exc_type, exc_val, exc_tb): try: if exc_type is None and self.autoexec: self.execute() finally: self.reset() cb = self._exit_handler if cb: cb()
class NestedPipeline(object): ''' Keep track of a parent pipeline object (either a `Pipeline` object or another `NestedPipeline` object. Queue the commands and pass them to the parent on execute. Don't instantiate this class directly. Instead, use the redpipe.pipeline(pipe) function which will set up this object correctly. ''' def __init__(self, parent: PipelineInterface, name: Optional[str] = None, autoexec: bool = False, # noqa exit_handler: Optional[Callable] = None): ''' Similar interface to the Pipeline object, but with the ability to also track a parent pipeline object. :param parent: Pipeline() or NestedPipeline() :param name: str, the name of the connection :param autoexec: bool, implicitly call execute? ''' pass @staticmethod def supports_redpipe_pipeline() -> bool: ''' used by the `redpipe.pipeline()` function to determine if it can be nested inside other pipeline objects. Do not call directly. :return: ''' pass def __getattr__(self, item): ''' when you call a command like `pipeline(pipe).incr('foo')` it winds up here. the item would be 'incr', because python can't find that attribute. We build a custom function for it on the fly. :param item: str, the name of the function we are wrapping. :return: callable ''' pass def command(*args, **kwargs): ''' track all the arguments passed to this function along with the function name (item). That way when pipe.execute() happens, we'll be able to run it. Return a Future object that will eventually contain the result of a redis call. :param args: array :param kwargs: dict :return: Future ''' pass def _pipeline(self, name): ''' Don't call directly. Used by other NestedPipeline objects. :param name: :return: ''' pass def execute(self): ''' execute the commands inside the nested pipeline. This causes all queued up commands to be passed upstream to the parent, including callbacks. The state of this pipeline object gets cleaned up. :return: ''' pass def on_execute(self, callback): ''' same purpose as the Pipeline().on_execute() method. In this case, it queues them so that when the nested pipeline executes, :param callback: callable :return: None ''' pass def _inject_callbacks(self, callbacks): pass @staticmethod def _nested_future(r, future): ''' A utility function to map one future result into another future via callback. :param r: :param future: :return: ''' pass def cb(): pass def reset(self): pass def __enter__(self): pass def __exit__(self, exc_type, exc_val, exc_tb): pass
16
9
11
1
5
5
1
1.11
1
4
2
0
9
6
11
11
149
21
61
37
41
68
53
31
39
3
1
2
16
1,511
72squared/redpipe
72squared_redpipe/redpipe/keyspaces.py
redpipe.keyspaces.String
class String(Keyspace): """ Manipulate a String key in Redis. """ def get(self, name: str) -> Future[str]: """ Return the value of the key or None if the key doesn't exist :param name: str the name of the redis key :return: Future() """ with self.pipe as pipe: f = Future[str]() res = pipe.get(self.redis_key(name)) def cb(): decode = self.valueparse.decode f.set(decode(res.result)) pipe.on_execute(cb) return f def mget(self, keys: Union[str, typing.List[str]], *args: str) -> Future: """ Returns a list of values ordered identically to ``keys`` """ rkeys = [self.redis_key(k) for k in self._parse_values(keys, args)] with self.pipe as pipe: f = Future[typing.List[Any]]() res = pipe.mget(rkeys) def cb(): decode = self.valueparse.decode f.set([None if r is None else decode(r) for r in res.result]) pipe.on_execute(cb) return f def set(self, name: str, value: str, ex: Optional[int] = None, px: Optional[int] = None, nx: bool = False, xx: bool = False) -> Future: """ Set the value at key ``name`` to ``value`` ``ex`` sets an expire flag on key ``name`` for ``ex`` seconds. ``px`` sets an expire flag on key ``name`` for ``px`` milliseconds. ``nx`` if set to True, set the value at key ``name`` to ``value`` if it does not already exist. ``xx`` if set to True, set the value at key ``name`` to ``value`` if it already exists. :return: Future() """ with self.pipe as pipe: return pipe.set(self.redis_key(name), self.valueparse.encode(value), ex=ex, px=px, nx=nx, xx=xx) def setnx(self, name: str, value: str) -> int: """ Set the value as a string in the key only if the key doesn't exist. :param name: str the name of the redis key :param value: :return: Future() """ with self.pipe as pipe: return pipe.setnx(self.redis_key(name), self.valueparse.encode(value)) def setex(self, name: str, value: str, time: int) -> Future: """ Set the value of key to ``value`` that expires in ``time`` seconds. ``time`` can be represented by an integer or a Python timedelta object. :param name: str the name of the redis key :param value: str :param time: secs :return: Future() """ with self.pipe as pipe: return pipe.setex(self.redis_key(name), value=self.valueparse.encode(value), time=time) def psetex(self, name: str, value: str, time_ms: int) -> Future: """ Set the value of key ``name`` to ``value`` that expires in ``time_ms`` milliseconds. ``time_ms`` can be represented by an integer or a Python timedelta object """ with self.pipe as pipe: return pipe.psetex(self.redis_key(name), time_ms=time_ms, value=self.valueparse.encode(value=value)) def append(self, name: str, value: str) -> Future: """ Appends the string ``value`` to the value at ``key``. If ``key`` doesn't already exist, create it with a value of ``value``. Returns the new length of the value at ``key``. :param name: str the name of the redis key :param value: str :return: Future() """ with self.pipe as pipe: return pipe.append(self.redis_key(name), self.valueparse.encode(value)) def strlen(self, name: str) -> Future: """ Return the number of bytes stored in the value of the key :param name: str the name of the redis key :return: Future() """ with self.pipe as pipe: return pipe.strlen(self.redis_key(name)) def substr(self, name: str, start: int, end: int = -1) -> Future[str]: """ Return a substring of the string at key ``name``. ``start`` and ``end`` are 0-based integers specifying the portion of the string to return. :param name: str the name of the redis key :param start: int :param end: int :return: Future() """ with self.pipe as pipe: f = Future[str]() res = pipe.substr(self.redis_key(name), start=start, end=end) def cb(): f.set(self.valueparse.decode(res.result)) pipe.on_execute(cb) return f def setrange(self, name: str, offset: int, value: str) -> Future: """ Overwrite bytes in the value of ``name`` starting at ``offset`` with ``value``. If ``offset`` plus the length of ``value`` exceeds the length of the original value, the new value will be larger than before. If ``offset`` exceeds the length of the original value, null bytes will be used to pad between the end of the previous value and the start of what's being injected. Returns the length of the new string. :param name: str the name of the redis key :param offset: int :param value: str :return: Future() """ with self.pipe as pipe: return pipe.setrange(self.redis_key(name), offset, value) def setbit(self, name: str, offset: int, value: str) -> Future: """ Flag the ``offset`` in the key as ``value``. Returns a boolean indicating the previous value of ``offset``. :param name: str the name of the redis key :param offset: int :param value: :return: Future() """ with self.pipe as pipe: return pipe.setbit(self.redis_key(name), offset, value) def getbit(self, name: str, offset: int) -> Future: """ Returns a boolean indicating the value of ``offset`` in key :param name: str the name of the redis key :param offset: int :return: Future() """ with self.pipe as pipe: return pipe.getbit(self.redis_key(name), offset) def bitcount(self, name, start=None, end=None) -> Future: """ Returns the count of set bits in the value of ``key``. Optional ``start`` and ``end`` paramaters indicate which bytes to consider :param name: str the name of the redis key :param start: int :param end: int :return: Future() """ with self.pipe as pipe: return pipe.bitcount(self.redis_key(name), start=start, end=end) def incr(self, name: str, amount: int = 1) -> Future: """ increment the value for key by 1 :param name: str the name of the redis key :param amount: int :return: Future() """ with self.pipe as pipe: return pipe.incr(self.redis_key(name), amount=amount) def incrby(self, name: str, amount: int = 1) -> Future: """ increment the value for key by value: int :param name: str the name of the redis key :param amount: int :return: Future() """ with self.pipe as pipe: return pipe.incrby(self.redis_key(name), amount=amount) def incrbyfloat(self, name: str, amount: float = 1.0) -> Future: """ increment the value for key by value: float :param name: str the name of the redis key :param amount: int :return: Future() """ with self.pipe as pipe: return pipe.incrbyfloat(self.redis_key(name), amount=amount) def __getitem__(self, name: str) -> Any: """ magic python method that makes the class behave like a dictionary. use to access elements. :param name: :return: """ return self.get(name) def __setitem__(self, name: str, value: str) -> None: """ magic python method that makes the class behave like a dictionary. use to set elements. :param name: :param value: :return: """ self.set(name, value)
class String(Keyspace): ''' Manipulate a String key in Redis. ''' def get(self, name: str) -> Future[str]: ''' Return the value of the key or None if the key doesn't exist :param name: str the name of the redis key :return: Future() ''' pass def cb(): pass def mget(self, keys: Union[str, typing.List[str]], *args: str) -> Future: ''' Returns a list of values ordered identically to ``keys`` ''' pass def cb(): pass def set(self, name: str, value: str, ex: Optional[int] = None, px: Optional[int] = None, nx: bool = False, xx: bool = False) -> Future: ''' Set the value at key ``name`` to ``value`` ``ex`` sets an expire flag on key ``name`` for ``ex`` seconds. ``px`` sets an expire flag on key ``name`` for ``px`` milliseconds. ``nx`` if set to True, set the value at key ``name`` to ``value`` if it does not already exist. ``xx`` if set to True, set the value at key ``name`` to ``value`` if it already exists. :return: Future() ''' pass def setnx(self, name: str, value: str) -> int: ''' Set the value as a string in the key only if the key doesn't exist. :param name: str the name of the redis key :param value: :return: Future() ''' pass def setex(self, name: str, value: str, time: int) -> Future: ''' Set the value of key to ``value`` that expires in ``time`` seconds. ``time`` can be represented by an integer or a Python timedelta object. :param name: str the name of the redis key :param value: str :param time: secs :return: Future() ''' pass def psetex(self, name: str, value: str, time_ms: int) -> Future: ''' Set the value of key ``name`` to ``value`` that expires in ``time_ms`` milliseconds. ``time_ms`` can be represented by an integer or a Python timedelta object ''' pass def append(self, name: str, value: str) -> Future: ''' Appends the string ``value`` to the value at ``key``. If ``key`` doesn't already exist, create it with a value of ``value``. Returns the new length of the value at ``key``. :param name: str the name of the redis key :param value: str :return: Future() ''' pass def strlen(self, name: str) -> Future: ''' Return the number of bytes stored in the value of the key :param name: str the name of the redis key :return: Future() ''' pass def substr(self, name: str, start: int, end: int = -1) -> Future[str]: ''' Return a substring of the string at key ``name``. ``start`` and ``end`` are 0-based integers specifying the portion of the string to return. :param name: str the name of the redis key :param start: int :param end: int :return: Future() ''' pass def cb(): pass def setrange(self, name: str, offset: int, value: str) -> Future: ''' Overwrite bytes in the value of ``name`` starting at ``offset`` with ``value``. If ``offset`` plus the length of ``value`` exceeds the length of the original value, the new value will be larger than before. If ``offset`` exceeds the length of the original value, null bytes will be used to pad between the end of the previous value and the start of what's being injected. Returns the length of the new string. :param name: str the name of the redis key :param offset: int :param value: str :return: Future() ''' pass def setbit(self, name: str, offset: int, value: str) -> Future: ''' Flag the ``offset`` in the key as ``value``. Returns a boolean indicating the previous value of ``offset``. :param name: str the name of the redis key :param offset: int :param value: :return: Future() ''' pass def getbit(self, name: str, offset: int) -> Future: ''' Returns a boolean indicating the value of ``offset`` in key :param name: str the name of the redis key :param offset: int :return: Future() ''' pass def bitcount(self, name, start=None, end=None) -> Future: ''' Returns the count of set bits in the value of ``key``. Optional ``start`` and ``end`` paramaters indicate which bytes to consider :param name: str the name of the redis key :param start: int :param end: int :return: Future() ''' pass def incr(self, name: str, amount: int = 1) -> Future: ''' increment the value for key by 1 :param name: str the name of the redis key :param amount: int :return: Future() ''' pass def incrby(self, name: str, amount: int = 1) -> Future: ''' increment the value for key by value: int :param name: str the name of the redis key :param amount: int :return: Future() ''' pass def incrbyfloat(self, name: str, amount: float = 1.0) -> Future: ''' increment the value for key by value: float :param name: str the name of the redis key :param amount: int :return: Future() ''' pass def __getitem__(self, name: str) -> Any: ''' magic python method that makes the class behave like a dictionary. use to access elements. :param name: :return: ''' pass def __setitem__(self, name: str, value: str) -> None: ''' magic python method that makes the class behave like a dictionary. use to set elements. :param name: :param value: :return: ''' pass
22
19
12
1
4
6
1
1.54
1
6
1
2
18
0
18
42
259
46
84
53
56
129
71
31
49
2
2
1
22
1,512
72squared/redpipe
72squared_redpipe/redpipe/keyspaces.py
redpipe.keyspaces.SortedSet
class SortedSet(Keyspace): """ Manipulate a SortedSet key in redis. """ def zadd(self, name: str, members: Union[str, typing.List[str]], score: float = 1.0, nx: bool = False, xx: bool = False, ch: bool = False, incr: bool = False) -> Future: """ Add members in the set and assign them the score. :param name: str the name of the redis key :param members: a list of item or a single item :param score: the score the assign to the item(s) :param nx: :param xx: :param ch: :param incr: :return: Future() """ _args: typing.List[Union[bytes, str]] if nx: _args = ['NX'] elif xx: _args = ['XX'] else: _args = [] if ch: _args.append('CH') if incr: _args.append('INCR') if isinstance(members, dict): for member, score in members.items(): _args += [str(score), self.valueparse.encode(member)] elif isinstance(members, str): _args += [str(score), self.valueparse.encode(members)] if nx and xx: raise InvalidOperation('cannot specify nx and xx at the same time') with self.pipe as pipe: return pipe.execute_command('ZADD', self.redis_key(name), *_args) def zrem(self, name: str, *values: str) -> Future: """ Remove the values from the SortedSet :param name: str the name of the redis key :param values: :return: True if **at least one** value is successfully removed, False otherwise """ with self.pipe as pipe: v_encode = self.valueparse.encode return pipe.zrem( self.redis_key(name), *[v_encode(v) for v in self._parse_values(values)]) def zincrby(self, name: str, value: Any, amount: float = 1.0) -> Future: """ Increment the score of the item by `value` :param name: str the name of the redis key :param value: :param amount: :return: """ with self.pipe as pipe: return pipe.zincrby(self.redis_key(name), value=self.valueparse.encode(value), amount=amount) def zrevrank(self, name: str, value: str): """ Returns the ranking in reverse order for the member :param name: str the name of the redis key :param value: str """ with self.pipe as pipe: return pipe.zrevrank(self.redis_key(name), self.valueparse.encode(value)) def zrange(self, name: str, start: int, end: int, desc: bool = False, withscores: bool = False, score_cast_func: Callable = float ) -> Future[typing.List[Any]]: """ Returns all the elements including between ``start`` (non included) and ``stop`` (included). :param name: str the name of the redis key :param start: :param end: :param desc: :param withscores: :param score_cast_func: :return: """ with self.pipe as pipe: f = Future[typing.List[Any]]() res = pipe.zrange( self.redis_key(name), start, end, desc=desc, withscores=withscores, score_cast_func=score_cast_func) def cb(): if withscores: f.set([(self.valueparse.decode(v), s) for v, s in res.result]) else: f.set([self.valueparse.decode(v) for v in res.result]) pipe.on_execute(cb) return f def zrevrange(self, name: str, start: int, end: int, withscores: bool = False, score_cast_func: Callable = float ) -> Future[typing.List[Any]]: """ Returns the range of items included between ``start`` and ``stop`` in reverse order (from high to low) :param name: str the name of the redis key :param start: :param end: :param withscores: :param score_cast_func: :return: """ with self.pipe as pipe: f = Future[typing.List[Any]]() res = pipe.zrevrange(self.redis_key(name), start, end, withscores=withscores, score_cast_func=score_cast_func) def cb(): if withscores: f.set([(self.valueparse.decode(v), s) for v, s in res.result]) else: f.set([self.valueparse.decode(v) for v in res.result]) pipe.on_execute(cb) return f # noinspection PyShadowingBuiltins def zrangebyscore(self, name: str, min: float, max: float, start: Optional[int] = None, num: Optional[int] = None, withscores: bool = False, score_cast_func: Callable = float ) -> Future[typing.List[Any]]: """ Returns the range of elements included between the scores (min and max) :param name: str the name of the redis key :param min: :param max: :param start: :param num: :param withscores: :param score_cast_func: :return: Future() """ with self.pipe as pipe: f = Future[typing.List[Any]]() res = pipe.zrangebyscore(self.redis_key(name), min, max, start=start, num=num, withscores=withscores, score_cast_func=score_cast_func) def cb(): if withscores: f.set([(self.valueparse.decode(v), s) for v, s in res.result]) else: f.set([self.valueparse.decode(v) for v in res.result]) pipe.on_execute(cb) return f # noinspection PyShadowingBuiltins def zrevrangebyscore(self, name: str, max: float, min: float, start: Optional[int] = None, num: Optional[int] = None, withscores: bool = False, score_cast_func: Callable = float ) -> Future[typing.List[Any]]: """ Returns the range of elements between the scores (min and max). If ``start`` and ``num`` are specified, then return a slice of the range. ``withscores`` indicates to return the scores along with the values. The return type is a list of (value, score) pairs `score_cast_func`` a callable used to cast the score return value :param name: str the name of the redis key :param max: int :param min: int :param start: int :param num: int :param withscores: bool :param score_cast_func: :return: Future() """ with self.pipe as pipe: f = Future[typing.List[Any]]() res = pipe.zrevrangebyscore(self.redis_key(name), max, min, start=start, num=num, withscores=withscores, score_cast_func=score_cast_func) def cb(): if withscores: f.set([(self.valueparse.decode(v), s) for v, s in res.result]) else: f.set([self.valueparse.decode(v) for v in res.result]) pipe.on_execute(cb) return f def zcard(self, name: str) -> Future[int]: """ Returns the cardinality of the SortedSet. :param name: str the name of the redis key :return: Future() """ with self.pipe as pipe: return pipe.zcard(self.redis_key(name)) # noinspection PyShadowingBuiltins def zcount(self, name: str, min: float, max: float) -> Future[int]: """ Returns the number of elements in the sorted set at key ``name`` with a score between ``min`` and ``max``. :param name: str :param min: float :param max: float :return: Future() """ with self.pipe as pipe: return pipe.zcount(self.redis_key(name), min, max) def zscore(self, name: str, value: Any) -> Future[float]: """ Return the score of an element :param name: str the name of the redis key :param value: the element in the sorted set key :return: Future() """ with self.pipe as pipe: return pipe.zscore(self.redis_key(name), self.valueparse.encode(value)) # noinspection PyShadowingBuiltins def zremrangebyrank(self, name: str, min: float, max: float ) -> Future[int]: """ Remove a range of element between the rank ``start`` and ``stop`` both included. :param name: str the name of the redis key :param min: :param max: :return: Future() """ with self.pipe as pipe: return pipe.zremrangebyrank(self.redis_key(name), min, max) # noinspection PyShadowingBuiltins def zremrangebyscore(self, name: str, min: int, max: int ) -> Future[typing.List[Any]]: """ Remove a range of element by between score ``min_value`` and ``max_value`` both included. :param name: str the name of the redis key :param min: :param max: :return: Future() """ with self.pipe as pipe: return pipe.zremrangebyscore(self.redis_key(name), min, max) def zrank(self, name: str, value: str) -> Future[int]: """ Returns the rank of the element. :param name: str the name of the redis key :param value: the element in the sorted set """ with self.pipe as pipe: return pipe.zrank(self.redis_key(name), self.valueparse.encode(value)) # noinspection PyShadowingBuiltins def zlexcount(self, name: str, min: float, max: float) -> Future[int]: """ Return the number of items in the sorted set between the lexicographical range ``min`` and ``max``. :param name: str the name of the redis key :param min: int or '-inf' :param max: int or '+inf' :return: Future() """ with self.pipe as pipe: return pipe.zlexcount(self.redis_key(name), min, max) # noinspection PyShadowingBuiltins def zrangebylex(self, name: str, min: float, max: float, start: Optional[int] = None, num: Optional[int] = None ) -> Future[typing.List[Any]]: """ Return the lexicographical range of values from sorted set ``name`` between ``min`` and ``max``. If ``start`` and ``num`` are specified, then return a slice of the range. :param name: str the name of the redis key :param min: int or '-inf' :param max: int or '+inf' :param start: int :param num: int :return: Future() """ with self.pipe as pipe: f = Future[typing.List[Any]]() res = pipe.zrangebylex(self.redis_key(name), min, max, start=start, num=num) def cb(): f.set([self.valueparse.decode(v) for v in res]) pipe.on_execute(cb) return f # noinspection PyShadowingBuiltins def zrevrangebylex(self, name: str, max: float, min: float, start: Optional[int] = None, num: Optional[int] = None ) -> Future[typing.List[Any]]: """ Return the reversed lexicographical range of values from the sorted set between ``max`` and ``min``. If ``start`` and ``num`` are specified, then return a slice of the range. :param name: str the name of the redis key :param max: int or '+inf' :param min: int or '-inf' :param start: int :param num: int :return: Future() """ with self.pipe as pipe: f = Future[typing.List[Any]]() res = pipe.zrevrangebylex(self.redis_key(name), max, min, start=start, num=num) def cb(): f.set([self.valueparse.decode(v) for v in res]) pipe.on_execute(cb) return f # noinspection PyShadowingBuiltins def zremrangebylex(self, name: str, min: float, max: float) -> Future[int]: """ Remove all elements in the sorted set between the lexicographical range specified by ``min`` and ``max``. Returns the number of elements removed. :param name: str the name of the redis key :param min: int or -inf :param max: into or +inf :return: Future() """ with self.pipe as pipe: return pipe.zremrangebylex(self.redis_key(name), min, max) def zunionstore(self, dest: str, keys: typing.List[str], aggregate: Optional[str] = None) -> Future[int]: """ Union multiple sorted sets specified by ``keys`` into a new sorted set, ``dest``. Scores in the destination will be aggregated based on the ``aggregate``, MIN, MAX, or SUM if none is provided. """ with self.pipe as pipe: return pipe.zunionstore(self.redis_key(dest), [self.redis_key(k) for k in keys], aggregate=aggregate) def zscan(self, name: str, cursor: int = 0, match: Optional[str] = None, count: Optional[int] = None, score_cast_func: Callable = float ) -> Future[Tuple[int, typing.List[Tuple[str, Any]]]]: """ Incrementally return lists of elements in a sorted set. Also return a cursor indicating the scan position. ``match`` allows for filtering the members by pattern ``count`` allows for hint the minimum number of returns ``score_cast_func`` a callable used to cast the score return value """ with self.pipe as pipe: f = Future[Tuple[int, typing.List[Tuple[str, Any]]]]() res = pipe.zscan(self.redis_key(name), cursor=cursor, match=match, count=count, score_cast_func=score_cast_func) def cb(): f.set((res[0], [(self.valueparse.decode(k), v) for k, v in res[1]])) pipe.on_execute(cb) return f def zscan_iter(self, name: str, match: Optional[str] = None, count: Optional[int] = None, score_cast_func: Callable = float ) -> Iterable[Tuple[str, Any]]: """ Make an iterator using the ZSCAN command so that the client doesn't need to remember the cursor position. ``match`` allows for filtering the keys by pattern ``count`` allows for hint the minimum number of returns ``score_cast_func`` a callable used to cast the score return value """ if self._pipe is not None: raise InvalidOperation('cannot pipeline scan operations') cursor = '0' while cursor != 0: cursor, data = self.zscan(name, cursor=int(cursor), match=match, count=count, score_cast_func=score_cast_func) for item in data: yield item
class SortedSet(Keyspace): ''' Manipulate a SortedSet key in redis. ''' def zadd(self, name: str, members: Union[str, typing.List[str]], score: float = 1.0, nx: bool = False, xx: bool = False, ch: bool = False, incr: bool = False) -> Future: ''' Add members in the set and assign them the score. :param name: str the name of the redis key :param members: a list of item or a single item :param score: the score the assign to the item(s) :param nx: :param xx: :param ch: :param incr: :return: Future() ''' pass def zrem(self, name: str, *values: str) -> Future: ''' Remove the values from the SortedSet :param name: str the name of the redis key :param values: :return: True if **at least one** value is successfully removed, False otherwise ''' pass def zincrby(self, name: str, value: Any, amount: float = 1.0) -> Future: ''' Increment the score of the item by `value` :param name: str the name of the redis key :param value: :param amount: :return: ''' pass def zrevrank(self, name: str, value: str): ''' Returns the ranking in reverse order for the member :param name: str the name of the redis key :param value: str ''' pass def zrange(self, name: str, start: int, end: int, desc: bool = False, withscores: bool = False, score_cast_func: Callable = float ) -> Future[typing.List[Any]]: ''' Returns all the elements including between ``start`` (non included) and ``stop`` (included). :param name: str the name of the redis key :param start: :param end: :param desc: :param withscores: :param score_cast_func: :return: ''' pass def cb(): pass def zrevrange(self, name: str, start: int, end: int, withscores: bool = False, score_cast_func: Callable = float ) -> Future[typing.List[Any]]: ''' Returns the range of items included between ``start`` and ``stop`` in reverse order (from high to low) :param name: str the name of the redis key :param start: :param end: :param withscores: :param score_cast_func: :return: ''' pass def cb(): pass def zrangebyscore(self, name: str, min: float, max: float, start: Optional[int] = None, num: Optional[int] = None, withscores: bool = False, score_cast_func: Callable = float ) -> Future[typing.List[Any]]: ''' Returns the range of elements included between the scores (min and max) :param name: str the name of the redis key :param min: :param max: :param start: :param num: :param withscores: :param score_cast_func: :return: Future() ''' pass def cb(): pass def zrevrangebyscore(self, name: str, max: float, min: float, start: Optional[int] = None, num: Optional[int] = None, withscores: bool = False, score_cast_func: Callable = float ) -> Future[typing.List[Any]]: ''' Returns the range of elements between the scores (min and max). If ``start`` and ``num`` are specified, then return a slice of the range. ``withscores`` indicates to return the scores along with the values. The return type is a list of (value, score) pairs `score_cast_func`` a callable used to cast the score return value :param name: str the name of the redis key :param max: int :param min: int :param start: int :param num: int :param withscores: bool :param score_cast_func: :return: Future() ''' pass def cb(): pass def zcard(self, name: str) -> Future[int]: ''' Returns the cardinality of the SortedSet. :param name: str the name of the redis key :return: Future() ''' pass def zcount(self, name: str, min: float, max: float) -> Future[int]: ''' Returns the number of elements in the sorted set at key ``name`` with a score between ``min`` and ``max``. :param name: str :param min: float :param max: float :return: Future() ''' pass def zscore(self, name: str, value: Any) -> Future[float]: ''' Return the score of an element :param name: str the name of the redis key :param value: the element in the sorted set key :return: Future() ''' pass def zremrangebyrank(self, name: str, min: float, max: float ) -> Future[int]: ''' Remove a range of element between the rank ``start`` and ``stop`` both included. :param name: str the name of the redis key :param min: :param max: :return: Future() ''' pass def zremrangebyscore(self, name: str, min: int, max: int ) -> Future[typing.List[Any]]: ''' Remove a range of element by between score ``min_value`` and ``max_value`` both included. :param name: str the name of the redis key :param min: :param max: :return: Future() ''' pass def zrank(self, name: str, value: str) -> Future[int]: ''' Returns the rank of the element. :param name: str the name of the redis key :param value: the element in the sorted set ''' pass def zlexcount(self, name: str, min: float, max: float) -> Future[int]: ''' Return the number of items in the sorted set between the lexicographical range ``min`` and ``max``. :param name: str the name of the redis key :param min: int or '-inf' :param max: int or '+inf' :return: Future() ''' pass def zrangebylex(self, name: str, min: float, max: float, start: Optional[int] = None, num: Optional[int] = None ) -> Future[typing.List[Any]]: ''' Return the lexicographical range of values from sorted set ``name`` between ``min`` and ``max``. If ``start`` and ``num`` are specified, then return a slice of the range. :param name: str the name of the redis key :param min: int or '-inf' :param max: int or '+inf' :param start: int :param num: int :return: Future() ''' pass def cb(): pass def zrevrangebylex(self, name: str, max: float, min: float, start: Optional[int] = None, num: Optional[int] = None ) -> Future[typing.List[Any]]: ''' Return the reversed lexicographical range of values from the sorted set between ``max`` and ``min``. If ``start`` and ``num`` are specified, then return a slice of the range. :param name: str the name of the redis key :param max: int or '+inf' :param min: int or '-inf' :param start: int :param num: int :return: Future() ''' pass def cb(): pass def zremrangebylex(self, name: str, min: float, max: float) -> Future[int]: ''' Remove all elements in the sorted set between the lexicographical range specified by ``min`` and ``max``. Returns the number of elements removed. :param name: str the name of the redis key :param min: int or -inf :param max: into or +inf :return: Future() ''' pass def zunionstore(self, dest: str, keys: typing.List[str], aggregate: Optional[str] = None) -> Future[int]: ''' Union multiple sorted sets specified by ``keys`` into a new sorted set, ``dest``. Scores in the destination will be aggregated based on the ``aggregate``, MIN, MAX, or SUM if none is provided. ''' pass def zscan(self, name: str, cursor: int = 0, match: Optional[str] = None, count: Optional[int] = None, score_cast_func: Callable = float ) -> Future[Tuple[int, typing.List[Tuple[str, Any]]]]: ''' Incrementally return lists of elements in a sorted set. Also return a cursor indicating the scan position. ``match`` allows for filtering the members by pattern ``count`` allows for hint the minimum number of returns ``score_cast_func`` a callable used to cast the score return value ''' pass def cb(): pass def zscan_iter(self, name: str, match: Optional[str] = None, count: Optional[int] = None, score_cast_func: Callable = float ) -> Iterable[Tuple[str, Any]]: ''' Make an iterator using the ZSCAN command so that the client doesn't need to remember the cursor position. ``match`` allows for filtering the keys by pattern ``count`` allows for hint the minimum number of returns ``score_cast_func`` a callable used to cast the score return value ''' pass
29
22
18
2
9
6
2
0.82
1
9
2
2
21
0
21
45
493
68
234
137
136
191
128
48
99
9
2
2
43
1,513
72squared/redpipe
72squared_redpipe/redpipe/keyspaces.py
redpipe.keyspaces.Set
class Set(Keyspace): """ Manipulate a Set key in redis. """ def sdiff(self, keys: Union[str, typing.List[str]], *args: str) -> Future[typing.List[Any]]: """ Return the difference of sets specified by ``keys`` :param keys: list :param args: tuple :return: Future() """ rkeys = [self.redis_key(k) for k in self._parse_values(keys, args)] with self.pipe as pipe: res = pipe.sdiff(*rkeys) f = Future[Any]() def cb(): f.set({self.valueparse.decode(v) for v in res.result}) pipe.on_execute(cb) return f def sdiffstore(self, dest: str, *keys: Union[str, typing.List[str]]) -> Future: """ Store the difference of sets specified by ``keys`` into a new set named ``dest``. Returns the number of keys in the new set. """ rkeys = (self.redis_key(k) for k in self._parse_values(keys)) with self.pipe as pipe: return pipe.sdiffstore(self.redis_key(dest), *rkeys) def sinter(self, keys, *args) -> Future[typing.List[str]]: """ Return the intersection of sets specified by ``keys`` :param keys: list or str :param args: tuple :return: Future """ keys = [self.redis_key(k) for k in self._parse_values(keys, args)] with self.pipe as pipe: res = pipe.sinter(*keys) f = Future[typing.List[str]]() def cb(): f.set({self.valueparse.decode(v) for v in res.result}) pipe.on_execute(cb) return f def sinterstore(self, dest: str, keys: Union[str, typing.List[str]], *args: str) -> Future: """ Store the intersection of sets specified by ``keys`` into a new set named ``dest``. Returns the number of keys in the new set. """ rkeys = [self.redis_key(k) for k in self._parse_values(keys, args)] with self.pipe as pipe: return pipe.sinterstore(self.redis_key(dest), rkeys) def sunion(self, keys: Union[str, typing.List[str]], *args: str) -> Future[typing.List[str]]: """ Return the union of sets specified by ``keys`` :param keys: list or str :param args: tuple :return: Future() """ rkeys = [self.redis_key(k) for k in self._parse_values(keys, args)] with self.pipe as pipe: res = pipe.sunion(*rkeys) f = Future[typing.List[str]]() def cb(): f.set({self.valueparse.decode(v) for v in res.result}) pipe.on_execute(cb) return f def sunionstore(self, dest: str, keys: Union[str, typing.List[str]], *args: str) -> Future: """ Store the union of sets specified by ``keys`` into a new set named ``dest``. Returns the number of members in the new set. """ rkeys = [self.redis_key(k) for k in self._parse_values(keys, args)] with self.pipe as pipe: return pipe.sunionstore(self.redis_key(dest), *rkeys) def sadd(self, name: str, values: Union[str, typing.List[str]], *args: str) -> Future: """ Add the specified members to the Set. :param name: str the name of the redis key :param values: a list of values or a simple value. :return: Future() """ with self.pipe as pipe: return pipe.sadd(self.redis_key(name), *[self.valueparse.encode(v) for v in self._parse_values(values, args)]) def srem(self, name: str, *values: Union[str, typing.List[str]]) -> Future: """ Remove the values from the Set if they are present. :param name: str the name of the redis key :param values: a list of values or a simple value. :return: Future() """ with self.pipe as pipe: v_encode = self.valueparse.encode return pipe.srem( self.redis_key(name), *[v_encode(v) for v in self._parse_values(values)]) def spop(self, name: str) -> Future[typing.List[Any]]: """ Remove and return (pop) a random element from the Set. :param name: str the name of the redis key :return: Future() """ with self.pipe as pipe: f = Future[typing.List[Any]]() res = pipe.spop(self.redis_key(name)) def cb(): f.set(self.valueparse.decode(res.result)) pipe.on_execute(cb) return f def smembers(self, name: str) -> Future[typing.List[Any]]: """ get the set of all members for key :param name: str the name of the redis key :return: """ with self.pipe as pipe: f = Future[typing.List[Any]]() res = pipe.smembers(self.redis_key(name)) def cb(): f.set({self.valueparse.decode(v) for v in res.result}) pipe.on_execute(cb) return f def scard(self, name: str) -> Future: """ How many items in the set? :param name: str the name of the redis key :return: Future() """ with self.pipe as pipe: return pipe.scard(self.redis_key(name)) def sismember(self, name: str, value: str) -> Future: """ Is the provided value is in the ``Set``? :param name: str the name of the redis key :param value: str :return: Future() """ with self.pipe as pipe: return pipe.sismember(self.redis_key(name), self.valueparse.encode(value)) def srandmember(self, name: str, number: Optional[int] = None ) -> Future[Any]: """ Return a random member of the set. :param name: str the name of the redis key :param number: optional int :return: Future() """ with self.pipe as pipe: f = Future[Any]() res = pipe.srandmember(self.redis_key(name), number=number) def cb(): if number is None: f.set(self.valueparse.decode(res.result)) else: f.set([self.valueparse.decode(v) for v in res.result]) pipe.on_execute(cb) return f def sscan(self, name: str, cursor: int = 0, match: Optional[str] = None, count: Optional[int] = None ) -> Future[Tuple[int, typing.List[Any]]]: """ Incrementally return lists of elements in a set. Also return a cursor indicating the scan position. ``match`` allows for filtering the keys by pattern ``count`` allows for hint the minimum number of returns :param name: str the name of the redis key :param cursor: int :param match: str :param count: int """ with self.pipe as pipe: f = Future[Tuple[int, typing.List[Any]]]() res = pipe.sscan(self.redis_key(name), cursor=cursor, match=match, count=count) def cb(): f.set((res[0], [self.valueparse.decode(v) for v in res[1]])) pipe.on_execute(cb) return f def sscan_iter(self, name: str, match: Optional[str] = None, count: Optional[int] = None) -> Iterable: """ Make an iterator using the SSCAN command so that the client doesn't need to remember the cursor position. ``match`` allows for filtering the keys by pattern ``count`` allows for hint the minimum number of returns :param name: str the name of the redis key :param match: str :param count: int """ if self._pipe is not None: raise InvalidOperation('cannot pipeline scan operations') cursor = '0' while cursor != 0: cursor, data = self.sscan(name, cursor=int(cursor), match=match, count=count) for item in data: yield item
class Set(Keyspace): ''' Manipulate a Set key in redis. ''' def sdiff(self, keys: Union[str, typing.List[str]], *args: str) -> Future[typing.List[Any]]: ''' Return the difference of sets specified by ``keys`` :param keys: list :param args: tuple :return: Future() ''' pass def cb(): pass def sdiffstore(self, dest: str, *keys: Union[str, typing.List[str]]) -> Future: ''' Store the difference of sets specified by ``keys`` into a new set named ``dest``. Returns the number of keys in the new set. ''' pass def sinter(self, keys, *args) -> Future[typing.List[str]]: ''' Return the intersection of sets specified by ``keys`` :param keys: list or str :param args: tuple :return: Future ''' pass def cb(): pass def sinterstore(self, dest: str, keys: Union[str, typing.List[str]], *args: str) -> Future: ''' Store the intersection of sets specified by ``keys`` into a new set named ``dest``. Returns the number of keys in the new set. ''' pass def sunion(self, keys: Union[str, typing.List[str]], *args: str) -> Future[typing.List[str]]: ''' Return the union of sets specified by ``keys`` :param keys: list or str :param args: tuple :return: Future() ''' pass def cb(): pass def sunionstore(self, dest: str, keys: Union[str, typing.List[str]], *args: str) -> Future: ''' Store the union of sets specified by ``keys`` into a new set named ``dest``. Returns the number of members in the new set. ''' pass def sadd(self, name: str, values: Union[str, typing.List[str]], *args: str) -> Future: ''' Add the specified members to the Set. :param name: str the name of the redis key :param values: a list of values or a simple value. :return: Future() ''' pass def srem(self, name: str, *values: Union[str, typing.List[str]]) -> Future: ''' Remove the values from the Set if they are present. :param name: str the name of the redis key :param values: a list of values or a simple value. :return: Future() ''' pass def spop(self, name: str) -> Future[typing.List[Any]]: ''' Remove and return (pop) a random element from the Set. :param name: str the name of the redis key :return: Future() ''' pass def cb(): pass def smembers(self, name: str) -> Future[typing.List[Any]]: ''' get the set of all members for key :param name: str the name of the redis key :return: ''' pass def cb(): pass def scard(self, name: str) -> Future: ''' How many items in the set? :param name: str the name of the redis key :return: Future() ''' pass def sismember(self, name: str, value: str) -> Future: ''' Is the provided value is in the ``Set``? :param name: str the name of the redis key :param value: str :return: Future() ''' pass def srandmember(self, name: str, number: Optional[int] = None ) -> Future[Any]: ''' Return a random member of the set. :param name: str the name of the redis key :param number: optional int :return: Future() ''' pass def cb(): pass def sscan(self, name: str, cursor: int = 0, match: Optional[str] = None, count: Optional[int] = None ) -> Future[Tuple[int, typing.List[Any]]]: ''' Incrementally return lists of elements in a set. Also return a cursor indicating the scan position. ``match`` allows for filtering the keys by pattern ``count`` allows for hint the minimum number of returns :param name: str the name of the redis key :param cursor: int :param match: str :param count: int ''' pass def cb(): pass def sscan_iter(self, name: str, match: Optional[str] = None, count: Optional[int] = None) -> Iterable: ''' Make an iterator using the SSCAN command so that the client doesn't need to remember the cursor position. ``match`` allows for filtering the keys by pattern ``count`` allows for hint the minimum number of returns :param name: str the name of the redis key :param match: str :param count: int ''' pass
23
16
12
2
7
4
1
0.7
1
5
2
2
15
0
15
39
270
49
130
87
80
91
95
46
72
4
2
2
26
1,514
72squared/redpipe
72squared_redpipe/redpipe/keyspaces.py
redpipe.keyspaces.List
class List(Keyspace): """ Manipulate a List key in redis """ def blpop(self, keys: Union[str, typing.List[str]], timeout: int = 0) -> Future[Optional[Tuple[str, Any]]]: """ LPOP a value off of the first non-empty list named in the ``keys`` list. If none of the lists in ``keys`` has a value to LPOP, then block for ``timeout`` seconds, or until a value gets pushed on to one of the lists. If timeout is 0, then block indefinitely. """ kvpairs = {self.redis_key(k): k for k in self._parse_values(keys)} with self.pipe as pipe: f = Future[Optional[Tuple[str, Any]]]() res = pipe.blpop(kvpairs.keys(), timeout=timeout) def cb(): if res.result: k = kvpairs[res.result[0]] v = self.valueparse.decode(res.result[1]) f.set((k, v)) else: f.set(res.result) pipe.on_execute(cb) return f def brpop(self, keys: Union[str, typing.List[str]], timeout: int = 0) -> Future[Optional[Tuple[str, Any]]]: """ RPOP a value off of the first non-empty list named in the ``keys`` list. If none of the lists in ``keys`` has a value to LPOP, then block for ``timeout`` seconds, or until a value gets pushed on to one of the lists. If timeout is 0, then block indefinitely. """ kvpairs = {self.redis_key(k): k for k in self._parse_values(keys)} with self.pipe as pipe: f = Future[Optional[Tuple[str, Any]]]() res = pipe.brpop(kvpairs.keys(), timeout=timeout) def cb(): if res.result: k = kvpairs[res.result[0]] v = self.valueparse.decode(res.result[1]) f.set((k, v)) else: f.set(res.result) pipe.on_execute(cb) return f def brpoplpush(self, src: str, dst: str, timeout: int = 0 ) -> Future[Optional[Tuple[str, Any]]]: """ Pop a value off the tail of ``src``, push it on the head of ``dst`` and then return it. This command blocks until a value is in ``src`` or until ``timeout`` seconds elapse, whichever is first. A ``timeout`` value of 0 blocks forever. """ with self.pipe as pipe: res = pipe.brpoplpush(self.redis_key(src), self.redis_key(dst), timeout) f = Future[Optional[Tuple[str, Any]]]() def cb(): f.set(self.valueparse.decode(res.result)) pipe.on_execute(cb) return f def llen(self, name: str) -> Future[int]: """ Returns the length of the list. :param name: str the name of the redis key :return: Future() """ with self.pipe as pipe: return pipe.llen(self.redis_key(name)) def lrange(self, name: str, start: int, stop: int ) -> Future[typing.List[Any]]: """ Returns a range of items. :param name: str the name of the redis key :param start: integer representing the start index of the range :param stop: integer representing the size of the list. :return: Future() """ with self.pipe as pipe: f = Future[typing.List[Any]]() res = pipe.lrange(self.redis_key(name), start, stop) def cb(): f.set([self.valueparse.decode(v) for v in res.result]) pipe.on_execute(cb) return f def lpush(self, name: str, *values: str) -> Future[int]: """ Push the value into the list from the *left* side :param name: str the name of the redis key :param values: a list of values or single value to push :return: Future() """ with self.pipe as pipe: v_encode = self.valueparse.encode return pipe.lpush( self.redis_key(name), *[v_encode(v) for v in self._parse_values(values)]) def rpush(self, name: str, *values: str) -> Future: """ Push the value into the list from the *right* side :param name: str the name of the redis key :param values: a list of values or single value to push :return: Future() """ with self.pipe as pipe: v_encode = self.valueparse.encode return pipe.rpush( self.redis_key(name), *[v_encode(v) for v in self._parse_values(values)]) def lpop(self, name: str) -> Future[Any]: """ Pop the first object from the left. :param name: str the name of the redis key :return: Future() """ with self.pipe as pipe: f = Future[Any]() res = pipe.lpop(self.redis_key(name)) def cb(): f.set(self.valueparse.decode(res.result)) pipe.on_execute(cb) return f def rpop(self, name: str) -> Future[Any]: """ Pop the first object from the right. :param name: str the name of the redis key :return: the popped value. """ with self.pipe as pipe: f = Future[Any]() res = pipe.rpop(self.redis_key(name)) def cb(): f.set(self.valueparse.decode(res.result)) pipe.on_execute(cb) return f def rpoplpush(self, src: str, dst: str) -> Future[Any]: """ RPOP a value off of the ``src`` list and atomically LPUSH it on to the ``dst`` list. Returns the value. """ with self.pipe as pipe: f = Future[Any]() res = pipe.rpoplpush(self.redis_key(src), self.redis_key(dst)) def cb(): f.set(self.valueparse.decode(res.result)) pipe.on_execute(cb) return f def lrem(self, name: str, value: str, num: int = 1) -> Future[int]: """ Remove first occurrence of value. Can't use redis-py interface. It's inconstistent between redis.Redis and redis.Redis in terms of the kwargs. Better to use the underlying execute_command instead. :param name: str the name of the redis key :param num: :param value: :return: Future() """ with self.pipe as pipe: return pipe.execute_command('LREM', self.redis_key(name), num, self.valueparse.encode(value)) def ltrim(self, name: str, start: int, end: int) -> Future: """ Trim the list from start to end. :param name: str the name of the redis key :param start: :param end: :return: Future() """ with self.pipe as pipe: return pipe.ltrim(self.redis_key(name), start, end) def lindex(self, name: str, index: int) -> Future[Any]: """ Return the value at the index *idx* :param name: str the name of the redis key :param index: the index to fetch the value. :return: Future() """ with self.pipe as pipe: f = Future[Any]() res = pipe.lindex(self.redis_key(name), index) def cb(): f.set(self.valueparse.decode(res.result)) pipe.on_execute(cb) return f def lset(self, name: str, index: int, value: str) -> Future: """ Set the value in the list at index *idx* :param name: str the name of the redis key :param index: :param value: :return: Future() """ with self.pipe as pipe: return pipe.lset(self.redis_key(name), index, self.valueparse.encode(value))
class List(Keyspace): ''' Manipulate a List key in redis ''' def blpop(self, keys: Union[str, typing.List[str]], timeout: int = 0) -> Future[Optional[Tuple[str, Any]]]: ''' LPOP a value off of the first non-empty list named in the ``keys`` list. If none of the lists in ``keys`` has a value to LPOP, then block for ``timeout`` seconds, or until a value gets pushed on to one of the lists. If timeout is 0, then block indefinitely. ''' pass def cb(): pass def brpop(self, keys: Union[str, typing.List[str]], timeout: int = 0) -> Future[Optional[Tuple[str, Any]]]: ''' RPOP a value off of the first non-empty list named in the ``keys`` list. If none of the lists in ``keys`` has a value to LPOP, then block for ``timeout`` seconds, or until a value gets pushed on to one of the lists. If timeout is 0, then block indefinitely. ''' pass def cb(): pass def brpoplpush(self, src: str, dst: str, timeout: int = 0 ) -> Future[Optional[Tuple[str, Any]]]: ''' Pop a value off the tail of ``src``, push it on the head of ``dst`` and then return it. This command blocks until a value is in ``src`` or until ``timeout`` seconds elapse, whichever is first. A ``timeout`` value of 0 blocks forever. ''' pass def cb(): pass def llen(self, name: str) -> Future[int]: ''' Returns the length of the list. :param name: str the name of the redis key :return: Future() ''' pass def lrange(self, name: str, start: int, stop: int ) -> Future[typing.List[Any]]: ''' Returns a range of items. :param name: str the name of the redis key :param start: integer representing the start index of the range :param stop: integer representing the size of the list. :return: Future() ''' pass def cb(): pass def lpush(self, name: str, *values: str) -> Future[int]: ''' Push the value into the list from the *left* side :param name: str the name of the redis key :param values: a list of values or single value to push :return: Future() ''' pass def rpush(self, name: str, *values: str) -> Future: ''' Push the value into the list from the *right* side :param name: str the name of the redis key :param values: a list of values or single value to push :return: Future() ''' pass def lpop(self, name: str) -> Future[Any]: ''' Pop the first object from the left. :param name: str the name of the redis key :return: Future() ''' pass def cb(): pass def rpop(self, name: str) -> Future[Any]: ''' Pop the first object from the right. :param name: str the name of the redis key :return: the popped value. ''' pass def cb(): pass def rpoplpush(self, src: str, dst: str) -> Future[Any]: ''' RPOP a value off of the ``src`` list and atomically LPUSH it on to the ``dst`` list. Returns the value. ''' pass def cb(): pass def lrem(self, name: str, value: str, num: int = 1) -> Future[int]: ''' Remove first occurrence of value. Can't use redis-py interface. It's inconstistent between redis.Redis and redis.Redis in terms of the kwargs. Better to use the underlying execute_command instead. :param name: str the name of the redis key :param num: :param value: :return: Future() ''' pass def ltrim(self, name: str, start: int, end: int) -> Future: ''' Trim the list from start to end. :param name: str the name of the redis key :param start: :param end: :return: Future() ''' pass def lindex(self, name: str, index: int) -> Future[Any]: ''' Return the value at the index *idx* :param name: str the name of the redis key :param index: the index to fetch the value. :return: Future() ''' pass def cb(): pass def lset(self, name: str, index: int, value: str) -> Future: ''' Set the value in the list at index *idx* :param name: str the name of the redis key :param index: :param value: :return: Future() ''' pass
23
15
12
2
6
4
1
0.81
1
4
1
2
14
0
14
38
259
49
116
73
81
94
95
47
72
2
2
1
24
1,515
72squared/redpipe
72squared_redpipe/redpipe/keyspaces.py
redpipe.keyspaces.Keyspace
class Keyspace(object): """ Base class for all keyspace. This class should not be used directly. """ __slots__ = ['key', '_pipe'] keyspace: Optional[str] = None connection: Optional[str] = None keyparse = TextField valueparse = TextField keyspace_template = "%s{%s}" def __init__(self, pipe: Optional[PipelineInterface] = None): """ Creates a new keyspace. Optionally pass in a pipeline object. If you pass in a pipeline, all commands to this instance will be pipelined. :param pipe: optional Pipeline or NestedPipeline """ self._pipe = pipe @classmethod def redis_key(cls, key: str) -> bytes: """ Get the key we pass to redis. If no namespace is declared, it will use the class name. :param key: str the name of the redis key :return: str """ keyspace = cls.keyspace tpl = cls.keyspace_template key = "%s" % key if keyspace is None else tpl % (keyspace, key) return cls.keyparse.encode(key) @property def pipe(self) -> PipelineInterface: """ Get a fresh pipeline() to be used in a `with` block. :return: Pipeline or NestedPipeline with autoexec set to true. """ return autoexec(self._pipe, name=self.connection) @property def super_pipe(self) -> PipelineInterface: """ Creates a mechanism for us to internally bind two different operations together in a shared pipeline on the class. This will temporarily set self._pipe to be this new pipeline, during this context and then when it leaves the context reset self._pipe to its original value. Example: def get_set(self, key, val) with self.super_pipe as pipe: res = self.get(key) self.set(key, val) return res This will have the effect of using only one network round trip if no pipeline was passed to the constructor. This method is still considered experimental and we are working out the details, so don't use it unless you feel confident you have a legitimate use-case for using this. """ orig_pipe = self._pipe def exit_handler(): self._pipe = orig_pipe self._pipe = autoexec(orig_pipe, name=self.connection, exit_handler=exit_handler) return self._pipe def delete(self, *names: str) -> Future: """ Remove the key from redis :param names: tuple of strings - The keys to remove from redis. :return: Future() """ with self.pipe as pipe: return pipe.delete(*[self.redis_key(n) for n in names]) def expire(self, name: str, time: int) -> Future: """ Allow the key to expire after ``time`` seconds. :param name: str the name of the redis key :param time: time expressed in seconds. :return: Future() """ with self.pipe as pipe: return pipe.expire(self.redis_key(name), time) def exists(self, name) -> Future: """ does the key exist in redis? :param name: str the name of the redis key :return: Future() """ with self.pipe as pipe: return pipe.exists(self.redis_key(name)) def eval(self, script: str, numkeys: int, *keys_and_args) -> Future: """ Run a lua script against the key. Doesn't support multi-key lua operations because we wouldn't be able to know what argument to namespace. Also, redis cluster doesn't really support multi-key operations. :param script: str A lua script targeting the current key. :param numkeys: number of keys passed to the script :param keys_and_args: list of keys and args passed to script :return: Future() """ with self.pipe as pipe: args = (a if i >= numkeys else self.redis_key(a) for i, a in enumerate(keys_and_args)) return pipe.eval(script, numkeys, *args) def dump(self, name: str) -> typing.ByteString: """ get a redis RDB-like serialization of the object. :param name: str the name of the redis key :return: Future() """ with self.pipe as pipe: return pipe.dump(self.redis_key(name)) def restorenx(self, name: str, value: bytes, pttl: int = 0) -> Future: """ Restore serialized dump of a key back into redis :param name: str the name of the redis key :param value: redis RDB-like serialization :param pttl: milliseconds till key expires :return: Future() """ return self.eval(lua_restorenx, 1, name, pttl, value) def restore(self, name: str, value: bytes, pttl: int = 0) -> Future[bool]: """ Restore serialized dump of a key back into redis :param name: the name of the key :param value: the binary representation of the key. :param pttl: milliseconds till key expires :return: """ with self.pipe as pipe: res = pipe.restore(self.redis_key(name), ttl=pttl, value=value) f = Future[bool]() def cb(): f.set(self.valueparse.decode(res.result)) pipe.on_execute(cb) return f def ttl(self, name: str) -> int: """ get the number of seconds until the key's expiration :param name: str the name of the redis key :return: Future() """ with self.pipe as pipe: return pipe.ttl(self.redis_key(name)) def persist(self, name: str) -> Future: """ clear any expiration TTL set on the object :param name: str the name of the redis key :return: Future() """ with self.pipe as pipe: return pipe.persist(self.redis_key(name)) def pexpire(self, name: str, time: Union[int, timedelta]) -> Future: """ Set an expire flag on key ``name`` for ``time`` milliseconds. ``time`` can be represented by an integer or a Python timedelta object. :param name: str :param time: int or timedelta :return Future """ with self.pipe as pipe: return pipe.pexpire(self.redis_key(name), time) def pexpireat(self, name: str, when: Union[int, datetime]) -> Future: """ Set an expire flag on key ``name``. ``when`` can be represented as an integer representing unix time in milliseconds (unix time * 1000) or a Python datetime object. """ with self.pipe as pipe: return pipe.pexpireat(self.redis_key(name), when) def pttl(self, name: str) -> Future: """ Returns the number of milliseconds until the key ``name`` will expire :param name: str the name of the redis key :return: Future int """ with self.pipe as pipe: return pipe.pttl(self.redis_key(name)) def rename(self, src: str, dst: str) -> Future: """ Rename key ``src`` to ``dst`` """ with self.pipe as pipe: return pipe.rename(self.redis_key(src), self.redis_key(dst)) def renamenx(self, src: str, dst: str) -> Future: "Rename key ``src`` to ``dst`` if ``dst`` doesn't already exist" with self.pipe as pipe: return pipe.renamenx(self.redis_key(src), self.redis_key(dst)) def object(self, infotype: str, key: str) -> Future: """ get the key's info stats :param infotype: REFCOUNT | ENCODING | IDLETIME :param key: str the name of the redis key :return: Future() """ with self.pipe as pipe: return pipe.object(infotype, self.redis_key(key)) @classmethod def __str__(cls): """ A string representation of the Collection :return: str """ return "<%s>" % cls.__name__ def scan(self, cursor: int = 0, match: Optional[str] = None, count: Optional[int] = None) -> Future[Iterable[Tuple[str, Any]]]: """ Incrementally return lists of key names. Also return a cursor indicating the scan position. ``match`` allows for filtering the keys by pattern ``count`` allows for hint the minimum number of returns """ f = Future[Iterable[Tuple[str, Any]]]() if self.keyspace is None: with self.pipe as pipe: res = pipe.scan(cursor=cursor, match=match, count=count) def cb(): f.set((res[0], [self.keyparse.decode(v) for v in res[1]])) pipe.on_execute(cb) return f if match is None: match = '*' match = "%s{%s}" % (self.keyspace, match) pattern = re.compile(r'^%s\{(.*)\}$' % self.keyspace) with self.pipe as pipe: res = pipe.scan(cursor=cursor, match=match, count=count) def cb(): keys = [] for k in res[1]: k = self.keyparse.decode(k) m = pattern.match(k) if m: keys.append(m.group(1)) f.set((res[0], keys)) pipe.on_execute(cb) return f def scan_iter(self, match: Optional[str] = None, count: Optional[int] = None) -> Iterable[Tuple[str, Any]]: """ Make an iterator using the SCAN command so that the client doesn't need to remember the cursor position. ``match`` allows for filtering the keys by pattern ``count`` allows for hint the minimum number of returns """ if self._pipe is not None: raise InvalidOperation('cannot pipeline scan operations') cursor = '0' while cursor != 0: cursor, data = self.scan(cursor=int(cursor), match=match, count=count) for item in data: yield item def sort(self, name: str, start: Optional[int] = None, num: Optional[int] = None, by: Optional[str] = None, get=None, desc: bool = False, alpha: bool = False, store: Optional[str] = None, groups: bool = False ) -> Future: """ Sort and return the list, set or sorted set at ``name``. ``start`` and ``num`` allow for paging through the sorted data ``by`` allows using an external key to weight and sort the items. Use an "*" to indicate where in the key the item value is located ``get`` allows for returning items from external keys rather than the sorted data itself. Use an "*" to indicate where int he key the item value is located ``desc`` allows for reversing the sort ``alpha`` allows for sorting lexicographically rather than numerically ``store`` allows for storing the result of the sort into the key ``store`` ``groups`` if set to True and if ``get`` contains at least two elements, sort will return a list of tuples, each containing the values fetched from the arguments to ``get``. """ with self.pipe as pipe: res = pipe.sort( self.redis_key(name), start=start, num=num, by=self.redis_key(by) if by is not None else None, get=self.redis_key(get) if get is not None else None, desc=desc, alpha=alpha, store=self.redis_key(store) if store is not None else None, groups=groups) if store: return res f = Future[Iterable[Any]]() def cb(): decode = self.valueparse.decode f.set([decode(v) for v in res.result]) pipe.on_execute(cb) return f @classmethod def _parse_values(cls, values, extra=None): return _parse_values(values, extra)
class Keyspace(object): ''' Base class for all keyspace. This class should not be used directly. ''' def __init__(self, pipe: Optional[PipelineInterface] = None): ''' Creates a new keyspace. Optionally pass in a pipeline object. If you pass in a pipeline, all commands to this instance will be pipelined. :param pipe: optional Pipeline or NestedPipeline ''' pass @classmethod def redis_key(cls, key: str) -> bytes: ''' Get the key we pass to redis. If no namespace is declared, it will use the class name. :param key: str the name of the redis key :return: str ''' pass @property def pipe(self) -> PipelineInterface: ''' Get a fresh pipeline() to be used in a `with` block. :return: Pipeline or NestedPipeline with autoexec set to true. ''' pass @property def super_pipe(self) -> PipelineInterface: ''' Creates a mechanism for us to internally bind two different operations together in a shared pipeline on the class. This will temporarily set self._pipe to be this new pipeline, during this context and then when it leaves the context reset self._pipe to its original value. Example: def get_set(self, key, val) with self.super_pipe as pipe: res = self.get(key) self.set(key, val) return res This will have the effect of using only one network round trip if no pipeline was passed to the constructor. This method is still considered experimental and we are working out the details, so don't use it unless you feel confident you have a legitimate use-case for using this. ''' pass def exit_handler(): pass def delete(self, *names: str) -> Future: ''' Remove the key from redis :param names: tuple of strings - The keys to remove from redis. :return: Future() ''' pass def expire(self, name: str, time: int) -> Future: ''' Allow the key to expire after ``time`` seconds. :param name: str the name of the redis key :param time: time expressed in seconds. :return: Future() ''' pass def exists(self, name) -> Future: ''' does the key exist in redis? :param name: str the name of the redis key :return: Future() ''' pass def eval(self, script: str, numkeys: int, *keys_and_args) -> Future: ''' Run a lua script against the key. Doesn't support multi-key lua operations because we wouldn't be able to know what argument to namespace. Also, redis cluster doesn't really support multi-key operations. :param script: str A lua script targeting the current key. :param numkeys: number of keys passed to the script :param keys_and_args: list of keys and args passed to script :return: Future() ''' pass def dump(self, name: str) -> typing.ByteString: ''' get a redis RDB-like serialization of the object. :param name: str the name of the redis key :return: Future() ''' pass def restorenx(self, name: str, value: bytes, pttl: int = 0) -> Future: ''' Restore serialized dump of a key back into redis :param name: str the name of the redis key :param value: redis RDB-like serialization :param pttl: milliseconds till key expires :return: Future() ''' pass def restorenx(self, name: str, value: bytes, pttl: int = 0) -> Future: ''' Restore serialized dump of a key back into redis :param name: the name of the key :param value: the binary representation of the key. :param pttl: milliseconds till key expires :return: ''' pass def cb(): pass def ttl(self, name: str) -> int: ''' get the number of seconds until the key's expiration :param name: str the name of the redis key :return: Future() ''' pass def persist(self, name: str) -> Future: ''' clear any expiration TTL set on the object :param name: str the name of the redis key :return: Future() ''' pass def pexpire(self, name: str, time: Union[int, timedelta]) -> Future: ''' Set an expire flag on key ``name`` for ``time`` milliseconds. ``time`` can be represented by an integer or a Python timedelta object. :param name: str :param time: int or timedelta :return Future ''' pass def pexpireat(self, name: str, when: Union[int, datetime]) -> Future: ''' Set an expire flag on key ``name``. ``when`` can be represented as an integer representing unix time in milliseconds (unix time * 1000) or a Python datetime object. ''' pass def pttl(self, name: str) -> Future: ''' Returns the number of milliseconds until the key ``name`` will expire :param name: str the name of the redis key :return: Future int ''' pass def rename(self, src: str, dst: str) -> Future: ''' Rename key ``src`` to ``dst`` ''' pass def renamenx(self, src: str, dst: str) -> Future: '''Rename key ``src`` to ``dst`` if ``dst`` doesn't already exist''' pass def object(self, infotype: str, key: str) -> Future: ''' get the key's info stats :param infotype: REFCOUNT | ENCODING | IDLETIME :param key: str the name of the redis key :return: Future() ''' pass @classmethod def __str__(cls): ''' A string representation of the Collection :return: str ''' pass def scan(self, cursor: int = 0, match: Optional[str] = None, count: Optional[int] = None) -> Future[Iterable[Tuple[str, Any]]]: ''' Incrementally return lists of key names. Also return a cursor indicating the scan position. ``match`` allows for filtering the keys by pattern ``count`` allows for hint the minimum number of returns ''' pass def cb(): pass def cb(): pass def scan_iter(self, match: Optional[str] = None, count: Optional[int] = None) -> Iterable[Tuple[str, Any]]: ''' Make an iterator using the SCAN command so that the client doesn't need to remember the cursor position. ``match`` allows for filtering the keys by pattern ``count`` allows for hint the minimum number of returns ''' pass def sort(self, name: str, start: Optional[int] = None, num: Optional[int] = None, by: Optional[str] = None, get=None, desc: bool = False, alpha: bool = False, store: Optional[str] = None, groups: bool = False ) -> Future: ''' Sort and return the list, set or sorted set at ``name``. ``start`` and ``num`` allow for paging through the sorted data ``by`` allows using an external key to weight and sort the items. Use an "*" to indicate where in the key the item value is located ``get`` allows for returning items from external keys rather than the sorted data itself. Use an "*" to indicate where int he key the item value is located ``desc`` allows for reversing the sort ``alpha`` allows for sorting lexicographically rather than numerically ``store`` allows for storing the result of the sort into the key ``store`` ``groups`` if set to True and if ``get`` contains at least two elements, sort will return a list of tuples, each containing the values fetched from the arguments to ``get``. ''' pass def cb(): pass @classmethod def _parse_values(cls, values, extra=None): pass
35
24
12
2
6
5
1
0.97
1
11
3
6
21
1
24
24
384
72
158
96
103
154
120
55
90
5
1
2
42
1,516
72squared/redpipe
72squared_redpipe/redpipe/keyspaces.py
redpipe.keyspaces.HyperLogLog
class HyperLogLog(Keyspace): """ Manipulate a HyperLogLog key in redis. """ def pfadd(self, name: str, *values: str) -> Future[int]: """ Adds the specified elements to the specified HyperLogLog. :param name: str the name of the redis key :param values: list of str """ with self.pipe as pipe: v_encode = self.valueparse.encode return pipe.pfadd( self.redis_key(name), *[v_encode(v) for v in self._parse_values(values)]) def pfcount(self, *sources: str) -> Future[int]: """ Return the approximated cardinality of the set observed by the HyperLogLog at key(s). Using the execute_command because redis-py disabled it unnecessarily for cluster. You can only send one key at a time in that case, or only keys that map to the same keyslot. Use at your own risk. :param sources: [str] the names of the redis keys """ with self.pipe as pipe: return pipe.execute_command('PFCOUNT', *[self.redis_key(s) for s in sources]) def pfmerge(self, dest: str, *sources: str) -> Future[None]: """ Merge N different HyperLogLogs into a single one. :param dest: :param sources: :return: """ with self.pipe as pipe: return pipe.pfmerge(self.redis_key(dest), *[self.redis_key(k) for k in sources])
class HyperLogLog(Keyspace): ''' Manipulate a HyperLogLog key in redis. ''' def pfadd(self, name: str, *values: str) -> Future[int]: ''' Adds the specified elements to the specified HyperLogLog. :param name: str the name of the redis key :param values: list of str ''' pass def pfcount(self, *sources: str) -> Future[int]: ''' Return the approximated cardinality of the set observed by the HyperLogLog at key(s). Using the execute_command because redis-py disabled it unnecessarily for cluster. You can only send one key at a time in that case, or only keys that map to the same keyslot. Use at your own risk. :param sources: [str] the names of the redis keys ''' pass def pfmerge(self, dest: str, *sources: str) -> Future[None]: ''' Merge N different HyperLogLogs into a single one. :param dest: :param sources: :return: ''' pass
4
4
13
1
5
7
1
1.6
1
3
1
2
3
0
3
27
46
7
15
8
11
24
11
5
7
1
2
1
3
1,517
72squared/redpipe
72squared_redpipe/redpipe/keyspaces.py
redpipe.keyspaces.HashedStringMeta
class HashedStringMeta(type): def __new__(mcs, name, bases, d): module = 'redpipe.keyspaces' if name in ['HashedString'] and d.get('__module__', '') == module: return type.__new__(mcs, name, bases, d) class Core(Hash): keyspace = d.get('keyspace', name) connection = d.get('connection', None) fields = d.get('fields', {}) keyparse = d.get('keyparse', TextField) valueparse = d.get('valueparse', TextField) memberparse = d.get('memberparse', TextField) keyspace_template = d.get('keyspace_template', '%s{%s}') d['_core'] = Core return type.__new__(mcs, name, bases, d)
class HashedStringMeta(type): def __new__(mcs, name, bases, d): pass class Core(Hash):
3
0
17
3
14
0
2
0
1
1
1
1
1
0
1
14
19
4
15
11
12
0
15
11
12
2
2
1
2
1,518
72squared/redpipe
72squared_redpipe/redpipe/keyspaces.py
redpipe.keyspaces.Hash
class Hash(Keyspace): """ Manipulate a Hash key in Redis. """ fields: Dict[str, Field] = {} memberparse = TextField @classmethod def _value_encode(cls, member, value): """ Internal method used to encode values into the hash. :param member: str :param value: multi :return: bytes """ try: field_validator = cls.fields[member] except KeyError: return cls.valueparse.encode(value) return field_validator.encode(value) @classmethod def _value_decode(cls, member, value): """ Internal method used to decode values from redis hash :param member: str :param value: bytes :return: multi """ if value is None: return None try: field_validator = cls.fields[member] except KeyError: return cls.valueparse.decode(value) return field_validator.decode(value) def hlen(self, name: str) -> Future[int]: """ Returns the number of elements in the Hash. :param name: str the name of the redis key :return: Future() """ with self.pipe as pipe: return pipe.hlen(self.redis_key(name)) def hstrlen(self, name: str, key: str) -> Future: """ Return the number of bytes stored in the value of ``key`` within hash ``name`` """ with self.pipe as pipe: return pipe.hstrlen(self.redis_key(name), key) def hset(self, name: str, key: str, value: Any) -> Future[int]: """ Set ``member`` in the Hash at ``value``. :param name: str the name of the redis key :param value: :param key: the member of the hash key :return: Future() """ with self.pipe as pipe: return pipe.hset(self.redis_key(name), self.memberparse.encode(key), self._value_encode(key, value)) def hsetnx(self, name: str, key: str, value: Any) -> Future[int]: """ Set ``member`` in the Hash at ``value``. :param name: str the name of the redis key :param value: :param key: :return: Future() """ with self.pipe as pipe: return pipe.hsetnx(self.redis_key(name), self.memberparse.encode(key), self._value_encode(key, value)) def hdel(self, name: str, *keys) -> Future[int]: """ Delete one or more hash field. :param name: str the name of the redis key :param keys: on or more members to remove from the key. :return: Future() """ with self.pipe as pipe: m_encode = self.memberparse.encode return pipe.hdel( self.redis_key(name), *[m_encode(m) for m in self._parse_values(keys)]) def hkeys(self, name: str) -> Future[typing.List[str]]: """ Returns all fields name in the Hash. :param name: str the name of the redis key :return: Future """ with self.pipe as pipe: f = Future[typing.List[str]]() res = pipe.hkeys(self.redis_key(name)) def cb(): m_decode = self.memberparse.decode f.set([m_decode(v) for v in res.result]) pipe.on_execute(cb) return f def hgetall(self, name: str) -> Future[Dict[str, Any]]: """ Returns all the fields and values in the Hash. :param name: str the name of the redis key :return: Future() """ with self.pipe as pipe: f = Future[Dict[str, Any]]() res = pipe.hgetall(self.redis_key(name)) def cb(): data = {} m_decode = self.memberparse.decode v_decode = self._value_decode for k, v in res.result.items(): k = m_decode(k) v = v_decode(k, v) data[k] = v f.set(data) pipe.on_execute(cb) return f def hvals(self, name: str) -> Future[typing.List[Any]]: """ Returns all the values in the Hash Unfortunately we can't type cast these fields. it is a useless call anyway imho. :param name: str the name of the redis key :return: Future() """ with self.pipe as pipe: f = Future[typing.List[Any]]() res = pipe.hvals(self.redis_key(name)) def cb(): f.set([self.valueparse.decode(v) for v in res.result]) pipe.on_execute(cb) return f def hget(self, name: str, key: str) -> Future[Any]: """ Returns the value stored in the field, None if the field doesn't exist. :param name: str the name of the redis key :param key: the member of the hash :return: Future() """ with self.pipe as pipe: f = Future[Any]() res = pipe.hget(self.redis_key(name), self.memberparse.encode(key)) def cb(): f.set(self._value_decode(key, res.result)) pipe.on_execute(cb) return f def hexists(self, name: str, key: str) -> Future[bool]: """ Returns ``True`` if the field exists, ``False`` otherwise. :param name: str the name of the redis key :param key: the member of the hash :return: Future() """ with self.pipe as pipe: return pipe.hexists(self.redis_key(name), self.memberparse.encode(key)) def hincrby(self, name: str, key: str, amount: int = 1) -> Future[int]: """ Increment the value of the field. :param name: str the name of the redis key :param key: str :param amount: int :return: Future() """ with self.pipe as pipe: return pipe.hincrby(self.redis_key(name), self.memberparse.encode(key), amount) def hincrbyfloat(self, name: str, key: str, amount: float = 1.0 ) -> Future[float]: """ Increment the value of the field. :param name: str the name of the redis key :param key: the name of the emement in the hash :param amount: float :return: Future() """ with self.pipe as pipe: return pipe.hincrbyfloat(self.redis_key(name), self.memberparse.encode(key), amount) def hmget(self, name: str, keys: typing.List[str], *args) -> Future[typing.List[Any]]: """ Returns the values stored in the fields. :param name: str the name of the redis key :param keys: :return: Future() """ member_encode = self.memberparse.encode with self.pipe as pipe: f = Future[typing.List[Any]]() keys = [k for k in self._parse_values(keys, args)] res = pipe.hmget(self.redis_key(name), [member_encode(k) for k in keys]) def cb(): f.set([self._value_decode(keys[i], v) for i, v in enumerate(res.result)]) pipe.on_execute(cb) return f def hmset(self, name: str, mapping: Dict[str, Any]) -> Future[None]: """ Sets or updates the fields with their corresponding values. :param name: str the name of the redis key :param mapping: a dict with keys and values :return: Future() """ with self.pipe as pipe: m_encode = self.memberparse.encode return pipe.hmset(self.redis_key(name), {m_encode(k): self._value_encode(k, v) for k, v in mapping.items()}) def hscan(self, name: str, cursor: int = 0, match: Optional[str] = None, count: Optional[int] = None ) -> Future[typing.Tuple[int, Dict[str, Any]]]: """ Incrementally return key/value slices in a hash. Also return a cursor indicating the scan position. ``match`` allows for filtering the keys by pattern ``count`` allows for hint the minimum number of returns """ with self.pipe as pipe: f = Future[typing.Tuple[int, Dict[str, Any]]]() res = pipe.hscan(self.redis_key(name), cursor=cursor, match=match, count=count) def cb(): data = {} m_decode = self.memberparse.decode for k, v in res[1].items(): k = m_decode(k) v = self._value_decode(k, v) data[k] = v f.set((res[0], data)) pipe.on_execute(cb) return f def hscan_iter(self, name: str, match: Optional[str] = None, count: Optional[int] = None ) -> Iterable[Tuple[str, Any]]: """ Make an iterator using the HSCAN command so that the client doesn't need to remember the cursor position. ``match`` allows for filtering the keys by pattern ``count`` allows for hint the minimum number of returns """ if self._pipe is not None: raise InvalidOperation('cannot pipeline scan operations') cursor = '0' while cursor != 0: cursor, data = self.hscan(name, cursor=int(cursor), match=match, count=count) for item in data.items(): yield item
class Hash(Keyspace): ''' Manipulate a Hash key in Redis. ''' @classmethod def _value_encode(cls, member, value): ''' Internal method used to encode values into the hash. :param member: str :param value: multi :return: bytes ''' pass @classmethod def _value_decode(cls, member, value): ''' Internal method used to decode values from redis hash :param member: str :param value: bytes :return: multi ''' pass def hlen(self, name: str) -> Future[int]: ''' Returns the number of elements in the Hash. :param name: str the name of the redis key :return: Future() ''' pass def hstrlen(self, name: str, key: str) -> Future: ''' Return the number of bytes stored in the value of ``key`` within hash ``name`` ''' pass def hset(self, name: str, key: str, value: Any) -> Future[int]: ''' Set ``member`` in the Hash at ``value``. :param name: str the name of the redis key :param value: :param key: the member of the hash key :return: Future() ''' pass def hsetnx(self, name: str, key: str, value: Any) -> Future[int]: ''' Set ``member`` in the Hash at ``value``. :param name: str the name of the redis key :param value: :param key: :return: Future() ''' pass def hdel(self, name: str, *keys) -> Future[int]: ''' Delete one or more hash field. :param name: str the name of the redis key :param keys: on or more members to remove from the key. :return: Future() ''' pass def hkeys(self, name: str) -> Future[typing.List[str]]: ''' Returns all fields name in the Hash. :param name: str the name of the redis key :return: Future ''' pass def cb(): pass def hgetall(self, name: str) -> Future[Dict[str, Any]]: ''' Returns all the fields and values in the Hash. :param name: str the name of the redis key :return: Future() ''' pass def cb(): pass def hvals(self, name: str) -> Future[typing.List[Any]]: ''' Returns all the values in the Hash Unfortunately we can't type cast these fields. it is a useless call anyway imho. :param name: str the name of the redis key :return: Future() ''' pass def cb(): pass def hgetall(self, name: str) -> Future[Dict[str, Any]]: ''' Returns the value stored in the field, None if the field doesn't exist. :param name: str the name of the redis key :param key: the member of the hash :return: Future() ''' pass def cb(): pass def hexists(self, name: str, key: str) -> Future[bool]: ''' Returns ``True`` if the field exists, ``False`` otherwise. :param name: str the name of the redis key :param key: the member of the hash :return: Future() ''' pass def hincrby(self, name: str, key: str, amount: int = 1) -> Future[int]: ''' Increment the value of the field. :param name: str the name of the redis key :param key: str :param amount: int :return: Future() ''' pass def hincrbyfloat(self, name: str, key: str, amount: float = 1.0 ) -> Future[float]: ''' Increment the value of the field. :param name: str the name of the redis key :param key: the name of the emement in the hash :param amount: float :return: Future() ''' pass def hmget(self, name: str, keys: typing.List[str], *args) -> Future[typing.List[Any]]: ''' Returns the values stored in the fields. :param name: str the name of the redis key :param keys: :return: Future() ''' pass def cb(): pass def hmset(self, name: str, mapping: Dict[str, Any]) -> Future[None]: ''' Sets or updates the fields with their corresponding values. :param name: str the name of the redis key :param mapping: a dict with keys and values :return: Future() ''' pass def hscan(self, name: str, cursor: int = 0, match: Optional[str] = None, count: Optional[int] = None ) -> Future[typing.Tuple[int, Dict[str, Any]]]: ''' Incrementally return key/value slices in a hash. Also return a cursor indicating the scan position. ``match`` allows for filtering the keys by pattern ``count`` allows for hint the minimum number of returns ''' pass def cb(): pass def hscan_iter(self, name: str, match: Optional[str] = None, count: Optional[int] = None ) -> Iterable[Tuple[str, Any]]: ''' Make an iterator using the HSCAN command so that the client doesn't need to remember the cursor position. ``match`` allows for filtering the keys by pattern ``count`` allows for hint the minimum number of returns ''' pass
27
19
13
1
7
5
1
0.73
1
9
2
5
16
0
18
42
318
54
153
87
111
111
118
55
93
4
2
2
32
1,519
72squared/redpipe
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/72squared_redpipe/test.py
test.StructExpiresTestCase.T
class T(redpipe.Struct): connection = 't' keyspace = 't' ttl = 30 fields = { 'foo': redpipe.IntegerField() }
class T(redpipe.Struct): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
8
1
7
5
6
0
5
5
4
0
1
0
0
1,520
72squared/redpipe
72squared_redpipe/test.py
test.HashedStringTestCase
class HashedStringTestCase(BaseTestCase): class Data(redpipe.HashedString): keyspace = 'my_index' shard_count = 3 def test(self): with redpipe.pipeline(autoexec=True) as pipe: set_res = self.Data(pipe).set('a', 'foo') get_res = self.Data(pipe).get('a') setnx_res = self.Data(pipe).setnx('a', 'boo') mget_res = self.Data(pipe).mget(['a']) strlen_res = self.Data(pipe).strlen('a') self.Data(pipe)['a'] = 'boo' dict_res = self.Data(pipe)['a'] self.assertEqual(set_res, 1) self.assertEqual(get_res, 'foo') self.assertEqual(setnx_res, 0) self.assertEqual(['foo'], mget_res) self.assertEqual(3, strlen_res) self.assertEqual('boo', dict_res) data = {k: v for k, v in self.Data().scan_iter()} self.assertEqual(data, {'a': 'boo'}) with redpipe.pipeline(autoexec=True) as pipe: remove_res = self.Data(pipe).delete('a') get_res = self.Data(pipe).get('a') self.assertEqual(1, remove_res) self.assertEqual(None, get_res) self.assertEqual(b'my_index{1}', self.Data.core().redis_key(self.Data.shard('a'))) def test_incr(self): with redpipe.pipeline(autoexec=True) as pipe: incr_res = self.Data(pipe).incr('b') incrby_res = self.Data(pipe).incrby('b', '1') incrbyfloat_res = self.Data(pipe).incrbyfloat('b', 0.2) self.assertEqual(1, incr_res) self.assertEqual(2, incrby_res) self.assertEqual(2.2, incrbyfloat_res)
class HashedStringTestCase(BaseTestCase): class Data(redpipe.HashedString): def test(self): pass def test_incr(self): pass
4
0
19
3
16
0
1
0
1
1
1
0
2
0
2
78
43
7
36
19
32
0
35
17
31
1
3
1
2
1,521
72squared/redpipe
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/72squared_redpipe/test.py
test.StrictHashTestCase.Data
class Data(redpipe.Hash): keyspace = 'HASH'
class Data(redpipe.Hash): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
42
2
0
2
2
1
0
2
2
1
0
3
0
0
1,522
72squared/redpipe
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/72squared_redpipe/test.py
test.StructTestCase.test_required_adding_later.Test
class Test(redpipe.Struct): keyspace = 'U' fields = { 'a': redpipe.IntegerField, 'b': redpipe.IntegerField }
class Test(redpipe.Struct): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
6
0
6
3
5
0
3
3
2
0
1
0
0
1,523
72squared/redpipe
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/72squared_redpipe/test.py
test.StructTestCase.test_required_adding_later.Test2
class Test2(redpipe.Struct): required = {'new_required_field'} keyspace = 'U' fields = { 'a': redpipe.IntegerField, 'b': redpipe.IntegerField }
class Test2(redpipe.Struct): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
7
0
7
4
6
0
4
4
3
0
1
0
0
1,524
72squared/redpipe
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/72squared_redpipe/test.py
test.StructTestCase.test_required_fields.Test
class Test(redpipe.Struct): keyspace = 'U' fields = { 'a': redpipe.IntegerField, 'b': redpipe.IntegerField } required = set('b')
class Test(redpipe.Struct): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
7
0
7
4
6
0
4
4
3
0
1
0
0
1,525
72squared/redpipe
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/72squared_redpipe/test.py
test.StructTestCase.test_typed_incr.T
class T(redpipe.Struct): keyspace = 'T' fields = { 'counter': redpipe.IntegerField }
class T(redpipe.Struct): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
5
0
5
3
4
0
3
3
2
0
1
0
0
1,526
72squared/redpipe
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/72squared_redpipe/test.py
test.StructTestCase.test_with_empty_update.Test
class Test(redpipe.Struct): keyspace = 'U' fields = { 'a': redpipe.TextField, } key_name = 'k'
class Test(redpipe.Struct): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
6
0
6
4
5
0
4
4
3
0
1
0
0
1,527
72squared/redpipe
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/72squared_redpipe/test.py
test.RedisClusterTestCase.test_list.Test
class Test(redpipe.List): keyspace = 'T'
class Test(redpipe.List): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
38
2
0
2
2
1
0
2
2
1
0
3
0
0
1,528
72squared/redpipe
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/72squared_redpipe/test.py
test.RedisClusterTestCase.test_string.Test
class Test(redpipe.String): keyspace = 'T'
class Test(redpipe.String): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
42
2
0
2
2
1
0
2
2
1
0
3
0
0
1,529
72squared/redpipe
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/72squared_redpipe/test.py
test.RedisClusterTestCase.test_sorted_sets.Test
class Test(redpipe.SortedSet): keyspace = 'T'
class Test(redpipe.SortedSet): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
45
2
0
2
2
1
0
2
2
1
0
3
0
0
1,530
72squared/redpipe
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/72squared_redpipe/test.py
test.StrictListTestCase.Data
class Data(redpipe.List): keyspace = 'LIST'
class Data(redpipe.List): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
38
2
0
2
2
1
0
2
2
1
0
3
0
0
1,531
72squared/redpipe
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/72squared_redpipe/test.py
test.StrictSetTestCase.Data
class Data(redpipe.Set): keyspace = 'SET'
class Data(redpipe.Set): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
39
2
0
2
2
1
0
2
2
1
0
3
0
0
1,532
72squared/redpipe
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/72squared_redpipe/test.py
test.StrictSortedSetTestCase.Data
class Data(redpipe.SortedSet): keyspace = 'SORTEDSET'
class Data(redpipe.SortedSet): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
45
2
0
2
2
1
0
2
2
1
0
3
0
0
1,533
72squared/redpipe
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/72squared_redpipe/test.py
test.StrictStringTestCase.Data
class Data(redpipe.String): keyspace = 'STRING' def super_get(self, key): f = redpipe.Future() with self.super_pipe as pipe: res = self.get(key) def cb(): f.set(res.result) pipe.on_execute(cb) return f
class Data(redpipe.String): def super_get(self, key): pass def cb(): pass
3
0
7
2
5
0
1
0
1
0
0
0
1
0
1
43
15
5
10
7
7
0
10
6
7
1
3
1
2
1,534
72squared/redpipe
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/72squared_redpipe/test.py
test.StructTestCase.test_nx.Test
class Test(redpipe.Struct): keyspace = 'U' fields = { 'f1': redpipe.TextField, 'f2': redpipe.TextField, } key_name = 'k'
class Test(redpipe.Struct): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
7
0
7
4
6
0
4
4
3
0
1
0
0
1,535
72squared/redpipe
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/72squared_redpipe/test.py
test.StructTestCase.test_fields_custom_default_defined_only.Test
class Test(redpipe.Struct): keyspace = 'U' fields = { 'a': redpipe.TextField, 'b': redpipe.TextField, } default_fields = 'defined' key_name = 'k'
class Test(redpipe.Struct): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
8
0
8
5
7
0
5
5
4
0
1
0
0
1,536
72squared/redpipe
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/72squared_redpipe/test.py
test.StructTestCase.test_fields_custom_default.Test
class Test(redpipe.Struct): keyspace = 'U' fields = { 'a': redpipe.TextField, 'b': redpipe.TextField, } default_fields = ['a'] key_name = 'k'
class Test(redpipe.Struct): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
8
0
8
5
7
0
5
5
4
0
1
0
0
1,537
72squared/redpipe
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/72squared_redpipe/test.py
test.StructTestCase.test_fields.Multi
class Multi(redpipe.Struct): keyspace = 'M' fields = { 'boolean': redpipe.BooleanField, 'integer': redpipe.IntegerField, 'float': redpipe.FloatField, 'text': redpipe.TextField, }
class Multi(redpipe.Struct): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
8
0
8
3
7
0
3
3
2
0
1
0
0
1,538
72squared/redpipe
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/72squared_redpipe/test.py
test.StructTestCase.test_empty_fields_init.Test
class Test(redpipe.Struct): key_name = 't' default_fields = 'all'
class Test(redpipe.Struct): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
3
0
3
3
2
0
3
3
2
0
1
0
0
1,539
72squared/redpipe
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/72squared_redpipe/test.py
test.StructTestCase.test_custom_pk_attr.UserWithPkAttr
class UserWithPkAttr(StructUser): key_name = 'user_id' field_attr_on = True
class UserWithPkAttr(StructUser): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
1
3
0
3
3
2
0
3
3
2
0
2
0
0
1,540
72squared/redpipe
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/72squared_redpipe/test.py
test.StructTestCase.UserWithPk
class UserWithPk(StructUser): key_name = 'user_id'
class UserWithPk(StructUser): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
1
2
0
2
2
1
0
2
2
1
0
2
0
0
1,541
72squared/redpipe
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/72squared_redpipe/test.py
test.RedisClusterTestCase.test_set.Test
class Test(redpipe.Set): keyspace = 'T'
class Test(redpipe.Set): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
39
2
0
2
2
1
0
2
2
1
0
3
0
0
1,542
72squared/redpipe
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/72squared_redpipe/test.py
test.Issue2NamedConnectionsTestCase.T
class T(redpipe.Struct): connection = 't' keyspace = 't' fields = { 'foo': redpipe.IntegerField() }
class T(redpipe.Struct): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
7
1
6
4
5
0
4
4
3
0
1
0
0
1,543
72squared/redpipe
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/72squared_redpipe/test.py
test.Issue2NamedConnectionsTestCase.H
class H(redpipe.Hash): connection = 't' keyspace = 'h'
class H(redpipe.Hash): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
42
3
0
3
3
2
0
3
3
2
0
3
0
0
1,544
72squared/redpipe
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/72squared_redpipe/test.py
test.HyperloglogTestCase.Data
class Data(redpipe.HyperLogLog): keyspace = 'HYPERLOGLOG'
class Data(redpipe.HyperLogLog): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
27
2
0
2
2
1
0
2
2
1
0
3
0
0
1,545
72squared/redpipe
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/72squared_redpipe/test.py
test.StructTestCase.test_incr.T
class T(redpipe.Struct): keyspace = 'T' fields = { }
class T(redpipe.Struct): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
5
1
4
3
3
0
3
3
2
0
1
0
0
1,546
72squared/redpipe
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/72squared_redpipe/test.py
test.RedisClusterTestCase.test_hll_commands.Test
class Test(redpipe.HyperLogLog): keyspace = 'T'
class Test(redpipe.HyperLogLog): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
27
2
0
2
2
1
0
2
2
1
0
3
0
0
1,547
7sDream/zhihu-py3
7sDream_zhihu-py3/test/test_activity.py
test_activity.ActivityTest
class ActivityTest(unittest.TestCase): @classmethod def setUpClass(cls): url = 'http://www.zhihu.com/question/24825703' file_path = os.path.join(TEST_DATA_PATH, 'question.html') with open(file_path, 'rb') as f: html = f.read() soup = BeautifulSoup(html) cls.question = Question(url) cls.question._session = None cls.question.soup = soup act_time = datetime.datetime.fromtimestamp(1439395600) act_type = ActType.FOLLOW_QUESTION cls.activity = Activity(act_type, act_time, question=cls.question) def test_content(self): self.assertIs(self.question, self.activity.content) def test_init_errors(self): act_time = datetime.datetime.fromtimestamp(1439395600) act_type = ActType.FOLLOW_QUESTION with self.assertRaises(ValueError): Activity(100, act_time) with self.assertRaises(ValueError): Activity(act_type, act_time)
class ActivityTest(unittest.TestCase): @classmethod def setUpClass(cls): pass def test_content(self): pass def test_init_errors(self): pass
5
0
8
1
7
0
1
0
1
2
0
0
2
0
3
75
28
5
23
14
18
0
22
12
18
1
2
1
3
1,548
7sDream/zhihu-py3
7sDream_zhihu-py3/test/test_collection.py
test_collection.CollectionTest
class CollectionTest(unittest.TestCase): @classmethod def setUpClass(cls): url = 'http://www.zhihu.com/collection/28698204' file_path = os.path.join(TEST_DATA_PATH, 'collection.html') with open(file_path, 'rb') as f: html = f.read() soup = BeautifulSoup(html) cls.collection = Collection(url) cls.collection._session = None cls.collection.soup = soup cls.expected = {'cid': 3725428, 'name': '可以用来背的答案', 'xsrf': 'cfd489623d34ca03adfdc125368c6426', 'owner_id': 'buhuilengyoumo', 'owner_name': '树叶', 'follower_num': 6328, 'top_ques_id': 26092705, 'top_ques_title': ('一直追求(吸引)不到喜欢的异性,' '感觉累了怎么办?'), 'top_ans_id': 32989919, 'top_ans_author_name': '朱炫', 'top_ans_upvote_num': 16595, 'top_ans_author_id': 'zhu-xuan-86' } def test_cid(self): self.assertEqual(self.expected['cid'], self.collection.cid) def test_name(self): self.assertEqual(self.expected['name'], self.collection.name) def test_xsrf(self): self.assertEqual(self.expected['xsrf'], self.collection.xsrf) def test_owner(self): owner = self.collection.owner self.assertEqual(self.expected['owner_id'], owner.id) self.assertEqual(self.expected['owner_name'], owner.name) def test_follower_num(self): self.assertEqual(self.expected['follower_num'], self.collection.follower_num) def test_page_get_questions(self): questions = [q for q in self.collection._page_get_questions(self.collection.soup)] ques = questions[0] self.assertEqual(self.expected['top_ques_id'], ques.id) self.assertEqual(self.expected['top_ques_title'], ques.title) def test_page_get_answers(self): answers = [a for a in self.collection._page_get_answers(self.collection.soup)] ans = answers[0] self.assertEqual(self.expected['top_ans_id'], ans.id) self.assertEqual(self.expected['top_ans_upvote_num'], ans.upvote_num) self.assertEqual(self.expected['top_ans_author_name'], ans.author.name) self.assertEqual(self.expected['top_ans_author_id'], ans.author.id) def test_questions(self): qs = self.collection.questions ques = next(qs) self.assertEqual(self.expected['top_ques_id'], ques.id) self.assertEqual(self.expected['top_ques_title'], ques.title) def test_answers(self): anses = self.collection.answers ans = next(anses) self.assertEqual(self.expected['top_ans_id'], ans.id) self.assertEqual(self.expected['top_ans_upvote_num'], ans.upvote_num) self.assertEqual(self.expected['top_ans_author_name'], ans.author.name) self.assertEqual(self.expected['top_ans_author_id'], ans.author.id)
class CollectionTest(unittest.TestCase): @classmethod def setUpClass(cls): pass def test_cid(self): pass def test_name(self): pass def test_xsrf(self): pass def test_owner(self): pass def test_follower_num(self): pass def test_page_get_questions(self): pass def test_page_get_answers(self): pass def test_questions(self): pass def test_answers(self): pass
12
0
6
0
6
0
1
0
1
0
0
0
9
0
10
82
70
10
60
26
48
0
47
24
36
1
2
1
10
1,549
7sDream/zhihu-py3
7sDream_zhihu-py3/test/test_answer.py
test_answer.AnswerTest
class AnswerTest(unittest.TestCase): @classmethod def setUpClass(cls): url = 'http://www.zhihu.com/question/24825703/answer/30975949' file_path = os.path.join(TEST_DATA_PATH, 'answer.html') with open(file_path, 'rb') as f: html = f.read() soup = BeautifulSoup(html) answer_saved_path = os.path.join(TEST_DATA_PATH, 'answer.md') with open(answer_saved_path, 'rb') as f: cls.answer_saved = f.read() cls.answer = Answer(url) cls.answer._session = None cls.answer.soup = soup cls.expected = {'id': 30975949, 'aid': 7775236, 'xsrf': 'cfd489623d34ca03adfdc125368c6426', 'html': soup.prettify(), 'author_id': 'tian-ge-xia', 'author_name': '甜阁下', 'question_id': 24825703, 'question_title': '关系亲密的人之间要说「谢谢」吗?', 'upvote_num': 1164, 'upvoter_name': 'Mikuroneko', 'upvoter_id': 'guo-yi-hui-23'} def test_id(self): self.assertEqual(self.expected['id'], self.answer.id) def test_aid(self): self.assertEqual(self.expected['aid'], self.answer.aid) def test_xsrf(self): self.assertEqual(self.expected['xsrf'], self.answer.xsrf) def test_html(self): self.assertEqual(self.expected['html'], self.answer.html) def test_upvote_num(self): self.assertEqual(self.expected['upvote_num'], self.answer.upvote_num) def test_author(self): self.assertEqual(self.expected['author_id'], self.answer.author.id) self.assertEqual(self.expected['author_name'], self.answer.author.name) def test_question(self): self.assertEqual(self.expected['question_id'], self.answer.question.id) self.assertEqual(self.expected['question_title'], self.answer.question.title) def test_content(self): path = os.path.join(TEST_DATA_PATH, 'answer_content.html') with open(path, 'rb') as f: content = f.read() self.assertEqual(content.decode('utf-8'), self.answer.content) def test_save(self): save_name = 'answer_save' self.answer.save(filepath=TEST_DATA_PATH, filename=save_name, mode='md') answer_saved_path = os.path.join(TEST_DATA_PATH, save_name + '.md') with open(answer_saved_path, 'rb') as f: answer_saved = f.read() os.remove(answer_saved_path) self.assertEqual(self.answer_saved, answer_saved) def test_parse_author_soup(self): fpath = os.path.join(TEST_DATA_PATH, 'answer_upvoter.html') with open(fpath, 'rb') as f: html = f.read().decode('utf-8') soup = BeautifulSoup(html) upvoter = self.answer._parse_author_soup(soup) self.assertEqual(self.expected['upvoter_name'], upvoter.name) self.assertEqual(self.expected['upvoter_id'], upvoter.id) def test_save_error(self): with self.assertRaises(ValueError): self.answer.save(filepath=TEST_DATA_PATH, filename='invalid', mode='invalid')
class AnswerTest(unittest.TestCase): @classmethod def setUpClass(cls): pass def test_id(self): pass def test_aid(self): pass def test_xsrf(self): pass def test_html(self): pass def test_upvote_num(self): pass def test_author(self): pass def test_question(self): pass def test_content(self): pass def test_save(self): pass def test_parse_author_soup(self): pass def test_save_error(self): pass
14
0
6
0
5
0
1
0
1
1
0
0
11
0
12
84
79
15
64
32
50
0
54
27
41
1
2
1
12
1,550
7sDream/zhihu-py3
7sDream_zhihu-py3/test/test_column.py
test_column.ColumnTest
class ColumnTest(unittest.TestCase): @classmethod def setUpClass(cls): url = 'http://zhuanlan.zhihu.com/xiepanda' file_path = os.path.join(TEST_DATA_PATH, 'column.json') with open(file_path, 'r') as f: soup = json.load(f) post_path = os.path.join(TEST_DATA_PATH, 'column_post.json') with open(post_path, 'r') as f: cls.post_json = json.load(f) cls.column = Column(url) cls.column.soup = soup cls.expected = {'name': '谢熊猫出没注意', 'follower_num': 76605, 'post_num': 69, 'post_author_id': 'xiepanda', 'post_title': ("为了做一个称职的吃货,他决定连着吃" "一百天转基因食物"), 'post_upvote_num': 963, 'post_comment_num': 199} def test_name(self): self.assertEqual(self.expected['name'], self.column.name) def test_folower_num(self): self.assertEqual(self.expected['follower_num'], self.column.follower_num) def test_post_num(self): self.assertEqual(self.expected['post_num'], self.column.post_num) def test_parse_post_data(self): post = self.column._parse_post_data(self.post_json) self.assertEqual(self.expected['post_author_id'], post.author.id) self.assertEqual(self.expected['post_title'], post.title) self.assertEqual(self.expected['post_upvote_num'], post.upvote_num) self.assertEqual(self.expected['post_comment_num'], post.comment_num) def test_posts(self): ps = self.column.posts post = next(ps) self.assertTrue(isinstance(post, Post))
class ColumnTest(unittest.TestCase): @classmethod def setUpClass(cls): pass def test_name(self): pass def test_folower_num(self): pass def test_post_num(self): pass def test_parse_post_data(self): pass def test_posts(self): pass
8
0
6
0
5
0
1
0
1
0
0
0
5
0
6
78
41
7
34
16
26
0
28
14
21
1
2
1
6
1,551
7sDream/zhihu-py3
7sDream_zhihu-py3/zhihu/acttype.py
zhihu.acttype.CollectActType
class CollectActType(enum.Enum): """用于表示收藏夹操作的类型. :常量说明: ================= ============== 常量名 说明 ================= ============== INSERT_ANSWER 在收藏夹中增加一个回答 DELETE_ANSWER 在收藏夹中删除一个回答 CREATE_COLLECTION 创建收藏夹 ================= ============== """ INSERT_ANSWER = 1 DELETE_ANSWER = 2 CREATE_COLLECTION = 3
class CollectActType(enum.Enum): '''用于表示收藏夹操作的类型. :常量说明: ================= ============== 常量名 说明 ================= ============== INSERT_ANSWER 在收藏夹中增加一个回答 DELETE_ANSWER 在收藏夹中删除一个回答 CREATE_COLLECTION 创建收藏夹 ================= ============== ''' pass
1
1
0
0
0
0
0
2.5
1
0
0
0
0
0
0
49
15
1
4
4
3
10
4
4
3
0
4
0
0
1,552
7sDream/zhihu-py3
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/7sDream_zhihu-py3/zhihu/author.py
zhihu.author.Author
class Author(BaseZhihu): """用户类,请使用``ZhihuClient.answer``方法构造对象.""" @class_common_init(re_author_url, True) def __init__(self, url, name=None, motto=None, follower_num=None, question_num=None, answer_num=None, upvote_num=None, thank_num=None, photo_url=None, session=None): """创建用户类实例. :param str url: 用户主页url,形如 http://www.zhihu.com/people/7sdream :param str name: 用户名字,可选 :param str motto: 用户简介,可选 :param int follower_num: 用户粉丝数,可选 :param int question_num: 用户提问数,可选 :param int answer_num: 用户答案数,可选 :param int upvote_num: 用户获得赞同数,可选 :param int thank_num: 用户获得感谢数,可选 :param str photo_url: 用户头像地址,可选 :param Session session: 使用的网络会话,为空则使用新会话。 :return: 用户对象 :rtype: Author """ self.url = url self._session = session self.card = None self._nav_list = None self._name = name self._motto = motto self._follower_num = follower_num self._question_num = question_num self._answer_num = answer_num self._upvote_num = upvote_num self._thank_num = thank_num self._photo_url = photo_url def _gen_soup(self, content): self.soup = BeautifulSoup(content) ban_title = self.soup.find("div", class_="ProfileBan-title") if ban_title is not None: raise BanException(ban_title.text) self._nav_list = self.soup.find( 'div', class_='profile-navbar').find_all('a') def _make_card(self): if self.card is None and self.url is not None: params = {'url_token': self.id} real_params = {'params': json.dumps(params)} r = self._session.get(Get_Profile_Card_URL, params=real_params) self.card = BeautifulSoup(r.content) @property def id(self): """获取用户id,就是网址最后那一部分. :return: 用户id :rtype: str """ return re.match(r'^.*/([^/]+)/$', self.url).group(1) \ if self.url is not None else '' @property @check_soup('_xsrf') def xsrf(self): """获取知乎的反xsrf参数(用不到就忽视吧~) :return: xsrf参数 :rtype: str """ return self.soup.find('input', attrs={'name': '_xsrf'})['value'] @property @check_soup('_hash_id') def hash_id(self): """获取作者的内部hash id(用不到就忽视吧~) :return: 用户hash id :rtype: str """ div = self.soup.find('div', class_='zm-profile-header-op-btns') if div is not None: return div.button['data-id'] else: ga = self.soup.find('script', attrs={'data-name': 'ga_vars'}) return json.loads(ga.text)['user_hash'] @property @check_soup('_name', '_make_card') def name(self): """获取用户名字. :return: 用户名字 :rtype: str """ if self.url is None: return '匿名用户' if self.soup is not None: return self.soup.find('div', class_='title-section').span.text else: assert self.card is not None return self.card.find('span', class_='name').text @property @check_soup('_motto', '_make_card') def motto(self): """获取用户自我介绍,由于历史原因,我还是把这个属性叫做motto吧. :return: 用户自我介绍 :rtype: str """ if self.url is None: return '' else: if self.soup is not None: bar = self.soup.find( 'div', class_='title-section') if len(bar.contents) < 4: return '' else: return bar.contents[3].text else: assert self.card is not None motto = self.card.find('div', class_='tagline') return motto.text if motto is not None else '' @property @check_soup('_photo_url', '_make_card') def photo_url(self): """获取用户头像图片地址. :return: 用户头像url :rtype: str """ if self.url is not None: if self.soup is not None: img = self.soup.find('img', class_='Avatar Avatar--l')['src'] return img.replace('_l', '_r') else: assert (self.card is not None) return PROTOCOL + self.card.img['src'].replace('_xs', '_r') else: return 'http://pic1.zhimg.com/da8e974dc_r.jpg' @property @check_soup('_followee_num') def followee_num(self): """获取关注了多少人. :return: 关注的人数 :rtype: int """ if self.url is None: return 0 else: number = int(self.soup.find( 'div', class_='zm-profile-side-following').a.strong.text) return number @property @check_soup('_follower_num') def follower_num(self): """获取追随者数量,就是关注此人的人数. :return: 追随者数量 :rtype: int """ if self.url is None: return 0 else: number = int(self.soup.find( 'div', class_='zm-profile-side-following zg-clear').find_all( 'a')[1].strong.text) return number @property @check_soup('_upvote_num') def upvote_num(self): """获取收到的的赞同数量. :return: 收到的的赞同数量 :rtype: int """ if self.url is None: return 0 else: number = int(self.soup.find( 'span', class_='zm-profile-header-user-agree').strong.text) return number @property @check_soup('_thank_num') def thank_num(self): """获取收到的感谢数量. :return: 收到的感谢数量 :rtype: int """ if self.url is None: return 0 else: number = int(self.soup.find( 'span', class_='zm-profile-header-user-thanks').strong.text) return number @property @check_soup('_weibo_url') def weibo_url(self): """获取用户微博链接. :return: 微博链接地址,如没有则返回 ‘unknown’ :rtype: str """ if self.url is None: return None else: tmp = self.soup.find( 'a', class_='zm-profile-header-user-weibo') return tmp['href'] if tmp is not None else 'unknown' @property def business(self): """用户的行业. :return: 用户的行业,如没有则返回 ‘unknown’ :rtype: str """ return self._find_user_profile('business') @property def location(self): """用户的所在地. :return: 用户的所在地,如没有则返回 ‘unknown’ :rtype: str """ return self._find_user_profile('location') @property def education(self): """用户的教育状况. :return: 用户的教育状况,如没有则返回 ‘unknown’ :rtype: str """ return self._find_user_profile('education') def _find_user_profile(self, t): self._make_soup() if self.url is None: return 'unknown' else: res = self.soup.find( 'span', class_=t) if res and res.has_attr('title'): return res['title'] else: return 'unknown' @property @check_soup('_gender') def gender(self): """用户的性别. :return: 用户的性别(male/female/unknown) :rtype: str """ if self.url is None: return 'unknown' else: return 'female' \ if self.soup.find('i', class_='icon-profile-female') \ else 'male' @property @check_soup('_question_num') def question_num(self): """获取提问数量. :return: 提问数量 :rtype: int """ if self.url is None: return 0 else: return int(self._nav_list[1].span.text) @property @check_soup('_answer_num') def answer_num(self): """获取答案数量. :return: 答案数量 :rtype: int """ if self.url is None: return 0 else: return int(self._nav_list[2].span.text) @property @check_soup('_post_num') def post_num(self): """获取专栏文章数量. :return: 专栏文章数量 :rtype: int """ if self.url is None: return 0 else: return int(self._nav_list[3].span.text) @property @check_soup('_collection_num') def collection_num(self): """获取收藏夹数量. :return: 收藏夹数量 :rtype: int """ if self.url is None: return 0 else: return int(self._nav_list[4].span.text) @property @check_soup('_followed_column_num') def followed_column_num(self): """获取用户关注的专栏数 :return: 关注的专栏数 :rtype: int """ if self.url is not None: tag = self.soup.find('div', class_='zm-profile-side-columns') if tag is not None: return int(re_get_number.match( tag.parent.strong.text).group(1)) return 0 @property @check_soup('_followed_topic_num') def followed_topic_num(self): """获取用户关注的话题数 :return: 关注的话题数 :rtype: int """ if self.url is not None: tag = self.soup.find('div', class_='zm-profile-side-topics') if tag is not None: return int(re_get_number.match( tag.parent.strong.text).group(1)) return 0 @property def questions(self): """获取用户的所有问题. :return: 用户的所有问题,返回生成器. :rtype: Question.Iterable """ from .question import Question if self.url is None or self.question_num == 0: return for page_index in range(1, (self.question_num - 1) // 20 + 2): html = self._session.get( self.url + 'asks?page=' + str(page_index)).text soup = BeautifulSoup(html) question_links = soup.find_all('a', class_='question_link') question_datas = soup.find_all( 'div', class_='zm-profile-section-main') for link, data in zip(question_links, question_datas): url = Zhihu_URL + link['href'] title = link.text.strip() answer_num = int( re_get_number.match(data.div.contents[4]).group(1)) follower_num = int( re_get_number.match(data.div.contents[6]).group(1)) q = Question(url, title, follower_num, answer_num, session=self._session) yield q @property def answers(self): """获取用户的所有答案. :return: 用户所有答案,返回生成器. :rtype: Answer.Iterable """ from .question import Question from .answer import Answer if self.url is None or self.answer_num == 0: return for page_index in range(1, (self.answer_num - 1) // 20 + 2): html = self._session.get( self.url + 'answers?page=' + str(page_index)).text soup = BeautifulSoup(html) questions = soup.find_all('a', class_='question_link') upvotes = soup.find_all('a', class_='zm-item-vote-count') for q, upvote in zip(questions, upvotes): answer_url = Zhihu_URL + q['href'] question_url = Zhihu_URL + re_a2q.match(q['href']).group(1) question_title = q.text upvote_num = upvote.text if upvote_num.isdigit(): upvote_num = int(upvote_num) else: upvote_num = None question = Question(question_url, question_title, session=self._session) yield Answer(answer_url, question, self, upvote_num, session=self._session) @property def followers(self): """获取关注此用户的人. :return: 关注此用户的人,返回生成器 :rtype: Author.Iterable """ for x in self._follow_ee_ers('er'): yield x @property def followees(self): """获取用户关注的人. :return: 用户关注的人的,返回生成器 :rtype: Author.Iterable """ for x in self._follow_ee_ers('ee'): yield x def followers_skip(self, skip): """获取关注此用户的人,跳过前 skip 个用户。 :return: 关注此用户的人,返回生成器 :rtype: Author.Iterable """ for x in self._follow_ee_ers('er', skip): yield x def followees_skip(self, skip): """获取用户关注的人,跳过前 skip 个用户。 :return: 用户关注的人的,返回生成器 :rtype: Author.Iterable """ for x in self._follow_ee_ers('ee', skip): yield x def _follow_ee_ers(self, t, skip=0): if self.url is None: return if t == 'er': request_url = Author_Get_More_Followers_URL else: request_url = Author_Get_More_Followees_URL self._make_card() if self.hash_id is None: self._make_soup() headers = dict(Default_Header) headers['Referer'] = self.url + 'follow' + t + 's' params = {"order_by": "created", "offset": 0, "hash_id": self.hash_id} data = {'_xsrf': self.xsrf, 'method': 'next', 'params': ''} gotten_date_num = 20 offset = skip while gotten_date_num == 20: params['offset'] = offset data['params'] = json.dumps(params) res = self._session.post(request_url, data=data, headers=headers) json_data = res.json() gotten_date_num = len(json_data['msg']) offset += gotten_date_num for html in json_data['msg']: soup = BeautifulSoup(html) h2 = soup.find('h2') author_name = h2.a.text author_url = h2.a['href'] author_motto = soup.find('span', class_='bio').text author_photo = PROTOCOL + soup.a.img['src'].replace('_m', '_r') numbers = [ int(re_get_number.match(x.text).group(1)) for x in soup.find_all('a', class_="zg-link-gray-normal") ] try: yield Author(author_url, author_name, author_motto, *numbers, photo_url=author_photo, session=self._session) except ValueError: # invalid url yield ANONYMOUS @property def collections(self): """获取用户收藏夹. :return: 用户收藏夹,返回生成器 :rtype: Collection.Iterable """ from .collection import Collection if self.url is None or self.collection_num == 0: return else: collection_num = self.collection_num for page_index in range(1, (collection_num - 1) // 20 + 2): html = self._session.get( self.url + 'collections?page=' + str(page_index)).text soup = BeautifulSoup(html) collections_names = soup.find_all( 'a', class_='zm-profile-fav-item-title') collection_follower_nums = soup.find_all( 'div', class_='zm-profile-fav-bio') for c, f in zip(collections_names, collection_follower_nums): c_url = Zhihu_URL + c['href'] c_name = c.text c_fn = int(re_get_number.match(f.contents[2]).group(1)) yield Collection(c_url, self, c_name, c_fn, session=self._session) @property def columns(self): """获取用户专栏. :return: 用户专栏,返回生成器 :rtype: Column.Iterable """ from .column import Column if self.url is None or self.post_num == 0: return soup = BeautifulSoup(self._session.get(self.url + 'posts').text) column_list = soup.find('div', class_='column-list') column_tags = column_list.find_all('div', class_='item') for column_tag in column_tags: name = column_tag['title'] url = column_tag['data-href'] numbers = column_tag.find('span', class_='des').text.split('•') follower_num = int(re_get_number.match(numbers[0]).group(1)) if len(numbers) == 1: post_num = 0 else: post_num = int( re_get_number.match(numbers[1]).group(1)) yield Column(url, name, follower_num, post_num, session=self._session) @property def followed_columns(self): """获取用户关注的专栏. :return: 用户关注的专栏,返回生成器 :rtype: Column.Iterable """ from .column import Column if self.url is None: return if self.followed_column_num > 0: tag = self.soup.find('div', class_='zm-profile-side-columns') if tag is not None: for a in tag.find_all('a'): yield Column(a['href'], a.img['alt'], session=self._session) if self.followed_column_num > 7: offset = 7 gotten_data_num = 20 while gotten_data_num == 20: params = { 'hash_id': self.hash_id, 'limit': 20, 'offset': offset } data = { 'method': 'next', '_xsrf': self.xsrf, 'params': json.dumps(params) } j = self._session.post(Author_Get_More_Follow_Column_URL, data=data).json() gotten_data_num = len(j['msg']) offset += gotten_data_num for msg in map(BeautifulSoup, j['msg']): name = msg.strong.text url = msg.a['href'] post_num = int(re_get_number.match( msg.span.text).group(1)) yield Column(url, name, post_num=post_num, session=self._session) @property def followed_topics(self): """获取用户关注的话题. :return: 用户关注的话题,返回生成器 :rtype: Topic.Iterable """ from .topic import Topic if self.url is None: return if self.followed_topic_num > 0: tag = self.soup.find('div', class_='zm-profile-side-topics') if tag is not None: for a in tag.find_all('a'): yield Topic(Zhihu_URL + a['href'], a.img['alt'], session=self._session) if self.followed_topic_num > 7: offset = 7 gotten_data_num = 20 while gotten_data_num == 20: data = {'start': 0, 'offset': offset, '_xsrf': self.xsrf} j = self._session.post( Author_Get_More_Follow_Topic_URL.format(self.id), data=data).json() gotten_data_num = j['msg'][0] offset += gotten_data_num topic_item = BeautifulSoup(j['msg'][1]).find_all( 'div', class_='zm-profile-section-item') for div in topic_item: name = div.strong.text url = Zhihu_URL + div.a['href'] yield Topic(url, name, session=self._session) @property def activities(self): """获取用户的最近动态. :return: 最近动态,返回生成器,具体说明见 :class:`.Activity` :rtype: Activity.Iterable """ from .activity import Activity if self.url is None: return gotten_feed_num = 20 start = '0' api_url = self.url + 'activities' while gotten_feed_num == 20: data = {'_xsrf': self.xsrf, 'start': start} res = self._session.post(api_url, data=data) gotten_feed_num = res.json()['msg'][0] soup = BeautifulSoup(res.json()['msg'][1]) acts = soup.find_all( 'div', class_='zm-profile-section-item zm-item clearfix') start = acts[-1]['data-time'] if len(acts) > 0 else 0 for act in acts: # --- ignore Round Table temporarily --- if act.attrs['data-type-detail'] == "member_follow_roundtable": continue # --- --- --- --- -- --- --- --- --- --- yield Activity(act, self._session, self) @property def last_activity_time(self): """获取用户最后一次活动的时间 :return: 用户最后一次活动的时间,返回值为 unix 时间戳 :rtype: int """ self._make_soup() act = self.soup.find( 'div', class_='zm-profile-section-item zm-item clearfix') return int(act['data-time']) if act is not None else -1 def is_zero_user(self): """返回当前用户是否为三零用户,其实是四零: 赞同0,感谢0,提问0,回答0. :return: 是否是三零用户 :rtype: bool """ return self.upvote_num + self.thank_num + \ self.question_num + self.answer_num == 0
class Author(BaseZhihu): '''用户类,请使用``ZhihuClient.answer``方法构造对象.''' @class_common_init(re_author_url, True) def __init__(self, url, name=None, motto=None, follower_num=None, question_num=None, answer_num=None, upvote_num=None, thank_num=None, photo_url=None, session=None): '''创建用户类实例. :param str url: 用户主页url,形如 http://www.zhihu.com/people/7sdream :param str name: 用户名字,可选 :param str motto: 用户简介,可选 :param int follower_num: 用户粉丝数,可选 :param int question_num: 用户提问数,可选 :param int answer_num: 用户答案数,可选 :param int upvote_num: 用户获得赞同数,可选 :param int thank_num: 用户获得感谢数,可选 :param str photo_url: 用户头像地址,可选 :param Session session: 使用的网络会话,为空则使用新会话。 :return: 用户对象 :rtype: Author ''' pass def _gen_soup(self, content): pass def _make_card(self): pass @property def id(self): '''获取用户id,就是网址最后那一部分. :return: 用户id :rtype: str ''' pass @property @check_soup('_xsrf') def xsrf(self): '''获取知乎的反xsrf参数(用不到就忽视吧~) :return: xsrf参数 :rtype: str ''' pass @property @check_soup('_hash_id') def hash_id(self): '''获取作者的内部hash id(用不到就忽视吧~) :return: 用户hash id :rtype: str ''' pass @property @check_soup('_name', '_make_card') def name(self): '''获取用户名字. :return: 用户名字 :rtype: str ''' pass @property @check_soup('_motto', '_make_card') def motto(self): '''获取用户自我介绍,由于历史原因,我还是把这个属性叫做motto吧. :return: 用户自我介绍 :rtype: str ''' pass @property @check_soup('_photo_url', '_make_card') def photo_url(self): '''获取用户头像图片地址. :return: 用户头像url :rtype: str ''' pass @property @check_soup('_followee_num') def followee_num(self): '''获取关注了多少人. :return: 关注的人数 :rtype: int ''' pass @property @check_soup('_follower_num') def follower_num(self): '''获取追随者数量,就是关注此人的人数. :return: 追随者数量 :rtype: int ''' pass @property @check_soup('_upvote_num') def upvote_num(self): '''获取收到的的赞同数量. :return: 收到的的赞同数量 :rtype: int ''' pass @property @check_soup('_thank_num') def thank_num(self): '''获取收到的感谢数量. :return: 收到的感谢数量 :rtype: int ''' pass @property @check_soup('_weibo_url') def weibo_url(self): '''获取用户微博链接. :return: 微博链接地址,如没有则返回 ‘unknown’ :rtype: str ''' pass @property def business(self): '''用户的行业. :return: 用户的行业,如没有则返回 ‘unknown’ :rtype: str ''' pass @property def location(self): '''用户的所在地. :return: 用户的所在地,如没有则返回 ‘unknown’ :rtype: str ''' pass @property def education(self): '''用户的教育状况. :return: 用户的教育状况,如没有则返回 ‘unknown’ :rtype: str ''' pass def _find_user_profile(self, t): pass @property @check_soup('_gender') def gender(self): '''用户的性别. :return: 用户的性别(male/female/unknown) :rtype: str ''' pass @property @check_soup('_question_num') def question_num(self): '''获取提问数量. :return: 提问数量 :rtype: int ''' pass @property @check_soup('_answer_num') def answer_num(self): '''获取答案数量. :return: 答案数量 :rtype: int ''' pass @property @check_soup('_post_num') def post_num(self): '''获取专栏文章数量. :return: 专栏文章数量 :rtype: int ''' pass @property @check_soup('_collection_num') def collection_num(self): '''获取收藏夹数量. :return: 收藏夹数量 :rtype: int ''' pass @property @check_soup('_followed_column_num') def followed_column_num(self): '''获取用户关注的专栏数 :return: 关注的专栏数 :rtype: int ''' pass @property @check_soup('_followed_topic_num') def followed_topic_num(self): '''获取用户关注的话题数 :return: 关注的话题数 :rtype: int ''' pass @property def questions(self): '''获取用户的所有问题. :return: 用户的所有问题,返回生成器. :rtype: Question.Iterable ''' pass @property def answers(self): '''获取用户的所有答案. :return: 用户所有答案,返回生成器. :rtype: Answer.Iterable ''' pass @property def followers(self): '''获取关注此用户的人. :return: 关注此用户的人,返回生成器 :rtype: Author.Iterable ''' pass @property def followees(self): '''获取用户关注的人. :return: 用户关注的人的,返回生成器 :rtype: Author.Iterable ''' pass def followers_skip(self, skip): '''获取关注此用户的人,跳过前 skip 个用户。 :return: 关注此用户的人,返回生成器 :rtype: Author.Iterable ''' pass def followees_skip(self, skip): '''获取用户关注的人,跳过前 skip 个用户。 :return: 用户关注的人的,返回生成器 :rtype: Author.Iterable ''' pass def _follow_ee_ers(self, t, skip=0): pass @property def collections(self): '''获取用户收藏夹. :return: 用户收藏夹,返回生成器 :rtype: Collection.Iterable ''' pass @property def columns(self): '''获取用户专栏. :return: 用户专栏,返回生成器 :rtype: Column.Iterable ''' pass @property def followed_columns(self): '''获取用户关注的专栏. :return: 用户关注的专栏,返回生成器 :rtype: Column.Iterable ''' pass @property def followed_topics(self): '''获取用户关注的话题. :return: 用户关注的话题,返回生成器 :rtype: Topic.Iterable ''' pass @property def activities(self): '''获取用户的最近动态. :return: 最近动态,返回生成器,具体说明见 :class:`.Activity` :rtype: Activity.Iterable ''' pass @property def last_activity_time(self): '''获取用户最后一次活动的时间 :return: 用户最后一次活动的时间,返回值为 unix 时间戳 :rtype: int ''' pass def is_zero_user(self): '''返回当前用户是否为三零用户,其实是四零: 赞同0,感谢0,提问0,回答0. :return: 是否是三零用户 :rtype: bool ''' pass
89
36
15
1
10
4
3
0.35
1
14
7
1
39
13
39
44
675
81
441
203
342
154
315
169
267
8
1
4
112
1,553
7sDream/zhihu-py3
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/7sDream_zhihu-py3/zhihu/collection.py
zhihu.collection.Collection
class Collection(BaseZhihu): """收藏夹,请使用``ZhihuClient.collection``方法构造对象.""" @class_common_init(re_collection_url) def __init__(self, url, owner=None, name=None, follower_num=None, session=None): """创建收藏夹类实例. :param str url: 收藏夹主页url,必须 :param Author owner: 收藏夹拥有者,可选 :param str name: 收藏夹标题,可选 :param int follower_num: 收藏夹关注人数,可选 :param Session session: 使用的网络会话,为空则使用新会话。 :return: 收藏夹对象 :rtype: Collection """ self.url = url self._session = session self.soup = None self._name = name self._owner = owner self._follower_num = follower_num self._id = int(re.match(r'.*/(\d+)', self.url).group(1)) @property def id(self): """获取收藏夹id(网址最后的部分). :return: 收藏夹id :rtype: int """ return self._id @property @check_soup('_cid') def cid(self): """获取收藏夹内部Id(用不到忽视就好) :return: 内部Id :rtype: int """ return int(re_get_number.match( self.soup.find('a', attrs={'name': 'focus'})['id']).group(1)) @property @check_soup('_xsrf') def xsrf(self): """获取知乎的反xsrf参数(用不到就忽视吧~) :return: xsrf参数 :rtype: str """ return self.soup.find( 'input', attrs={'name': '_xsrf'})['value'] @property @check_soup('_name') def name(self): """获取收藏夹名字. :return: 收藏夹名字 :rtype: str """ return re_del_empty_line.match( self.soup.find('h2', id='zh-fav-head-title').text).group(1) @property @check_soup('_owner') def owner(self): """获取收藏夹拥有者,返回Author对象. :return: 收藏夹拥有者 :rtype: Author """ from .author import Author a = self.soup.find('h2', class_='zm-list-content-title').a name = a.text url = Zhihu_URL + a['href'] motto = self.soup.find( 'div', id='zh-single-answer-author-info').div.text photo_url = PROTOCOL + self.soup.find( 'img', class_='zm-list-avatar-medium')['src'].replace('_m', '_r') return Author(url, name, motto, photo_url=photo_url, session=self._session) @property @check_soup('_follower_num') def follower_num(self): """获取关注此收藏夹的人数. :return: 关注此收藏夹的人数 :rtype: int """ href = re_collection_url_split.match(self.url).group(1) return int(self.soup.find('a', href=href + 'followers').text) @property def followers(self): """获取关注此收藏夹的用户 :return: 关注此收藏夹的用户 :rtype: Author.Iterable """ self._make_soup() followers_url = self.url + 'followers' for x in common_follower(followers_url, self.xsrf, self._session): yield x @property def questions(self): """获取收藏夹内所有问题对象. :return: 收藏夹内所有问题,返回生成器 :rtype: Question.Iterable """ self._make_soup() # noinspection PyTypeChecker for question in self._page_get_questions(self.soup): yield question i = 2 while True: soup = BeautifulSoup(self._session.get( self.url[:-1] + '?page=' + str(i)).text) for question in self._page_get_questions(soup): if question == 0: return yield question i += 1 @property def answers(self): """获取收藏夹内所有答案对象. :return: 收藏夹内所有答案,返回生成器 :rtype: Answer.Iterable """ self._make_soup() # noinspection PyTypeChecker for answer in self._page_get_answers(self.soup): yield answer i = 2 while True: soup = BeautifulSoup(self._session.get( self.url[:-1] + '?page=' + str(i)).text) for answer in self._page_get_answers(soup): if answer == 0: return yield answer i += 1 @property def logs(self): """获取收藏夹日志 :return: 收藏夹日志中的操作,返回生成器 :rtype: CollectActivity.Iterable """ import time from datetime import datetime from .answer import Answer from .question import Question from .acttype import CollectActType self._make_soup() gotten_feed_num = 20 offset = 0 data = { 'start': 0, '_xsrf': self.xsrf } api_url = self.url + 'log' while gotten_feed_num == 20: data['offset'] = offset res = self._session.post(url=api_url, data=data) gotten_feed_num = res.json()['msg'][0] soup = BeautifulSoup(res.json()['msg'][1]) offset += gotten_feed_num zm_items = soup.find_all('div', class_='zm-item') for zm_item in zm_items: act_time = datetime.strptime( zm_item.find('time').text, "%Y-%m-%d %H:%M:%S") if zm_item.find('ins'): link = zm_item.find('ins').a act_type = CollectActType.INSERT_ANSWER elif zm_item.find('del'): link = zm_item.find('del').a act_type = CollectActType.DELETE_ANSWER else: continue try: answer_url = Zhihu_URL + link['href'] question_url = re_a2q.match(answer_url).group(1) question = Question(question_url, link.text) answer = Answer( answer_url, question, session=self._session) yield CollectActivity( act_type, act_time, self.owner, self, answer) except AttributeError: act_type = CollectActType.CREATE_COLLECTION yield CollectActivity( act_type, act_time, self.owner, self) data['start'] = zm_items[-1]['id'][8:] time.sleep(0.5) def _page_get_questions(self, soup): from .question import Question question_tags = soup.find_all("div", class_="zm-item") if len(question_tags) == 0: yield 0 return else: for question_tag in question_tags: if question_tag.h2 is not None: question_title = question_tag.h2.a.text question_url = Zhihu_URL + question_tag.h2.a['href'] yield Question(question_url, question_title, session=self._session) def _page_get_answers(self, soup): from .question import Question from .author import Author, ANONYMOUS from .answer import Answer answer_tags = soup.find_all("div", class_="zm-item") if len(answer_tags) == 0: yield 0 return else: question = None for tag in answer_tags: # 判断是否是'建议修改的回答'等情况 url_tag = tag.find('a', class_='answer-date-link') if url_tag is None: reason = tag.find('div', id='answer-status').p.text print("pass a answer, reason %s ." % reason) continue if tag.h2 is not None: question_title = tag.h2.a.text question_url = Zhihu_URL + tag.h2.a['href'] question = Question(question_url, question_title, session=self._session) answer_url = Zhihu_URL + url_tag['href'] div = tag.find('div', class_='zm-item-answer-author-info') author_link = div.find('a', class_='author-link') if author_link is not None: author_url = Zhihu_URL + author_link['href'] author_name = author_link.text motto_span = div.find('span', class_='bio') author_motto = motto_span['title'] if motto_span else '' author = Author(author_url, author_name, author_motto, session=self._session) else: author = ANONYMOUS upvote_num = tag.find('a', class_='zm-item-vote-count').text if upvote_num.isdigit(): upvote_num = int(upvote_num) else: upvote_num = None answer = Answer(answer_url, question, author, upvote_num, session=self._session) yield answer
class Collection(BaseZhihu): '''收藏夹,请使用``ZhihuClient.collection``方法构造对象.''' @class_common_init(re_collection_url) def __init__(self, url, owner=None, name=None, follower_num=None, session=None): '''创建收藏夹类实例. :param str url: 收藏夹主页url,必须 :param Author owner: 收藏夹拥有者,可选 :param str name: 收藏夹标题,可选 :param int follower_num: 收藏夹关注人数,可选 :param Session session: 使用的网络会话,为空则使用新会话。 :return: 收藏夹对象 :rtype: Collection ''' pass @property def id(self): '''获取收藏夹id(网址最后的部分). :return: 收藏夹id :rtype: int ''' pass @property @check_soup('_cid') def cid(self): '''获取收藏夹内部Id(用不到忽视就好) :return: 内部Id :rtype: int ''' pass @property @check_soup('_xsrf') def xsrf(self): '''获取知乎的反xsrf参数(用不到就忽视吧~) :return: xsrf参数 :rtype: str ''' pass @property @check_soup('_name') def name(self): '''获取收藏夹名字. :return: 收藏夹名字 :rtype: str ''' pass @property @check_soup('_owner') def owner(self): '''获取收藏夹拥有者,返回Author对象. :return: 收藏夹拥有者 :rtype: Author ''' pass @property @check_soup('_follower_num') def follower_num(self): '''获取关注此收藏夹的人数. :return: 关注此收藏夹的人数 :rtype: int ''' pass @property def followers(self): '''获取关注此收藏夹的用户 :return: 关注此收藏夹的用户 :rtype: Author.Iterable ''' pass @property def questions(self): '''获取收藏夹内所有问题对象. :return: 收藏夹内所有问题,返回生成器 :rtype: Question.Iterable ''' pass @property def answers(self): '''获取收藏夹内所有答案对象. :return: 收藏夹内所有答案,返回生成器 :rtype: Answer.Iterable ''' pass @property def logs(self): '''获取收藏夹日志 :return: 收藏夹日志中的操作,返回生成器 :rtype: CollectActivity.Iterable ''' pass def _page_get_questions(self, soup): pass def _page_get_answers(self, soup): pass
30
12
18
1
13
4
3
0.29
1
9
5
0
13
7
13
18
264
30
181
93
140
53
140
81
116
8
1
3
37
1,554
7sDream/zhihu-py3
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/7sDream_zhihu-py3/zhihu/column.py
zhihu.column.Column
class Column(JsonAsSoupMixin, BaseZhihu): """专栏类,请使用``ZhihuClient.column``方法构造对象.""" @class_common_init(re_column_url) def __init__(self, url, name=None, follower_num=None, post_num=None, session=None): """创建专栏类实例. :param str url: 专栏url :param str name: 专栏名,可选 :param int follower_num: 关注者数量,可选 :param int post_num: 文章数量,可选 :param Session session: 使用的网络会话,为空则使用新会话。 :return: 专栏对象 :rtype: Column """ self._in_name = re_column_url.match(url).group(1) self.url = url self._session = session self._name = name self._follower_num = follower_num self._post_num = post_num def _make_soup(self): if self.soup is None: json = self._get_content() self._gen_soup(json) def _get_content(self): origin_host = self._session.headers.get('Host') self._session.headers.update(Host='zhuanlan.zhihu.com') res = self._session.get(Column_Data.format(self._in_name)) self._session.headers.update(Host=origin_host) return res.json() @property @check_soup('_name') def name(self): """获取专栏名称. :return: 专栏名称 :rtype: str """ return self.soup['name'] @property @check_soup('_follower_num') def follower_num(self): """获取关注人数. :return: 关注人数 :rtype: int """ return int(self.soup['followersCount']) @property @check_soup('_post_num') def post_num(self): """获取专栏文章数. :return: 专栏文章数 :rtype: int """ return int(self.soup['postsCount']) @property def posts(self): """获取专栏的所有文章. :return: 专栏所有文章,返回生成器 :rtype: Post.Iterable """ origin_host = self._session.headers.get('Host') for offset in range(0, (self.post_num - 1) // 10 + 1): self._session.headers.update(Host='zhuanlan.zhihu.com') res = self._session.get( Column_Posts_Data.format(self._in_name, offset * 10)) soup = res.json() self._session.headers.update(Host=origin_host) for post in soup: yield self._parse_post_data(post) def _parse_post_data(self, post): from .author import Author from .post import Post url = Column_Url + post['url'] template = post['author']['avatar']['template'] photo_id = post['author']['avatar']['id'] photo_url = template.format(id=photo_id, size='r') author = Author(post['author']['profileUrl'], post['author']['name'], post['author']['bio'], photo_url=photo_url, session=self._session) title = post['title'] upvote_num = post['likesCount'] comment_num = post['commentsCount'] print(url) return Post(url, self, author, title, upvote_num, comment_num, session=self._session)
class Column(JsonAsSoupMixin, BaseZhihu): '''专栏类,请使用``ZhihuClient.column``方法构造对象.''' @class_common_init(re_column_url) def __init__(self, url, name=None, follower_num=None, post_num=None, session=None): '''创建专栏类实例. :param str url: 专栏url :param str name: 专栏名,可选 :param int follower_num: 关注者数量,可选 :param int post_num: 文章数量,可选 :param Session session: 使用的网络会话,为空则使用新会话。 :return: 专栏对象 :rtype: Column ''' pass def _make_soup(self): pass def _get_content(self): pass @property @check_soup('_name') def name(self): '''获取专栏名称. :return: 专栏名称 :rtype: str ''' pass @property @check_soup('_follower_num') def follower_num(self): '''获取关注人数. :return: 关注人数 :rtype: int ''' pass @property @check_soup('_post_num') def post_num(self): '''获取专栏文章数. :return: 专栏文章数 :rtype: int ''' pass @property def posts(self): '''获取专栏的所有文章. :return: 专栏所有文章,返回生成器 :rtype: Post.Iterable ''' pass def _parse_post_data(self, post): pass
17
6
10
1
6
3
1
0.44
2
4
2
0
8
6
8
14
100
15
59
39
39
26
46
33
35
3
1
2
11
1,555
7sDream/zhihu-py3
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/7sDream_zhihu-py3/zhihu/post.py
zhihu.post.Post
class Post(JsonAsSoupMixin, BaseZhihu): """专栏文章类,请使用``ZhihuClient.post``方法构造对象.""" @class_common_init(re_post_url) def __init__(self, url, column=None, author=None, title=None, upvote_num=None, comment_num=None, session=None): """创建专栏文章类实例. :param str url: 文章url :param Column column: 文章所属专栏,可选 :param Author author: 文章作者,可选 :param str title: 文章标题,可选 :param int upvote_num: 文章赞同数,可选 :param int comment_num: 文章评论数,可选 :param Session session: 使用的网络会话,为空则使用新会话 :return: 专栏文章对象 :rtype: Post """ match = re_post_url.match(url) self.url = url self._session = session self._column = column self._author = author self._title = title self._upvote_num = upvote_num self._comment_num = comment_num self._slug = int(match.group(1)) # 文章编号 def _make_soup(self): if self.soup is None: json = self._get_content() self._gen_soup(json) def _get_content(self): origin_host = self._session.headers.get('Host') self._session.headers.update(Host='zhuanlan.zhihu.com') json = self._session.get(Column_Post_Data.format(self.slug)).json() self._session.headers.update(Host=origin_host) return json @property def column_in_name(self): """获取文章所在专栏的内部名称(用不到就忽视吧~) :return: 专栏的内部名称 :rtype: str """ self._make_soup() if 'column' in self.soup: return self.soup['column']['slug'] else: return None @property def slug(self): """获取文章的编号(用不到就忽视吧~) :return: 文章编号 :rtype: int """ return self._slug @property @check_soup('_column') def column(self): """获取文章所在专栏. :return: 文章所在专栏 :rtype: Column """ from .column import Column if 'column' in self.soup: url = Column_Url + '/' + self.soup['column']['slug'] name = self.soup['column']['name'] return Column(url, name, session=self._session) else: return None @property @check_soup('_author') def author(self): """获取文章作者. :return: 文章作者 :rtype: Author """ from .author import Author url = self.soup['author']['profileUrl'] name = self.soup['author']['name'] motto = self.soup['author']['bio'] template = self.soup['author']['avatar']['template'] photo_id = self.soup['author']['avatar']['id'] photo_url = template.format(id=photo_id, size='r') return Author(url, name, motto, photo_url=photo_url, session=self._session) @property @check_soup('_title') def title(self): """获取文章标题. :return: 文章标题 :rtype: str """ return self.soup['title'] @property @check_soup('_upvote_num') def upvote_num(self): """获取文章赞同数量. :return: 文章赞同数 :rtype: int """ return int(self.soup['likesCount']) @property @check_soup('_comment_num') def comment_num(self): """获取评论数量. :return: 评论数量 :rtype: int """ return self.soup['commentsCount'] def save(self, filepath=None, filename=None, mode="md"): """保存答案为 Html 文档或 markdown 文档. :param str filepath: 要保存的文件所在的目录, 不填为当前目录下以专栏标题命名的目录, 设为"."则为当前目录。 :param str filename: 要保存的文件名, 不填则默认为 所在文章标题 - 作者名.html/md。 如果文件已存在,自动在后面加上数字区分。 **自定义文件名时请不要输入后缀 .html 或 .md。** :param str mode: 保存类型,可选 `html` 、 `markdown` 、 `md` 。 :return: 无 :rtype: None """ if mode not in ["html", "md", "markdown"]: raise ValueError("`mode` must be 'html', 'markdown' or 'md'," " got {0}".format(mode)) self._make_soup() file = get_path(filepath, filename, mode, self.column.name, self.title + '-' + self.author.name) with open(file, 'wb') as f: if mode == "html": f.write(self.soup['content'].encode('utf-8')) else: import html2text h2t = html2text.HTML2Text() h2t.body_width = 0 f.write(h2t.handle(self.soup['content']).encode('utf-8')) @property def upvoters(self): """获取文章的点赞用户 :return: 文章的点赞用户,返回生成器。 """ from .author import Author, ANONYMOUS self._make_soup() headers = dict(Default_Header) headers['Host'] = 'zhuanlan.zhihu.com' json = self._session.get( Post_Get_Upvoter.format(self.slug), headers=headers ).json() for au in json: try: yield Author( au['profileUrl'], au['name'], au['bio'], photo_url=au['avatar']['template'].format( id=au['avatar']['id'], size='r'), session=self._session ) except ValueError: # invalid url yield ANONYMOUS
class Post(JsonAsSoupMixin, BaseZhihu): '''专栏文章类,请使用``ZhihuClient.post``方法构造对象.''' @class_common_init(re_post_url) def __init__(self, url, column=None, author=None, title=None, upvote_num=None, comment_num=None, session=None): '''创建专栏文章类实例. :param str url: 文章url :param Column column: 文章所属专栏,可选 :param Author author: 文章作者,可选 :param str title: 文章标题,可选 :param int upvote_num: 文章赞同数,可选 :param int comment_num: 文章评论数,可选 :param Session session: 使用的网络会话,为空则使用新会话 :return: 专栏文章对象 :rtype: Post ''' pass def _make_soup(self): pass def _get_content(self): pass @property def column_in_name(self): '''获取文章所在专栏的内部名称(用不到就忽视吧~) :return: 专栏的内部名称 :rtype: str ''' pass @property def slug(self): '''获取文章的编号(用不到就忽视吧~) :return: 文章编号 :rtype: int ''' pass @property @check_soup('_column') def column_in_name(self): '''获取文章所在专栏. :return: 文章所在专栏 :rtype: Column ''' pass @property @check_soup('_author') def author(self): '''获取文章作者. :return: 文章作者 :rtype: Author ''' pass @property @check_soup('_title') def title(self): '''获取文章标题. :return: 文章标题 :rtype: str ''' pass @property @check_soup('_upvote_num') def upvote_num(self): '''获取文章赞同数量. :return: 文章赞同数 :rtype: int ''' pass @property @check_soup('_comment_num') def comment_num(self): '''获取评论数量. :return: 评论数量 :rtype: int ''' pass def save(self, filepath=None, filename=None, mode="md"): '''保存答案为 Html 文档或 markdown 文档. :param str filepath: 要保存的文件所在的目录, 不填为当前目录下以专栏标题命名的目录, 设为"."则为当前目录。 :param str filename: 要保存的文件名, 不填则默认为 所在文章标题 - 作者名.html/md。 如果文件已存在,自动在后面加上数字区分。 **自定义文件名时请不要输入后缀 .html 或 .md。** :param str mode: 保存类型,可选 `html` 、 `markdown` 、 `md` 。 :return: 无 :rtype: None ''' pass @property def upvoters(self): '''获取文章的点赞用户 :return: 文章的点赞用户,返回生成器。 ''' pass
27
11
13
1
7
5
2
0.54
2
5
2
0
12
8
12
18
183
25
104
53
72
56
73
42
56
3
1
2
19
1,556
7sDream/zhihu-py3
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/7sDream_zhihu-py3/zhihu/question.py
zhihu.question.Question
class Question(BaseZhihu): """问题类,请使用``ZhihuClient.question``方法构造对象.""" @class_common_init(re_question_url, trailing_slash=False) def __init__(self, url, title=None, followers_num=None, answer_num=None, creation_time=None, author=None, session=None): """创建问题类实例. :param str url: 问题url. 现在支持两种 url 1. https://www.zhihu.com/question/qid 2. https://www.zhihu.com/question/qid?sort=created 区别在于,使用第一种,调用 ``question.answers`` 的时候会按投票排序返回答案; 使用第二种, 会按时间排序返回答案, 后提交的答案先返回 :param str title: 问题标题,可选, :param int followers_num: 问题关注人数,可选 :param int answer_num: 问题答案数,可选 :param datetime.datetime creation_time: 问题创建时间,可选 :param Author author: 提问者,可选 :return: 问题对象 :rtype: Question """ self._session = session self._url = url self._title = title self._answer_num = answer_num self._followers_num = followers_num self._id = int(re.match(r'.*/(\d+)', self.url).group(1)) self._author = author self._creation_time = creation_time self._logs = None self._deleted = None @property def url(self): # always return url like https://www.zhihu.com/question/1234/ url = re.match(re_question_url_std, self._url).group() return url if url.endswith('/') else url + '/' @property def id(self): """获取问题id(网址最后的部分). :return: 问题id :rtype: int """ return self._id @property @check_soup('_qid') def qid(self): """获取问题内部id(用不到就忽视吧) :return: 问题内部id :rtype: int """ return int(self.soup.find( 'div', id='zh-question-detail')['data-resourceid']) @property @check_soup('_xsrf') def xsrf(self): """获取知乎的反xsrf参数(用不到就忽视吧~) :return: xsrf参数 :rtype: str """ return self.soup.find('input', attrs={'name': '_xsrf'})['value'] @property @check_soup('_html') def html(self): """获取页面源码. :return: 页面源码 :rtype: str """ return self.soup.prettify() @property @check_soup('_title') def title(self): """获取问题标题. :return: 问题标题 :rtype: str """ return self.soup.find('h2', class_='zm-item-title') \ .text.replace('\n', '') @property @check_soup('_details') def details(self): """获取问题详细描述,目前实现方法只是直接获取文本,效果不满意……等更新. :return: 问题详细描述 :rtype: str """ return self.soup.find("div", id="zh-question-detail").div.text @property @check_soup('_answer_num') def answer_num(self): """获取问题答案数量. :return: 问题答案数量 :rtype: int """ answer_num_block = self.soup.find('h3', id='zh-question-answer-num') # 当0人回答或1回答时,都会找不到 answer_num_block, # 通过找答案的赞同数block来判断到底有没有答案。 # (感谢知乎用户 段晓晨 提出此问题) if answer_num_block is None: if self.soup.find('span', class_='count') is not None: return 1 else: return 0 return int(answer_num_block['data-num']) @property @check_soup('_follower_num') def follower_num(self): """获取问题关注人数. :return: 问题关注人数 :rtype: int """ follower_num_block = self.soup.find('div', class_='zg-gray-normal') # 无人关注时 找不到对应block,直接返回0 (感谢知乎用户 段晓晨 提出此问题) if follower_num_block is None or follower_num_block.strong is None: return 0 return int(follower_num_block.strong.text) @property @check_soup('_topics') def topics(self): """获取问题所属话题. :return: 问题所属话题 :rtype: Topic.Iterable """ from .topic import Topic for topic in self.soup.find_all('a', class_='zm-item-tag'): yield Topic(Zhihu_URL + topic['href'], topic.text.replace('\n', ''), session=self._session) @property def followers(self): """获取关注此问题的用户 :return: 关注此问题的用户 :rtype: Author.Iterable :问题: 要注意若执行过程中另外有人关注,可能造成重复获取到某些用户 """ self._make_soup() followers_url = self.url + 'followers' for x in common_follower(followers_url, self.xsrf, self._session): yield x @property def answers(self): """获取问题的所有答案. :return: 问题的所有答案,返回生成器 :rtype: Answer.Iterable """ from .author import Author from .answer import Answer self._make_soup() # TODO: 统一逻辑. 完全可以都用 _parse_answer_html 的逻辑替换 if self._url.endswith('sort=created'): pager = self.soup.find('div', class_='zm-invite-pager') if pager is None: max_page = 1 else: max_page = int(pager.find_all('span')[-2].a.text) for page in range(1, max_page + 1): if page == 1: soup = self.soup else: url = self._url + '&page=%d' % page soup = BeautifulSoup(self._session.get(url).content) error_answers = soup.find_all('div', id='answer-status') for each in error_answers: each['class'] = 'zm-editable-content' answers_wrap = soup.find('div', id='zh-question-answer-wrap') # 正式处理 authors = answers_wrap.find_all( 'div', class_='zm-item-answer-author-info') urls = answers_wrap.find_all('a', class_='answer-date-link') up_num = answers_wrap.find_all('div', class_='zm-item-vote-info') contents = answers_wrap.find_all( 'div', class_='zm-editable-content') assert len(authors) == len(urls) == len(up_num) == len( contents) for author, url, up_num, content in \ zip(authors, urls, up_num, contents): a_url, name, motto, photo = parser_author_from_tag(author) author_obj = Author(a_url, name, motto, photo_url=photo, session=self._session) url = Zhihu_URL + url['href'] up_num = int(up_num['data-votecount']) content = answer_content_process(content) yield Answer(url, self, author_obj, up_num, content, session=self._session) else: pagesize = 10 new_header = dict(Default_Header) new_header['Referer'] = self.url params = {"url_token": self.id, 'pagesize': pagesize, 'offset': 0} data = {'_xsrf': self.xsrf, 'method': 'next', 'params': ''} for i in range(0, (self.answer_num - 1) // pagesize + 1): if i == 0: # 修正各种建议修改的回答…… error_answers = self.soup.find_all('div', id='answer-status') for each in error_answers: each['class'] = 'zm-editable-content' answers_wrap = self.soup.find('div', id='zh-question-answer-wrap') # 正式处理 authors = answers_wrap.find_all( 'div', class_='zm-item-answer-author-info') urls = answers_wrap.find_all( 'a', class_='answer-date-link') up_num = answers_wrap.find_all('div', class_='zm-item-vote-info') contents = answers_wrap.find_all( 'div', class_='zm-editable-content') assert len(authors) == len(urls) == len(up_num) == len( contents) for author, url, up_num, content in \ zip(authors, urls, up_num, contents): a_url, name, motto, photo = parser_author_from_tag( author) author_obj = Author(a_url, name, motto, photo_url=photo, session=self._session) url = Zhihu_URL + url['href'] up_num = int(up_num['data-votecount']) content = answer_content_process(content) yield Answer(url, self, author_obj, up_num, content, session=self._session) else: params['offset'] = i * pagesize data['params'] = json.dumps(params) r = self._session.post(Question_Get_More_Answer_URL, data=data, headers=new_header) answer_list = r.json()['msg'] for answer_html in answer_list: yield self._parse_answer_html(answer_html) @property def top_answer(self): """获取排名第一的答案. :return: 排名第一的答案 :rtype: Answer """ for a in self.answers: return a def top_i_answer(self, i): """获取排名某一位的答案. :param int i: 要获取的答案的排名 :return: 答案对象,能直接获取的属性参见answers方法 :rtype: Answer """ for j, a in enumerate(self.answers): if j == i - 1: return a def top_i_answers(self, i): """获取排名在前几位的答案. :param int i: 获取前几个 :return: 答案对象,返回生成器 :rtype: Answer.Iterable """ for j, a in enumerate(self.answers): if j <= i - 1: yield a else: return @property @check_soup('_author') def author(self): """获取问题的提问者. :return: 提问者 :rtype: Author or zhihu.ANONYMOUS """ from .author import Author, ANONYMOUS logs = self._query_logs() author_a = logs[-1].find_all('div')[0].a if author_a.text == '匿名用户': return ANONYMOUS else: url = Zhihu_URL + author_a['href'] return Author(url, name=author_a.text, session=self._session) @property @check_soup('_creation_time') def creation_time(self): """ :return: 问题创建时间 :rtype: datetime.datetime """ logs = self._query_logs() time_string = logs[-1].find('div', class_='zm-item-meta').time[ 'datetime'] return datetime.strptime(time_string, "%Y-%m-%d %H:%M:%S") @property @check_soup('_last_edit_time') def last_edit_time(self): """ :return: 问题最后编辑时间 :rtype: datetime.datetime """ data = {'_xsrf': self.xsrf, 'offset': '1'} res = self._session.post(self.url + 'log', data=data) _, content = res.json()['msg'] soup = BeautifulSoup(content) time_string = soup.find_all('time')[0]['datetime'] return datetime.strptime(time_string, "%Y-%m-%d %H:%M:%S") def _query_logs(self): if self._logs is None: gotten_feed_num = 20 start = '0' offset = 0 api_url = self.url + 'log' logs = None while gotten_feed_num == 20: data = {'_xsrf': self.xsrf, 'offset': offset, 'start': start} res = self._session.post(api_url, data=data) gotten_feed_num, content = res.json()['msg'] offset += gotten_feed_num soup = BeautifulSoup(content) logs = soup.find_all('div', class_='zm-item') start = logs[-1]['id'][8:] if len(logs) > 0 else '0' time.sleep(0.2) # prevent from posting too quickly self._logs = logs return self._logs # noinspection PyAttributeOutsideInit def refresh(self): """刷新 Question object 的属性. 例如回答数增加了, 先调用 ``refresh()`` 再访问 answer_num 属性, 可获得更新后的答案数量. :return: None """ super().refresh() self._html = None self._title = None self._details = None self._answer_num = None self._follower_num = None self._topics = None self._last_edit_time = None self._logs = None @property @check_soup('_deleted') def deleted(self): """问题是否被删除, 被删除了返回 True, 未被删除返回 False :return: True or False """ return self._deleted def _parse_answer_html(self, answer_html): from .author import Author from .answer import Answer soup = BeautifulSoup(answer_html) # 修正各种建议修改的回答…… error_answers = soup.find_all('div', id='answer-status') for each in error_answers: each['class'] = 'zm-editable-content' answer_url = self.url + 'answer/' + soup.div['data-atoken'] author = soup.find('div', class_='zm-item-answer-author-info') upvote_num = int(soup.find( 'div', class_='zm-item-vote-info')['data-votecount']) content = soup.find('div', class_='zm-editable-content') content = answer_content_process(content) a_url, name, motto, photo = parser_author_from_tag(author) author = Author(a_url, name, motto, photo_url=photo, session=self._session) return Answer(answer_url, self, author, upvote_num, content, session=self._session)
class Question(BaseZhihu): '''问题类,请使用``ZhihuClient.question``方法构造对象.''' @class_common_init(re_question_url, trailing_slash=False) def __init__(self, url, title=None, followers_num=None, answer_num=None, creation_time=None, author=None, session=None): '''创建问题类实例. :param str url: 问题url. 现在支持两种 url 1. https://www.zhihu.com/question/qid 2. https://www.zhihu.com/question/qid?sort=created 区别在于,使用第一种,调用 ``question.answers`` 的时候会按投票排序返回答案; 使用第二种, 会按时间排序返回答案, 后提交的答案先返回 :param str title: 问题标题,可选, :param int followers_num: 问题关注人数,可选 :param int answer_num: 问题答案数,可选 :param datetime.datetime creation_time: 问题创建时间,可选 :param Author author: 提问者,可选 :return: 问题对象 :rtype: Question ''' pass @property def url(self): pass @property def id(self): '''获取问题id(网址最后的部分). :return: 问题id :rtype: int ''' pass @property @check_soup('_qid') def qid(self): '''获取问题内部id(用不到就忽视吧) :return: 问题内部id :rtype: int ''' pass @property @check_soup('_xsrf') def xsrf(self): '''获取知乎的反xsrf参数(用不到就忽视吧~) :return: xsrf参数 :rtype: str ''' pass @property @check_soup('_html') def html(self): '''获取页面源码. :return: 页面源码 :rtype: str ''' pass @property @check_soup('_title') def title(self): '''获取问题标题. :return: 问题标题 :rtype: str ''' pass @property @check_soup('_details') def details(self): '''获取问题详细描述,目前实现方法只是直接获取文本,效果不满意……等更新. :return: 问题详细描述 :rtype: str ''' pass @property @check_soup('_answer_num') def answer_num(self): '''获取问题答案数量. :return: 问题答案数量 :rtype: int ''' pass @property @check_soup('_follower_num') def follower_num(self): '''获取问题关注人数. :return: 问题关注人数 :rtype: int ''' pass @property @check_soup('_topics') def topics(self): '''获取问题所属话题. :return: 问题所属话题 :rtype: Topic.Iterable ''' pass @property def followers(self): '''获取关注此问题的用户 :return: 关注此问题的用户 :rtype: Author.Iterable :问题: 要注意若执行过程中另外有人关注,可能造成重复获取到某些用户 ''' pass @property def answers(self): '''获取问题的所有答案. :return: 问题的所有答案,返回生成器 :rtype: Answer.Iterable ''' pass @property def top_answer(self): '''获取排名第一的答案. :return: 排名第一的答案 :rtype: Answer ''' pass def top_i_answer(self, i): '''获取排名某一位的答案. :param int i: 要获取的答案的排名 :return: 答案对象,能直接获取的属性参见answers方法 :rtype: Answer ''' pass def top_i_answers(self, i): '''获取排名在前几位的答案. :param int i: 获取前几个 :return: 答案对象,返回生成器 :rtype: Answer.Iterable ''' pass @property @check_soup('_author') def author(self): '''获取问题的提问者. :return: 提问者 :rtype: Author or zhihu.ANONYMOUS ''' pass @property @check_soup('_creation_time') def creation_time(self): ''' :return: 问题创建时间 :rtype: datetime.datetime ''' pass @property @check_soup('_last_edit_time') def last_edit_time(self): ''' :return: 问题最后编辑时间 :rtype: datetime.datetime ''' pass def _query_logs(self): pass def refresh(self): '''刷新 Question object 的属性. 例如回答数增加了, 先调用 ``refresh()`` 再访问 answer_num 属性, 可获得更新后的答案数量. :return: None ''' pass @property @check_soup('_deleted') def deleted(self): '''问题是否被删除, 被删除了返回 True, 未被删除返回 False :return: True or False ''' pass def _parse_answer_html(self, answer_html): pass
54
21
15
1
10
5
2
0.42
1
10
3
0
23
15
23
28
409
52
252
124
190
106
183
104
153
12
1
4
50
1,557
7sDream/zhihu-py3
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/7sDream_zhihu-py3/zhihu/topic.py
zhihu.topic.Topic
class Topic(BaseZhihu): """答案类,请使用``ZhihuClient.topic``方法构造对象.""" @class_common_init(re_topic_url) def __init__(self, url, name=None, session=None): """创建话题类实例. :param url: 话题url :param name: 话题名称,可选 :return: Topic """ self.url = url self._session = session self._name = name self._id = int(re_topic_url.match(self.url).group(1)) @property def id(self): """获取话题Id(网址最后那串数字) :return: 话题Id :rtype: int """ return self._id @property @check_soup('_xsrf') def xsrf(self): """获取知乎的反xsrf参数(用不到就忽视吧~) :return: xsrf参数 :rtype: str """ return self.soup.find('input', attrs={'name': '_xsrf'})['value'] @property @check_soup('_tid') def tid(self): """话题内部Id,有时候要用到 :return: 话题内部Id :rtype: int """ return int(self.soup.find( 'div', id='zh-topic-desc')['data-resourceid']) @property @check_soup('_name') def name(self): """获取话题名称. :return: 话题名称 :rtype: str """ return self.soup.find('h1').text @property def parents(self): """获取此话题的父话题。 注意:由于没找到有很多父话题的话题来测试, 所以本方法可能再某些时候出现问题,请不吝反馈。 :return: 此话题的父话题,返回生成器 :rtype: Topic.Iterable """ self._make_soup() parent_topic_tag = self.soup.find('div', class_='parent-topic') if parent_topic_tag is None: yield [] else: for topic_tag in parent_topic_tag.find_all('a'): yield Topic(Zhihu_URL + topic_tag['href'], topic_tag.text.strip(), session=self._session) @property def children(self): """获取此话题的子话题 :return: 此话题的子话题, 返回生成器 :rtype: Topic.Iterable """ self._make_soup() child_topic_tag = self.soup.find('div', class_='child-topic') if child_topic_tag is None: return [] elif '共有' not in child_topic_tag.contents[-2].text: for topic_tag in child_topic_tag.div.find_all('a'): yield Topic(Zhihu_URL + topic_tag['href'], topic_tag.text.strip(), session=self._session) else: flag = 'load' child = '' data = {'_xsrf': self.xsrf} params = { 'parent': self.id } while flag == 'load': params['child'] = child res = self._session.post(Topic_Get_Children_Url, params=params, data=data) j = map(lambda x: x[0], res.json()['msg'][1]) *topics, last = j for topic in topics: yield Topic(Zhihu_URL + '/topic/' + topic[2], topic[1], session=self._session) flag = last[0] child = last[2] if flag == 'topic': yield Topic(Zhihu_URL + '/topic/' + last[2], last[1], session=self._session) @property @check_soup('_follower_num') def follower_num(self): """获取话题关注人数. :return: 关注人数 :rtype: int """ follower_num_block = self.soup.find( 'div', class_='zm-topic-side-followers-info') # 无人关注时 找不到对应block,直接返回0 (感谢知乎用户 段晓晨 提出此问题) if follower_num_block.strong is None: return 0 return int(follower_num_block.strong.text) @property def followers(self): """获取话题关注者 :return: 话题关注者,返回生成器 :rtype: Author.Iterable """ from .author import Author, ANONYMOUS self._make_soup() gotten_data_num = 20 data = { '_xsrf': self.xsrf, 'start': '', 'offset': 0 } while gotten_data_num == 20: res = self._session.post( Topic_Get_More_Follower_Url.format(self.id), data=data) j = res.json()['msg'] gotten_data_num = j[0] data['offset'] += gotten_data_num soup = BeautifulSoup(j[1]) divs = soup.find_all('div', class_='zm-person-item') for div in divs: h2 = div.h2 url = Zhihu_URL + h2.a['href'] name = h2.a.text motto = h2.parent.div.text.strip() try: yield Author(url, name, motto, session=self._session) except ValueError: # invalid url yield ANONYMOUS data['start'] = int(re_get_number.match(divs[-1]['id']).group(1)) @property @check_soup('_photo_url') def photo_url(self): """获取话题头像图片地址. :return: 话题头像url :rtype: str """ img = self.soup.find('a', id='zh-avartar-edit-form').img['src'] return img.replace('_m', '_r') @property @check_soup('_description') def description(self): """获取话题描述信息. :return: 话题描述信息 :rtype: str """ desc = self.soup.find('div', class_='zm-editable-content').text return desc @property def top_authors(self): """获取最佳回答者 :return: 此话题下最佳回答者,一般来说是5个,要不就没有,返回生成器 :rtype: Author.Iterable """ from .author import Author, ANONYMOUS self._make_soup() t = self.soup.find('div', id='zh-topic-top-answerer') if t is None: return for d in t.find_all('div', class_='zm-topic-side-person-item-content'): url = Zhihu_URL + d.a['href'] name = d.a.text motto = d.find('span', class_='bio')['title'] try: yield Author(url, name, motto, session=self._session) except ValueError: # invalid url yield ANONYMOUS @property def top_answers(self): """获取话题下的精华答案. :return: 话题下的精华答案,返回生成器. :rtype: Answer.Iterable """ from .question import Question from .answer import Answer from .author import Author, ANONYMOUS top_answers_url = Topic_Top_Answers_Url.format(self.id) params = {'page': 1} while True: # 超出50页直接返回 if params['page'] > 50: return res = self._session.get(top_answers_url, params=params) params['page'] += 1 soup = BeautifulSoup(res.content) # 不够50页,来到错误页面 返回 if soup.find('div', class_='error') is not None: return questions = soup.find_all('a', class_='question_link') answers = soup.find_all('a', class_='answer-date-link') authors = soup.find_all('div', class_='zm-item-answer-author-info') upvotes = soup.find_all('a', class_='zm-item-vote-count') for ans, up, q, au in zip(answers, upvotes, questions, authors): answer_url = Zhihu_URL + ans['href'] question_url = Zhihu_URL + q['href'] question_title = q.text.strip() upvote = up.text if upvote.isdigit(): upvote = int(upvote) else: upvote = None question = Question(question_url, question_title, session=self._session) if au.a is None: author = ANONYMOUS else: author_url = Zhihu_URL + au.a['href'] author_name = au.a.text author_motto = au.strong['title'] if au.strong else '' author = Author(author_url, author_name, author_motto, session=self._session) yield Answer(answer_url, question, author, upvote, session=self._session) @property def questions(self): """获取话题下的所有问题(按时间降序排列) :return: 话题下所有问题,返回生成器 :rtype: Question.Iterable """ from .question import Question question_url = Topic_Questions_Url.format(self.id) params = {'page': 1} older_time_stamp = int(time.time()) * 1000 while True: res = self._session.get(question_url, params=params) soup = BeautifulSoup(res.content) if soup.find('div', class_='error') is not None: return questions = soup.find_all('div', class_='question-item') questions = list(filter( lambda x: int(x.h2.span['data-timestamp']) < older_time_stamp, questions)) for qu_div in questions: url = Zhihu_URL + qu_div.h2.a['href'] title = qu_div.h2.a.text.strip() creation_time = datetime.fromtimestamp( int(qu_div.h2.span['data-timestamp']) // 1000) yield Question(url, title, creation_time=creation_time, session=self._session) older_time_stamp = int(questions[-1].h2.span['data-timestamp']) params['page'] += 1 @property def unanswered_questions(self): """获取话题下的等待回答的问题 什么是「等待回答」的问题:https://www.zhihu.com/question/40470324 :return: 话题下等待回答的问题,返回生成器 :rtype: Question.Iterable """ from .question import Question question_url = Topic_Unanswered_Question_Url.format(self.id) params = {'page': 1} while True: res = self._session.get(question_url, params=params) soup = BeautifulSoup(res.content) if soup.find('div', class_='error') is not None: return questions = soup.find_all('div', class_='question-item') for qu_div in questions: url = Zhihu_URL + qu_div.h2.a['href'] title = qu_div.h2.a.text.strip() yield Question(url, title, session=self._session) params['page'] += 1 @property def answers(self): """获取话题下所有答案(按时间降序排列) :return: 话题下所有答案,返回生成器 :rtype: Answer.Iterable """ from .question import Question from .answer import Answer from .author import Author, ANONYMOUS newest_url = Topic_Newest_Url.format(self.id) params = {'start': 0, '_xsrf': self.xsrf} res = self._session.get(newest_url) soup = BeautifulSoup(res.content) while True: divs = soup.find_all('div', class_='folding') # 如果话题下无答案,则直接返回 if len(divs) == 0: return last_score = divs[-1]['data-score'] for div in divs: q = div.find('a', class_="question_link") question_url = Zhihu_URL + q['href'] question_title = q.text.strip() question = Question(question_url, question_title, session=self._session) ans = div.find('a', class_='answer-date-link') answer_url = Zhihu_URL + ans['href'] upvote = div.find('a', class_='zm-item-vote-count').text if upvote.isdigit(): upvote = int(upvote) else: upvote = None au = div.find('div', class_='zm-item-answer-author-info') if au.a is None: author = ANONYMOUS else: author_url = Zhihu_URL + au.a['href'] author_name = au.a.text author_motto = au.strong['title'] if au.strong else '' author = Author(author_url, author_name, author_motto, session=self._session) yield Answer(answer_url, question, author, upvote, session=self._session) params['offset'] = last_score res = self._session.post(newest_url, data=params) gotten_feed_num = res.json()['msg'][0] # 如果得到内容数量为0则返回 if gotten_feed_num == 0: return soup = BeautifulSoup(res.json()['msg'][1]) @property def hot_questions(self): """获取话题下热门的问题 :return: 话题下的热门动态中的问题,按热门度顺序返回生成器 :rtype: Question.Iterable """ from .question import Question hot_questions_url = Topic_Hot_Questions_Url.format(self.id) params = {'start': 0, '_xsrf': self.xsrf} res = self._session.get(hot_questions_url) soup = BeautifulSoup(res.content) while True: questions_duplicate = soup.find_all('a', class_='question_link') # 如果话题下无问题,则直接返回 if len(questions_duplicate) == 0: return # 去除重复的问题 questions = list(set(questions_duplicate)) questions.sort(key=self._get_score, reverse=True) last_score = soup.find_all( 'div', class_='feed-item')[-1]['data-score'] for q in questions: question_url = Zhihu_URL + q['href'] question_title = q.text.strip() question = Question(question_url, question_title, session=self._session) yield question params['offset'] = last_score res = self._session.post(hot_questions_url, data=params) gotten_feed_num = res.json()['msg'][0] # 如果得到问题数量为0则返回 if gotten_feed_num == 0: return soup = BeautifulSoup(res.json()['msg'][1]) @property def hot_answers(self): """获取话题下热门的回答 :return: 话题下的热门动态中的回答,按热门度顺序返回生成器 :rtype: Question.Iterable """ from .question import Question from .author import Author from .answer import Answer hot_questions_url = Topic_Hot_Questions_Url.format(self.id) params = {'start': 0, '_xsrf': self.xsrf} res = self._session.get(hot_questions_url) soup = BeautifulSoup(res.content) while True: answers_div = soup.find_all('div', class_='feed-item') last_score = answers_div[-1]['data-score'] for div in answers_div: # 没有 text area 的情况是:答案被和谐。 if not div.textarea: continue question_url = Zhihu_URL + div.h2.a['href'] question_title = div.h2.a.text.strip() question = Question(question_url, question_title, session=self._session) author_link = div.find('a', class_='author-link') if not author_link: author_url = None author_name = '匿名用户' author_motto = '' else: author_url = Zhihu_URL + author_link['href'] author_name = author_link.text author_motto_span = div.find('span', class_='bio') author_motto = author_motto_span['title'] \ if author_motto_span else '' author = Author(author_url, author_name, author_motto, session=self._session) body = div.find('div', class_='zm-item-rich-text') answer_url = Zhihu_URL + body['data-entry-url'] upvote_num = int(div.find( 'div', class_='zm-item-vote-info')['data-votecount']) yield Answer(answer_url, question, author, upvote_num, session=self._session) params['offset'] = last_score res = self._session.post(hot_questions_url, data=params) gotten_feed_num = res.json()['msg'][0] # 如果得到问题数量为0则返回 if gotten_feed_num == 0: return soup = BeautifulSoup(res.json()['msg'][1]) @staticmethod def _get_score(tag): h2 = tag.parent div = h2.parent try: _ = h2['class'] return div['data-score'] except KeyError: return div.parent.parent['data-score']
class Topic(BaseZhihu): '''答案类,请使用``ZhihuClient.topic``方法构造对象.''' @class_common_init(re_topic_url) def __init__(self, url, name=None, session=None): '''创建话题类实例. :param url: 话题url :param name: 话题名称,可选 :return: Topic ''' pass @property def id(self): '''获取话题Id(网址最后那串数字) :return: 话题Id :rtype: int ''' pass @property @check_soup('_xsrf') def xsrf(self): '''获取知乎的反xsrf参数(用不到就忽视吧~) :return: xsrf参数 :rtype: str ''' pass @property @check_soup('_tid') def tid(self): '''话题内部Id,有时候要用到 :return: 话题内部Id :rtype: int ''' pass @property @check_soup('_name') def name(self): '''获取话题名称. :return: 话题名称 :rtype: str ''' pass @property def parents(self): '''获取此话题的父话题。 注意:由于没找到有很多父话题的话题来测试, 所以本方法可能再某些时候出现问题,请不吝反馈。 :return: 此话题的父话题,返回生成器 :rtype: Topic.Iterable ''' pass @property def children(self): '''获取此话题的子话题 :return: 此话题的子话题, 返回生成器 :rtype: Topic.Iterable ''' pass @property @check_soup('_follower_num') def follower_num(self): '''获取话题关注人数. :return: 关注人数 :rtype: int ''' pass @property def followers(self): '''获取话题关注者 :return: 话题关注者,返回生成器 :rtype: Author.Iterable ''' pass @property @check_soup('_photo_url') def photo_url(self): '''获取话题头像图片地址. :return: 话题头像url :rtype: str ''' pass @property @check_soup('_description') def description(self): '''获取话题描述信息. :return: 话题描述信息 :rtype: str ''' pass @property def top_authors(self): '''获取最佳回答者 :return: 此话题下最佳回答者,一般来说是5个,要不就没有,返回生成器 :rtype: Author.Iterable ''' pass @property def top_answers(self): '''获取话题下的精华答案. :return: 话题下的精华答案,返回生成器. :rtype: Answer.Iterable ''' pass @property def questions(self): '''获取话题下的所有问题(按时间降序排列) :return: 话题下所有问题,返回生成器 :rtype: Question.Iterable ''' pass @property def unanswered_questions(self): '''获取话题下的等待回答的问题 什么是「等待回答」的问题:https://www.zhihu.com/question/40470324 :return: 话题下等待回答的问题,返回生成器 :rtype: Question.Iterable ''' pass @property def answers(self): '''获取话题下所有答案(按时间降序排列) :return: 话题下所有答案,返回生成器 :rtype: Answer.Iterable ''' pass @property def hot_questions(self): '''获取话题下热门的问题 :return: 话题下的热门动态中的问题,按热门度顺序返回生成器 :rtype: Question.Iterable ''' pass @property def hot_answers(self): '''获取话题下热门的回答 :return: 话题下的热门动态中的回答,按热门度顺序返回生成器 :rtype: Question.Iterable ''' pass @staticmethod def _get_score(tag): pass
45
19
22
1
16
5
3
0.27
1
12
3
0
18
4
19
24
466
48
331
179
272
89
265
160
231
8
1
3
65
1,558
7sDream/zhihu-py3
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/7sDream_zhihu-py3/zhihu/answer.py
zhihu.answer.Answer
class Answer(BaseZhihu): """答案类,请使用``ZhihuClient.answer``方法构造对象.""" @class_common_init(re_ans_url) def __init__(self, url, question=None, author=None, upvote_num=None, content=None, session=None): """创建答案类实例. :param str url: 答案url :param Question question: 答案所在的问题对象,可选 :param Author author: 答案回答者对象,可选 :param int upvote_num: 答案赞同数量,可选 :param str content: 答案内容,可选 :param Session session: 使用的网络会话,为空则使用新会话 :return: 答案对象 :rtype: Answer """ self.url = url self._session = session self._question = question self._author = author self._upvote_num = upvote_num self._content = content self._deleted = None @property def id(self): """答案的id :return: 答案id :rtype: int """ return int(re.match(r'.*/(\d+)/$', self.url).group(1)) @property @check_soup('_xsrf') def xsrf(self): """获取知乎的反xsrf参数(用不到就忽视吧~) :return: xsrf参数 :rtype: str """ return self.soup.find('input', attrs={'name': '_xsrf'})['value'] @property @check_soup('_aid') def aid(self): """获取答案的内部id,某些POST操作需要此参数 :return: 答案内部id :rtype: str """ return int(self.soup.find('div', class_='zm-item-answer')['data-aid']) @property @check_soup('_html') def html(self): """获取网页源码 :return: 网页源码 :rtype: str """ return self.soup.prettify() @property @check_soup('_author') def author(self): """获取答案作者. :return: 答案作者 :rtype: Author """ from .author import Author author = self.soup.find('div', class_='zm-item-answer-author-info') url, name, motto, photo = parser_author_from_tag(author) if name == '匿名用户': return ANONYMOUS else: return Author(url, name, motto, photo_url=photo, session=self._session) @property @check_soup('_question') def question(self): """获取答案所在问题. :return: 答案所在问题 :rtype: Question """ from .question import Question question_link = self.soup.find( "h2", class_="zm-item-title").a url = Zhihu_URL + question_link["href"] title = question_link.text.strip() followers_num = int(self.soup.find( 'div', class_='zh-question-followers-sidebar').div.a.strong.text) answers_num = int(re_get_number.match(self.soup.find( 'div', class_='zh-answers-title').h3.a.text).group(1)) return Question(url, title, followers_num, answers_num, session=self._session) @property @check_soup('_upvote_num') def upvote_num(self): """获取答案赞同数量. :return: 答案赞同数量 :rtype: int """ return int(self.soup.find( 'div', class_='zm-item-vote-info')['data-votecount']) @property def upvoters(self): """获取答案点赞用户,返回生成器. :return: 点赞用户 :rtype: Author.Iterable """ self._make_soup() next_req = '/answer/' + str(self.aid) + '/voters_profile' while next_req != '': data = self._session.get(Zhihu_URL + next_req).json() next_req = data['paging']['next'] for html in data['payload']: soup = BeautifulSoup(html) yield self._parse_author_soup(soup) @property @check_soup('_content') def content(self): """以处理过的Html代码形式返回答案内容. :return: 答案内容 :rtype: str """ answer_wrap = self.soup.find('div', id='zh-question-answer-wrap') content = answer_wrap.find('div', class_='zm-editable-content') content = answer_content_process(content) return content @property @check_soup('_creation_time') def creation_time(self): """获取答案创建时间 :return: 答案创建时间 :rtype: datetime.datetime """ return datetime.fromtimestamp(int(self.soup.find( 'div', class_='zm-item-answer')['data-created'])) @property @check_soup('_collect_num') def collect_num(self): """获取答案收藏数 :return: 答案收藏数量 :rtype: int """ element = self.soup.find("a", { "data-za-a": "click_answer_collected_count" }) if element is None: return 0 else: return int(element.get_text()) @property def collections(self): """获取包含该答案的收藏夹 :return: 包含该答案的收藏夹 :rtype: Collection.Iterable collect_num 未必等于 len(collections),比如: https://www.zhihu.com/question/20064699/answer/13855720 显示被收藏 38 次,但只有 30 个收藏夹 """ import time gotten_feed_num = 20 offset = 0 data = { 'method': 'next', '_xsrf': self.xsrf } while gotten_feed_num >= 10: data['params'] = "{\"answer_url\": %d,\"offset\": %d}" % ( self.id, offset) res = self._session.post(url=Get_Collection_Url, data=data) gotten_feed_num = len(res.json()['msg']) offset += gotten_feed_num soup = BeautifulSoup(''.join(res.json()['msg'])) for zm_item in soup.find_all('div', class_='zm-item'): url = Zhihu_URL + zm_item.h2.a['href'] name = zm_item.h2.a.text links = zm_item.div.find_all('a') owner = Author(links[0]['href'], session=self._session) follower_num = int(links[1].text.split()[0]) yield Collection(url, owner=owner, name=name, follower_num=follower_num, session=self._session) time.sleep(0.2) # prevent from posting too quickly def save(self, filepath=None, filename=None, mode="html"): """保存答案为Html文档或markdown文档. :param str filepath: 要保存的文件所在的目录, 不填为当前目录下以问题标题命名的目录, 设为"."则为当前目录。 :param str filename: 要保存的文件名, 不填则默认为 所在问题标题 - 答主名.html/md。 如果文件已存在,自动在后面加上数字区分。 **自定义文件名时请不要输入后缀 .html 或 .md。** :param str mode: 保存类型,可选 `html` 、 `markdown` 、 `md` 。 :return: 无 :rtype: None """ if mode not in ["html", "md", "markdown"]: raise ValueError("`mode` must be 'html', 'markdown' or 'md'," " got {0}".format(mode)) file = get_path(filepath, filename, mode, self.question.title, self.question.title + '-' + self.author.name) with open(file, 'wb') as f: if mode == "html": f.write(self.content.encode('utf-8')) else: import html2text h2t = html2text.HTML2Text() h2t.body_width = 0 f.write(h2t.handle(self.content).encode('utf-8')) def _parse_author_soup(self, soup): from .author import Author, ANONYMOUS author_tag = soup.find('div', class_='body') if author_tag.string is None: author_name = author_tag.div.a['title'] author_url = author_tag.div.a['href'] author_motto = author_tag.div.span.text photo_url = PROTOCOL + soup.a.img['src'].replace('_m', '_r') numbers_tag = soup.find_all('li') numbers = [int(re_get_number.match(x.get_text()).group(1)) for x in numbers_tag] # noinspection PyTypeChecker return Author(author_url, author_name, author_motto, None, numbers[2], numbers[3], numbers[0], numbers[1], photo_url, session=self._session) else: return ANONYMOUS @property @check_soup('_comment_num') def comment_num(self): """ :return: 答案下评论的数量 :rtype: int """ comment = self.soup.select_one("div.answer-actions a.toggle-comment") comment_num_string = comment.text number = comment_num_string.split()[0] return int(number) if number.isdigit() else 0 @property def comments(self): """获取答案下的所有评论. :return: 答案下的所有评论,返回生成器 :rtype: Comments.Iterable """ import math from .author import Author, ANONYMOUS from .comment import Comment api_url = Get_Answer_Comment_URL.format(self.aid) page = pages = 1 while page <= pages: res = self._session.get(api_url + '?page=' + str(page)) if page == 1: total = int(res.json()['paging']['totalCount']) if total == 0: return pages = math.ceil(total / 30) page += 1 comment_items = res.json()['data'] for comment_item in comment_items: comment_id = comment_item['id'] content = comment_item['content'] upvote_num = comment_item['likesCount'] time_string = comment_item['createdTime'][:19] time = datetime.strptime(time_string, "%Y-%m-%dT%H:%M:%S") if comment_item['author'].get('url') is not None: a_url = comment_item['author']['url'] a_name = comment_item['author']['name'] photo_url_tmp = comment_item['author']['avatar']['template'] photo_url_id = comment_item['author']['avatar']['id'] a_photo_url = photo_url_tmp.replace( '{id}', photo_url_id).replace('_{size}', '') author_obj = Author(a_url, a_name, photo_url=a_photo_url, session=self._session) else: author_obj = ANONYMOUS yield Comment(comment_id, self, author_obj, upvote_num, content, time) @property def latest_comments(self): """获取答案下的所有评论。较新的评论先返回。 使用该方法比 ``reversed(list(answer.comments))`` 效率高 因为现在靠后的热门评论会被挪到前面,所以返回的评论未必严格满足时间先后关系 :return: 答案下的所有评论,返回生成器 :rtype: Comments.Iterable """ import math from .author import Author, ANONYMOUS from .comment import Comment if self.comment_num == 0: return pages = math.ceil(self.comment_num / 30) api_url = Get_Answer_Comment_URL.format(self.aid) for page in range(pages, 0, -1): res = self._session.get(api_url + '?page=' + str(page)) comment_items = res.json()['data'] for comment_item in reversed(comment_items): comment_id = comment_item['id'] content = comment_item['content'] upvote_num = comment_item['likesCount'] time_string = comment_item['createdTime'][:19] time = datetime.strptime(time_string, "%Y-%m-%dT%H:%M:%S") if comment_item['author'].get('url') != None: a_url = comment_item['author']['url'] a_name = comment_item['author']['name'] photo_url_tmp = comment_item['author']['avatar']['template'] photo_url_id = comment_item['author']['avatar']['id'] a_photo_url = photo_url_tmp.replace( '{id}', photo_url_id).replace('_{size}', '') author_obj = Author(a_url, a_name, photo_url=a_photo_url, session=self._session) else: author_obj = ANONYMOUS yield Comment(comment_id, self, author_obj, upvote_num, content, time) def refresh(self): """刷新 Answer object 的属性. 例如赞同数增加了, 先调用 ``refresh()`` 再访问 upvote_num属性, 可获得更新后的赞同数. :return: None """ super().refresh() self._html = None self._upvote_num = None self._content = None self._collect_num = None self._comment_num = None @property @check_soup('_deleted') def deleted(self): """答案是否被删除, 被删除了返回 True, 为被删除返回 False :return: True or False """ return self._deleted
class Answer(BaseZhihu): '''答案类,请使用``ZhihuClient.answer``方法构造对象.''' @class_common_init(re_ans_url) def __init__(self, url, question=None, author=None, upvote_num=None, content=None, session=None): '''创建答案类实例. :param str url: 答案url :param Question question: 答案所在的问题对象,可选 :param Author author: 答案回答者对象,可选 :param int upvote_num: 答案赞同数量,可选 :param str content: 答案内容,可选 :param Session session: 使用的网络会话,为空则使用新会话 :return: 答案对象 :rtype: Answer ''' pass @property def id(self): '''答案的id :return: 答案id :rtype: int ''' pass @property @check_soup('_xsrf') def xsrf(self): '''获取知乎的反xsrf参数(用不到就忽视吧~) :return: xsrf参数 :rtype: str ''' pass @property @check_soup('_aid') def aid(self): '''获取答案的内部id,某些POST操作需要此参数 :return: 答案内部id :rtype: str ''' pass @property @check_soup('_html') def html(self): '''获取网页源码 :return: 网页源码 :rtype: str ''' pass @property @check_soup('_author') def author(self): '''获取答案作者. :return: 答案作者 :rtype: Author ''' pass @property @check_soup('_question') def question(self): '''获取答案所在问题. :return: 答案所在问题 :rtype: Question ''' pass @property @check_soup('_upvote_num') def upvote_num(self): '''获取答案赞同数量. :return: 答案赞同数量 :rtype: int ''' pass @property def upvoters(self): '''获取答案点赞用户,返回生成器. :return: 点赞用户 :rtype: Author.Iterable ''' pass @property @check_soup('_content') def content(self): '''以处理过的Html代码形式返回答案内容. :return: 答案内容 :rtype: str ''' pass @property @check_soup('_creation_time') def creation_time(self): '''获取答案创建时间 :return: 答案创建时间 :rtype: datetime.datetime ''' pass @property @check_soup('_collect_num') def collect_num(self): '''获取答案收藏数 :return: 答案收藏数量 :rtype: int ''' pass @property def collections(self): '''获取包含该答案的收藏夹 :return: 包含该答案的收藏夹 :rtype: Collection.Iterable collect_num 未必等于 len(collections),比如: https://www.zhihu.com/question/20064699/answer/13855720 显示被收藏 38 次,但只有 30 个收藏夹 ''' pass def save(self, filepath=None, filename=None, mode="html"): '''保存答案为Html文档或markdown文档. :param str filepath: 要保存的文件所在的目录, 不填为当前目录下以问题标题命名的目录, 设为"."则为当前目录。 :param str filename: 要保存的文件名, 不填则默认为 所在问题标题 - 答主名.html/md。 如果文件已存在,自动在后面加上数字区分。 **自定义文件名时请不要输入后缀 .html 或 .md。** :param str mode: 保存类型,可选 `html` 、 `markdown` 、 `md` 。 :return: 无 :rtype: None ''' pass def _parse_author_soup(self, soup): pass @property @check_soup('_comment_num') def comment_num(self): ''' :return: 答案下评论的数量 :rtype: int ''' pass @property def comments(self): '''获取答案下的所有评论. :return: 答案下的所有评论,返回生成器 :rtype: Comments.Iterable ''' pass @property def latest_comments(self): '''获取答案下的所有评论。较新的评论先返回。 使用该方法比 ``reversed(list(answer.comments))`` 效率高 因为现在靠后的热门评论会被挪到前面,所以返回的评论未必严格满足时间先后关系 :return: 答案下的所有评论,返回生成器 :rtype: Comments.Iterable ''' pass def refresh(self): '''刷新 Answer object 的属性. 例如赞同数增加了, 先调用 ``refresh()`` 再访问 upvote_num属性, 可获得更新后的赞同数. :return: None ''' pass @property @check_soup('_deleted') def deleted(self): '''答案是否被删除, 被删除了返回 True, 为被删除返回 False :return: True or False ''' pass
49
20
16
1
10
5
2
0.43
1
11
4
0
20
10
20
25
370
49
225
132
164
97
167
113
135
6
1
3
39
1,559
7sDream/zhihu-py3
7sDream_zhihu-py3/test/test_common.py
test_common.CommonTest
class CommonTest(unittest.TestCase): def test_question_url(self): url = 'https://www.zhihu.com/question/26901243?sort=created' obj = re.match(re_question_url, url) assert obj.group() == url url = 'https://www.zhihu.com/question/26901243' obj = re.match(re_question_url, url) assert obj.group() == url url = 'https://www.zhihu.com/question/26901243/' obj = re.match(re_question_url, url) assert obj.group() == url url = 'https://www.zhihu.com/question/26901243?sort=createdx' obj = re.match(re_question_url, url) assert obj is None url = 'https://www.zhihu.com/question/26901243sort=created' obj = re.match(re_question_url, url) assert obj is None url = 'https://www.zhihu.com/question/26901243/?sort=created' obj = re.match(re_question_url, url) assert obj is None url = 'https://www.zhihu.com/question/26901243?/sort=created' obj = re.match(re_question_url, url) assert obj is None
class CommonTest(unittest.TestCase): def test_question_url(self): pass
2
0
28
6
22
0
1
0
1
0
0
0
1
0
1
73
30
7
23
4
21
0
23
4
21
1
2
0
1
1,560
7sDream/zhihu-py3
7sDream_zhihu-py3/zhihu/author.py
zhihu.author._Anonymous
class _Anonymous: def __init__(self): self.name = "匿名用户" self.url = ''
class _Anonymous: def __init__(self): pass
2
0
3
0
3
0
1
0
0
0
0
0
1
2
1
1
4
0
4
4
2
0
4
4
2
1
0
0
1
1,561
7sDream/zhihu-py3
7sDream_zhihu-py3/test/test_question.py
test_question.QuestionTest
class QuestionTest(unittest.TestCase): @classmethod def setUpClass(cls): url = 'http://www.zhihu.com/question/24825703' file_path = os.path.join(TEST_DATA_PATH, 'question.html') with open(file_path, 'rb') as f: html = f.read() soup = BeautifulSoup(html) cls.question = Question(url) cls.question._session = None cls.question.soup = soup cls.expected = {'id': 24825703, 'qid': 2112271, 'xsrf': 'cfd489623d34ca03adfdc125368c6426', 'html': soup.prettify(), 'title': '关系亲密的人之间要说「谢谢」吗?', 'details': description, 'answer_num': 621, 'follower_num': 4427, 'top_answer_id': 39753456, 'top_answer_author_name': '芝士就是力量', 'top_answer_upvote_num': 97, 'top_50_ans_id': 31003847, 'top_50_ans_author_name': '圭多达莱佐', 'top_50_ans_upvote_num': 31, 'more_ans_id': 39958704, 'more_ans_author_name': '柳蜻蜓', 'more_ans_upvote_num': 1, 'topics': ['心理学', '恋爱', '社会', '礼仪', '亲密关系'], } more_ans_file_path = os.path.join(TEST_DATA_PATH, 'question_more_answer.html') with open(more_ans_file_path, 'rb') as f: cls.more_ans_html = f.read() def test_id(self): self.assertEqual(self.expected['id'], self.question.id) def test_qid(self): self.assertEqual(self.expected['qid'], self.question.qid) def test_xsrf(self): self.assertEqual(self.expected['xsrf'], self.question.xsrf) def test_html(self): self.assertEqual(self.expected['html'], self.question.html) def test_title(self): self.assertEqual(self.expected['title'], self.question.title) def test_details(self): self.assertEqual(self.expected['details'], self.question.details) def test_answer_num(self): self.assertEqual(self.expected['answer_num'], self.question.answer_num) def test_follower_num(self): self.assertEqual(self.expected['follower_num'], self.question.follower_num) def test_topics(self): self.assertEqual(self.expected['topics'], self.question.topics) def test_top_answer(self): answer = self.question.top_answer self.assertEqual(self.expected['top_answer_id'], answer.id) self.assertEqual(self.expected['top_answer_author_name'], answer.author.name) self.assertEqual(self.expected['top_answer_upvote_num'], answer.upvote_num) def test_top_i_answer(self): answer = self.question.top_i_answer(50) self.assertEqual(self.expected['top_50_ans_id'], answer.id) self.assertEqual(self.expected['top_50_ans_author_name'], answer.author.name) self.assertEqual(self.expected['top_50_ans_upvote_num'], answer.upvote_num) def test_parse_answer_html(self): answer = self.question._parse_answer_html(self.more_ans_html) self.assertEqual(self.expected['more_ans_id'], answer.id) self.assertEqual(self.expected['more_ans_author_name'], answer.author.name) self.assertEqual(self.expected['more_ans_upvote_num'], answer.upvote_num) def test_top_i_answers(self): answers = [a for a in self.question.top_i_answers(1)] answer = answers[0] self.assertEqual(self.expected['top_answer_id'], answer.id) self.assertEqual(self.expected['top_answer_author_name'], answer.author.name) self.assertEqual(self.expected['top_answer_upvote_num'], answer.upvote_num)
class QuestionTest(unittest.TestCase): @classmethod def setUpClass(cls): pass def test_id(self): pass def test_qid(self): pass def test_xsrf(self): pass def test_html(self): pass def test_title(self): pass def test_details(self): pass def test_answer_num(self): pass def test_follower_num(self): pass def test_topics(self): pass def test_top_answer(self): pass def test_top_i_answer(self): pass def test_parse_answer_html(self): pass def test_top_i_answers(self): pass
16
0
6
0
5
0
1
0
1
0
0
0
13
0
14
86
93
15
78
27
62
0
53
25
38
1
2
1
14
1,562
7sDream/zhihu-py3
7sDream_zhihu-py3/zhihu/comment.py
zhihu.comment.Comment
class Comment: """评论类,一般不直接使用,而是作为``Answer.comments``迭代器的返回类型.""" def __init__(self, cid, answer, author, upvote_num, content, time, group_id=None): """创建评论类实例. :param int cid: 评论ID :param int group_id: 评论所在的组ID :param Answer answer: 评论所在的答案对象 :param Author author: 评论的作者对象 :param int upvote_num: 评论赞同数量 :param str content: 评论内容 :param datetime.datetime creation_time: 评论发表时间 :return: 评论对象 :rtype: Comment """ self.cid = cid self.answer = answer self.author = author self.upvote_num = upvote_num self.content = content self.creation_time = time self._group_id = group_id
class Comment: '''评论类,一般不直接使用,而是作为``Answer.comments``迭代器的返回类型.''' def __init__(self, cid, answer, author, upvote_num, content, time, group_id=None): '''创建评论类实例. :param int cid: 评论ID :param int group_id: 评论所在的组ID :param Answer answer: 评论所在的答案对象 :param Author author: 评论的作者对象 :param int upvote_num: 评论赞同数量 :param str content: 评论内容 :param datetime.datetime creation_time: 评论发表时间 :return: 评论对象 :rtype: Comment ''' pass
2
2
22
2
9
11
1
1.2
0
0
0
0
1
7
1
1
26
4
10
10
7
12
9
9
7
1
0
0
1
1,563
7sDream/zhihu-py3
7sDream_zhihu-py3/test/test_post.py
test_post.ColumnTest
class ColumnTest(unittest.TestCase): @classmethod def setUpClass(cls): url = 'http://zhuanlan.zhihu.com/xiepanda/20202275' post_path = os.path.join(TEST_DATA_PATH, 'column_post.json') with open(post_path, 'r') as f: post_json = json.load(f) post_saved_path = os.path.join(TEST_DATA_PATH, 'post.md') with open(post_saved_path, 'rb') as f: cls.post_saved = f.read() cls.post = Post(url) cls.post.soup = post_json cls.expected = {'column_in_name': 'xiepanda', 'slug': 20202275, 'column_name': '谢熊猫出没注意', 'author_name': '谢熊猫君', 'author_id': 'xiepanda', 'title': '为了做一个称职的吃货,他决定连着吃一百天转基因食物', 'upvote_num': 963, 'comment_num': 199} def test_column_in_name(self): self.assertEqual(self.expected['column_in_name'], self.post.column_in_name) def test_slug(self): self.assertEqual(self.expected['slug'], self.post.slug) def test_author(self): self.assertEqual(self.expected['author_name'], self.post.author.name) self.assertEqual(self.expected['author_id'], self.post.author.id) def test_title(self): self.assertEqual(self.expected['title'], self.post.title) def test_upvote_num(self): self.assertEqual(self.expected['upvote_num'], self.post.upvote_num) def test_comment_num(self): self.assertEqual(self.expected['comment_num'], self.post.comment_num) def test_save(self): save_name = 'post_save' self.post.save(filepath=TEST_DATA_PATH, filename=save_name) post_saved_path = os.path.join(TEST_DATA_PATH, save_name + '.md') with open(post_saved_path, 'rb') as f: post_saved = f.read() os.remove(post_saved_path) self.assertEqual(self.post_saved, post_saved)
class ColumnTest(unittest.TestCase): @classmethod def setUpClass(cls): pass def test_column_in_name(self): pass def test_slug(self): pass def test_author(self): pass def test_title(self): pass def test_upvote_num(self): pass def test_comment_num(self): pass def test_save(self): pass
10
0
5
0
5
0
1
0
1
0
0
0
7
0
8
80
49
10
39
19
29
0
33
16
24
1
2
1
8
1,564
7sDream/zhihu-py3
7sDream_zhihu-py3/zhihu/collection.py
zhihu.collection.CollectActivity
class CollectActivity: """收藏夹操作, 请使用``Collection.logs``构造对象.""" def __init__(self, type, time, owner, collection, answer=None): """创建收藏夹操作类实例 :param acttype.CollectActType type: 操作类型 :param datetime.datetime time: 进行操作的时间 :param Author owner: 收藏夹的拥有者 :param Collection collection: 所属收藏夹 :param Answer answer: 收藏的答案,可选 :return: CollectActivity """ self._type = type self._time = time self._owner = owner self._collection = collection self._answer = answer @property def type(self): """ :return: 收藏夹操作类型, 具体参见 :class:`.CollectActType` :rtype: :class:`.CollectActType` """ return self._type @property def answer(self): """ :return: 添加或删除收藏的答案, 若是创建收藏夹操作返回 None :rtype: Answer or None """ return self._answer @property def time(self): """ :return: 进行操作的时间 :rtype: datetime.datetime """ return self._time @property def owner(self): """ :return: 收藏夹的拥有者 :rtype: Author """ return self._owner @property def collection(self): """ :return: 所属收藏夹 :rtype: Collection """ return self._collection
class CollectActivity: '''收藏夹操作, 请使用``Collection.logs``构造对象.''' def __init__(self, type, time, owner, collection, answer=None): '''创建收藏夹操作类实例 :param acttype.CollectActType type: 操作类型 :param datetime.datetime time: 进行操作的时间 :param Author owner: 收藏夹的拥有者 :param Collection collection: 所属收藏夹 :param Answer answer: 收藏的答案,可选 :return: CollectActivity ''' pass @property def type(self): ''' :return: 收藏夹操作类型, 具体参见 :class:`.CollectActType` :rtype: :class:`.CollectActType` ''' pass @property def answer(self): ''' :return: 添加或删除收藏的答案, 若是创建收藏夹操作返回 None :rtype: Answer or None ''' pass @property def time(self): ''' :return: 进行操作的时间 :rtype: datetime.datetime ''' pass @property def owner(self): ''' :return: 收藏夹的拥有者 :rtype: Author ''' pass @property def collection(self): ''' :return: 所属收藏夹 :rtype: Collection ''' pass
12
7
8
0
3
5
1
1.32
0
0
0
0
6
5
6
6
58
7
22
17
10
29
17
12
10
1
0
0
6
1,565
7sDream/zhihu-py3
7sDream_zhihu-py3/zhihu/client.py
zhihu.client.ZhihuClient
class ZhihuClient: """知乎客户端类,内部维护了自己专用的网络会话,可用cookies或账号密码登录.""" def __init__(self, cookies=None): """创建客户端类实例. :param str cookies: 见 :meth:`.login_with_cookies` 中 ``cookies`` 参数 :return: 知乎客户端对象 :rtype: ZhihuClient """ self._session = requests.Session() self._session.headers.update(Default_Header) self.proxies = None if cookies is not None: assert isinstance(cookies, str) self.login_with_cookies(cookies) # ===== login staff ===== @staticmethod def _get_captcha_url(): params = { 'r': str(int(time.time() * 1000)), 'type': 'login', } return Captcha_URL + '?' + urlencode(params) def get_captcha(self): """获取验证码数据。 :return: 验证码图片数据。 :rtype: bytes """ self._session.get(Zhihu_URL) r = self._session.get(self._get_captcha_url()) return r.content def login(self, email, password, captcha=None): """登陆知乎. :param str email: 邮箱 :param str password: 密码 :param str captcha: 验证码, 默认为None,表示不提交验证码 :return: ======== ======== ============== ==================== 元素序号 元素类型 意义 说明 ======== ======== ============== ==================== 0 int 是否成功 0为成功,1为失败 1 str 失败原因 登录成功则为空字符串 2 str cookies字符串 登录失败则为空字符串 ======== ======== ============== ==================== :rtype: (int, str, str) """ data = {'email': email, 'password': password, 'remember_me': 'true'} if captcha is not None: data['captcha'] = captcha r = self._session.post(Login_URL, data=data) j = r.json() code = int(j['r']) message = j['msg'] cookies_str = json.dumps(self._session.cookies.get_dict()) \ if code == 0 else '' return code, message, cookies_str def login_with_cookies(self, cookies): """使用cookies文件或字符串登录知乎 :param str cookies: ============== =========================== 参数形式 作用 ============== =========================== 文件名 将文件内容作为cookies字符串 cookies 字符串 直接提供cookies字符串 ============== =========================== :return: 无 :rtype: None """ if os.path.isfile(cookies): with open(cookies) as f: cookies = f.read() cookies_dict = json.loads(cookies) self._session.cookies.update(cookies_dict) def login_in_terminal(self, need_captcha=False, use_getpass=True): """不使用cookies,在终端中根据提示登陆知乎 :param bool need_captcha: 是否要求输入验证码,如果登录失败请设为 True :param bool use_getpass: 是否使用安全模式输入密码,默认为 True, 如果在某些 Windows IDE 中无法正常输入密码,请把此参数设置为 False 试试 :return: 如果成功返回cookies字符串 :rtype: str """ print('====== zhihu login =====') email = input('email: ') if use_getpass: password = getpass.getpass('password: ') else: password = input("password: ") if need_captcha: captcha_data = self.get_captcha() with open('captcha.gif', 'wb') as f: f.write(captcha_data) print('please check captcha.gif for captcha') captcha = input('captcha: ') os.remove('captcha.gif') else: captcha = None print('====== logging.... =====') code, msg, cookies = self.login(email, password, captcha) if code == 0: print('login successfully') else: print('login failed, reason: {0}'.format(msg)) return cookies def create_cookies(self, file, need_captcha=False, use_getpass=True): """在终端中执行登录流程,将 cookies 存放在文件中以便后续使用 :param str file: 文件名 :param bool need_captcha: 登录过程中是否使用验证码, 默认为 False :param bool use_getpass: 是否使用安全模式输入密码,默认为 True, 如果在某些 Windows IDE 中无法正常输入密码,请把此参数设置为 False 试试 :return: """ cookies_str = self.login_in_terminal(need_captcha, use_getpass) if cookies_str: with open(file, 'w') as f: f.write(cookies_str) print('cookies file created.') else: print('can\'t create cookies.') # ===== network staff ===== def set_proxy(self, proxy): """设置代理 :param str proxy: 使用 "http://example.com:port" 的形式 :return: 无 :rtype: None :说明: 由于一个 :class:`.ZhihuClient` 对象和它创建出来的其他知乎对象共用 一个Session,所以调用这个方法也会将所有生成出的知乎类设置上代理。 """ self._session.proxies.update({'http': proxy}) def set_proxy_pool(self, proxies, auth=None, https=True): """设置代理池 :param proxies: proxy列表, 形如 ``["ip1:port1", "ip2:port2"]`` :param auth: 如果代理需要验证身份, 通过这个参数提供, 比如 :param https: 默认为 True, 传入 False 则不设置 https 代理 .. code-block:: python from requests.auth import HTTPProxyAuth auth = HTTPProxyAuth('laike9m', '123') :说明: 每次 GET/POST 请求会随机选择列表中的代理 """ from random import choice if https: self.proxies = [{'http': p, 'https': p} for p in proxies] else: self.proxies = [{'http': p} for p in proxies] def get_with_random_proxy(url, **kwargs): proxy = choice(self.proxies) kwargs['proxies'] = proxy if auth: kwargs['auth'] = auth return self._session.original_get(url, **kwargs) def post_with_random_proxy(url, *args, **kwargs): proxy = choice(self.proxies) kwargs['proxies'] = proxy if auth: kwargs['auth'] = auth return self._session.original_post(url, *args, **kwargs) self._session.original_get = self._session.get self._session.get = get_with_random_proxy self._session.original_post = self._session.post self._session.post = post_with_random_proxy def remove_proxy_pool(self): """ 移除代理池 """ self.proxies = None self._session.get = self._session.original_get self._session.post = self._session.original_post del self._session.original_get del self._session.original_post # ===== getter staff ====== def me(self): """获取使用特定 cookies 的 Me 实例 :return: cookies对应的Me对象 :rtype: Me """ from .me import Me headers = dict(Default_Header) headers['Host'] = 'zhuanlan.zhihu.com' res = self._session.get(Get_Me_Info_Url, headers=headers) json_data = res.json() url = json_data['profileUrl'] name = json_data['name'] motto = json_data['bio'] photo = json_data['avatar']['template'].format( id=json_data['avatar']['id'], size='r') return Me(url, name, motto, photo, session=self._session) def __getattr__(self, item: str): """本函数用于获取各种类,如 `Answer` `Question` 等. :支持的形式有: 1. client.answer() 2. client.author() 3. client.collection() 4. client.column() 5. client.post() 6. client.question() 7. client.topic() 参数均为对应页面的url,返回对应的类的实例。 """ def getter(url): return getattr(module, item.capitalize())(url, session=self._session) attr_list = ['answer', 'author', 'collection', 'column', 'post', 'question', 'topic'] if item.lower() in attr_list: module = importlib.import_module('.'+item.lower(), 'zhihu') return getter
class ZhihuClient: '''知乎客户端类,内部维护了自己专用的网络会话,可用cookies或账号密码登录.''' def __init__(self, cookies=None): '''创建客户端类实例. :param str cookies: 见 :meth:`.login_with_cookies` 中 ``cookies`` 参数 :return: 知乎客户端对象 :rtype: ZhihuClient ''' pass @staticmethod def _get_captcha_url(): pass def get_captcha(self): '''获取验证码数据。 :return: 验证码图片数据。 :rtype: bytes ''' pass def login(self, email, password, captcha=None): '''登陆知乎. :param str email: 邮箱 :param str password: 密码 :param str captcha: 验证码, 默认为None,表示不提交验证码 :return: ======== ======== ============== ==================== 元素序号 元素类型 意义 说明 ======== ======== ============== ==================== 0 int 是否成功 0为成功,1为失败 1 str 失败原因 登录成功则为空字符串 2 str cookies字符串 登录失败则为空字符串 ======== ======== ============== ==================== :rtype: (int, str, str) ''' pass def login_with_cookies(self, cookies): '''使用cookies文件或字符串登录知乎 :param str cookies: ============== =========================== 参数形式 作用 ============== =========================== 文件名 将文件内容作为cookies字符串 cookies 字符串 直接提供cookies字符串 ============== =========================== :return: 无 :rtype: None ''' pass def login_in_terminal(self, need_captcha=False, use_getpass=True): '''不使用cookies,在终端中根据提示登陆知乎 :param bool need_captcha: 是否要求输入验证码,如果登录失败请设为 True :param bool use_getpass: 是否使用安全模式输入密码,默认为 True, 如果在某些 Windows IDE 中无法正常输入密码,请把此参数设置为 False 试试 :return: 如果成功返回cookies字符串 :rtype: str ''' pass def create_cookies(self, file, need_captcha=False, use_getpass=True): '''在终端中执行登录流程,将 cookies 存放在文件中以便后续使用 :param str file: 文件名 :param bool need_captcha: 登录过程中是否使用验证码, 默认为 False :param bool use_getpass: 是否使用安全模式输入密码,默认为 True, 如果在某些 Windows IDE 中无法正常输入密码,请把此参数设置为 False 试试 :return: ''' pass def set_proxy(self, proxy): '''设置代理 :param str proxy: 使用 "http://example.com:port" 的形式 :return: 无 :rtype: None :说明: 由于一个 :class:`.ZhihuClient` 对象和它创建出来的其他知乎对象共用 一个Session,所以调用这个方法也会将所有生成出的知乎类设置上代理。 ''' pass def set_proxy_pool(self, proxies, auth=None, https=True): '''设置代理池 :param proxies: proxy列表, 形如 ``["ip1:port1", "ip2:port2"]`` :param auth: 如果代理需要验证身份, 通过这个参数提供, 比如 :param https: 默认为 True, 传入 False 则不设置 https 代理 .. code-block:: python from requests.auth import HTTPProxyAuth auth = HTTPProxyAuth('laike9m', '123') :说明: 每次 GET/POST 请求会随机选择列表中的代理 ''' pass def get_with_random_proxy(url, **kwargs): pass def post_with_random_proxy(url, *args, **kwargs): pass def remove_proxy_pool(self): ''' 移除代理池 ''' pass def me(self): '''获取使用特定 cookies 的 Me 实例 :return: cookies对应的Me对象 :rtype: Me ''' pass def __getattr__(self, item: str): '''本函数用于获取各种类,如 `Answer` `Question` 等. :支持的形式有: 1. client.answer() 2. client.author() 3. client.collection() 4. client.column() 5. client.post() 6. client.question() 7. client.topic() 参数均为对应页面的url,返回对应的类的实例。 ''' pass def getter(url): pass
17
12
16
2
9
6
2
0.74
0
4
1
0
11
2
12
12
248
41
119
50
100
88
105
46
87
4
0
2
27
1,566
7sDream/zhihu-py3
7sDream_zhihu-py3/zhihu/base.py
zhihu.base.JsonAsSoupMixin
class JsonAsSoupMixin: def _gen_soup(self, content): # 为了让`from_html`对外提供统一的接口, 判断一下输入, 如果是bytes 或者 str 则用json处理, # 否则认为是由_get_content返回的dict if isinstance(content, bytes): r = Response() r._content = content soup = r.json() self.soup = soup elif isinstance(content, str): self.soup = json.loads(content) else: self.soup = content
class JsonAsSoupMixin: def _gen_soup(self, content): pass
2
0
13
1
10
2
3
0.18
0
3
0
2
1
1
1
1
14
1
11
5
9
2
9
5
7
3
0
1
3
1,567
7sDream/zhihu-py3
7sDream_zhihu-py3/zhihu/me.py
zhihu.me.Me
class Me(Author): """封装了相关操作(如点赞,关注问题)的类。 请使用 :meth:`.ZhihuClient.me` 方法获取实例。 """ def __init__(self, url, name, motto, photo_url, session): super(Me, self).__init__(url, name, motto, photo_url=photo_url, session=session) def vote(self, something, vote='up'): """给答案或文章点赞或取消点赞 :param Answer/Post something: 需要点赞的答案或文章对象 :param str vote: ===== ================ ====== 取值 说明 默认值 ===== ================ ====== up 赞同 √ down 反对 X clear 既不赞同也不反对 X ===== ================ ====== :return: 成功返回True,失败返回False :rtype: bool """ from .answer import Answer from zhihu import Post if isinstance(something, Answer): mapping = { 'up': 'vote_up', 'clear': 'vote_neutral', 'down': 'vote_down' } if vote not in mapping.keys(): raise ValueError('Invalid vote value: {0}'.format(vote)) if something.author.url == self.url: return False params = {'answer_id': str(something.aid)} data = { '_xsrf': something.xsrf, 'method': mapping[vote], 'params': json.dumps(params) } headers = dict(Default_Header) headers['Referer'] = something.question.url[:-1] res = self._session.post(Upvote_Answer_Url, headers=headers, data=data) return res.json()['r'] == 0 elif isinstance(something, Post): mapping = { 'up': 'like', 'clear': 'none', 'down': 'dislike' } if vote not in mapping.keys(): raise ValueError('Invalid vote value: {0}'.format(vote)) if something.author.url == self.url: return False put_url = Upvote_Article_Url.format( something.column_in_name, something.slug) data = {'value': mapping[vote]} headers = { 'Content-Type': 'application/json;charset=utf-8', 'Host': 'zhuanlan.zhihu.com', 'Referer': something.url[:-1], 'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; ' 'rv:39.0) Gecko/20100101 Firefox/39.0', 'X-XSRF-TOKEN': self._session.cookies.get('XSRF-TOKEN') } res = self._session.put(put_url, json.dumps(data), headers=headers) return res.status_code == 204 else: raise ValueError('argument something need to be ' 'zhihu.Answer or zhihu.Post object.') def thanks(self, answer, thanks=True): """感谢或取消感谢回答 :param Answer answer: 要感谢或取消感谢的回答 :param thanks: True-->感谢,False-->取消感谢 :return: 成功返回True,失败返回False :rtype: bool """ from .answer import Answer if isinstance(answer, Answer) is False: raise ValueError('argument answer need to be Zhihu.Answer object.') if answer.author.url == self.url: return False data = { '_xsrf': answer.xsrf, 'aid': answer.aid } res = self._session.post(Thanks_Url if thanks else Cancel_Thanks_Url, data=data) return res.json()['r'] == 0 def follow(self, something, follow=True): """关注用户、问题、话题或收藏夹 :param Author/Question/Topic something: 需要关注的对象 :param bool follow: True-->关注,False-->取消关注 :return: 成功返回True,失败返回False :rtype: bool """ from .question import Question from .topic import Topic from .collection import Collection if isinstance(something, Author): if something.url == self.url: return False data = { '_xsrf': something.xsrf, 'method': ' follow_member' if follow else 'unfollow_member', 'params': json.dumps({'hash_id': something.hash_id}) } res = self._session.post(Follow_Author_Url, data=data) return res.json()['r'] == 0 elif isinstance(something, Question): data = { '_xsrf': something.xsrf, 'method': 'follow_question' if follow else 'unfollow_question', 'params': json.dumps({'question_id': str(something.qid)}) } res = self._session.post(Follow_Question_Url, data=data) return res.json()['r'] == 0 elif isinstance(something, Topic): data = { '_xsrf': something.xsrf, 'method': 'follow_topic' if follow else 'unfollow_topic', 'params': json.dumps({'topic_id': something.tid}) } res = self._session.post(Follow_Topic_Url, data=data) return res.json()['r'] == 0 elif isinstance(something, Collection): data = { '_xsrf': something.xsrf, 'favlist_id': something.cid } res = self._session.post( Follow_Collection_Url if follow else Unfollow_Collection_Url, data=data) return res.json()['r'] == 0 else: raise ValueError('argument something need to be ' 'zhihu.Author, zhihu.Question' ', Zhihu.Topic or Zhihu.Collection object.') def add_comment(self, answer, content): """给指定答案添加评论 :param Answer answer: 答案对象 :param string content: 评论内容 :return: 成功返回 True,失败返回 False :rtype: bool """ from .answer import Answer if isinstance(answer, Answer) is False: raise ValueError('argument answer need to be Zhihu.Answer object.') if not content: raise ValueError('answer content cannot be empty') data = { 'method': 'add_comment', 'params': json.dumps({'answer_id': answer.aid, 'content': content}), '_xsrf': answer.xsrf } res = self._session.post(Answer_Add_Comment_URL, data=data) return res.json()['r'] == 0 def send_message(self, author, content): """发送私信给一个用户 :param Author author: 接收私信用户对象 :param string content: 发送给用户的私信内容 :return: 成功返回 True,失败返回 False :rtype: bool """ if isinstance(author, Author) is False: raise ValueError('argument answer need to be Zhihu.Author object.') if not content: raise ValueError('answer content cannot be empty') if author.url == self.url: return False data = { 'member_id': author.hash_id, 'content': content, 'token': '', '_xsrf': author.xsrf } res = self._session.post(Send_Message_Url, data=data) return res.json()['r'] == 0 def block(self, something, block=True): """屏蔽某个用户、话题 :param Author/Topic something: :param block: True-->屏蔽,False-->取消屏蔽 :return: 成功返回 True,失败返回 False :rtype: bool """ from .topic import Topic if isinstance(something, Author): if something.url == self.url: return False data = { '_xsrf': something.xsrf, 'action': 'add' if block else 'cancel', } block_author_url = something.url + 'block' res = self._session.post(block_author_url, data=data) return res.json()['r'] == 0 elif isinstance(something, Topic): tid = something.tid data = { '_xsrf': something.xsrf, 'method': 'add' if block else 'del', 'tid': tid, } block_topic_url = 'http://www.zhihu.com/topic/ignore' res = self._session.post(block_topic_url, data=data) return res.status_code == 200 else: raise ValueError('argument something need to be ' 'Zhihu.Author or Zhihu.Topic object.') def unhelpful(self, answer, unhelpful=True): """没有帮助或取消没有帮助回答 :param Answer answer: 要没有帮助或取消没有帮助回答 :param unhelpful: True-->没有帮助,False-->取消没有帮助 :return: 成功返回 True,失败返回 False :rtype: bool """ from .answer import Answer if isinstance(answer, Answer) is False: raise ValueError('argument answer need to be Zhihu.Answer object.') if answer.author.url == self.url: return False data = { '_xsrf': answer.xsrf, 'aid': answer.aid } res = self._session.post(Unhelpful_Url if unhelpful else Cancel_Unhelpful_Url, data=data) return res.json()['r'] == 0
class Me(Author): '''封装了相关操作(如点赞,关注问题)的类。 请使用 :meth:`.ZhihuClient.me` 方法获取实例。 ''' def __init__(self, url, name, motto, photo_url, session): pass def vote(self, something, vote='up'): '''给答案或文章点赞或取消点赞 :param Answer/Post something: 需要点赞的答案或文章对象 :param str vote: ===== ================ ====== 取值 说明 默认值 ===== ================ ====== up 赞同 √ down 反对 X clear 既不赞同也不反对 X ===== ================ ====== :return: 成功返回True,失败返回False :rtype: bool ''' pass def thanks(self, answer, thanks=True): '''感谢或取消感谢回答 :param Answer answer: 要感谢或取消感谢的回答 :param thanks: True-->感谢,False-->取消感谢 :return: 成功返回True,失败返回False :rtype: bool ''' pass def follow(self, something, follow=True): '''关注用户、问题、话题或收藏夹 :param Author/Question/Topic something: 需要关注的对象 :param bool follow: True-->关注,False-->取消关注 :return: 成功返回True,失败返回False :rtype: bool ''' pass def add_comment(self, answer, content): '''给指定答案添加评论 :param Answer answer: 答案对象 :param string content: 评论内容 :return: 成功返回 True,失败返回 False :rtype: bool ''' pass def send_message(self, author, content): '''发送私信给一个用户 :param Author author: 接收私信用户对象 :param string content: 发送给用户的私信内容 :return: 成功返回 True,失败返回 False :rtype: bool ''' pass def block(self, something, block=True): '''屏蔽某个用户、话题 :param Author/Topic something: :param block: True-->屏蔽,False-->取消屏蔽 :return: 成功返回 True,失败返回 False :rtype: bool ''' pass def unhelpful(self, answer, unhelpful=True): '''没有帮助或取消没有帮助回答 :param Answer answer: 要没有帮助或取消没有帮助回答 :param unhelpful: True-->没有帮助,False-->取消没有帮助 :return: 成功返回 True,失败返回 False :rtype: bool ''' pass
9
8
30
1
22
6
5
0.29
1
8
4
0
8
0
8
52
249
19
178
39
160
52
101
39
83
10
2
2
39
1,568
7sDream/zhihu-py3
7sDream_zhihu-py3/zhihu/author.py
zhihu.author.BanException
class BanException(Exception): """当尝试获取被反屏蔽系统限制的用户资料时,将会引发此异常""" pass
class BanException(Exception): '''当尝试获取被反屏蔽系统限制的用户资料时,将会引发此异常''' pass
1
1
0
0
0
0
0
0.5
1
0
0
0
0
0
0
10
3
0
2
1
1
1
2
1
1
0
3
0
0
1,569
7sDream/zhihu-py3
7sDream_zhihu-py3/zhihu/acttype.py
zhihu.acttype.ActType
class ActType(enum.Enum): """用于表示用户动态的类型. :常量说明: ================= ================ ============ ===================== 常量名 说明 提供属性 属性类型 ================= ================ ============ ===================== ANSWER_QUESTION 回答了一个问题 answer :class:`.Answer` UPVOTE_ANSWER 赞同了一个回答 answer :class:`.Answer` ASK_QUESTION 提出了一个问题 question :class:`.Question` FOLLOW_QUESTION 关注了一个问题 question :class:`.Question` UPVOTE_POST 赞同了一篇文章 post :class:`.Post` FOLLOW_COLUMN 关注了一个专栏 column :class:`.Column` FOLLOW_TOPIC 关注了一个话题 topic :class:`.Topic` PUBLISH_POST 发表了一篇文章 post :class:`.Post` FOLLOW_COLLECTION 关注了一个收藏夹 collection :class:`.Collection` ================= ================ ============ ===================== """ ANSWER_QUESTION = 1 UPVOTE_ANSWER = 2 ASK_QUESTION = 4 FOLLOW_QUESTION = 8 UPVOTE_POST = 16 FOLLOW_COLUMN = 32 FOLLOW_TOPIC = 64 PUBLISH_POST = 128 FOLLOW_COLLECTION = 256 @classmethod def from_str(cls, div_class): return cls.__getattr__(reverse_match[div_class]) def __str__(self): return match[self.name]
class ActType(enum.Enum): '''用于表示用户动态的类型. :常量说明: ================= ================ ============ ===================== 常量名 说明 提供属性 属性类型 ================= ================ ============ ===================== ANSWER_QUESTION 回答了一个问题 answer :class:`.Answer` UPVOTE_ANSWER 赞同了一个回答 answer :class:`.Answer` ASK_QUESTION 提出了一个问题 question :class:`.Question` FOLLOW_QUESTION 关注了一个问题 question :class:`.Question` UPVOTE_POST 赞同了一篇文章 post :class:`.Post` FOLLOW_COLUMN 关注了一个专栏 column :class:`.Column` FOLLOW_TOPIC 关注了一个话题 topic :class:`.Topic` PUBLISH_POST 发表了一篇文章 post :class:`.Post` FOLLOW_COLLECTION 关注了一个收藏夹 collection :class:`.Collection` ================= ================ ============ ===================== ''' @classmethod def from_str(cls, div_class): pass def __str__(self): pass
4
1
2
0
2
0
1
1.07
1
0
0
0
1
0
2
51
37
6
15
13
11
16
14
12
11
1
4
0
2
1,570
7sDream/zhihu-py3
7sDream_zhihu-py3/zhihu/activity.py
zhihu.activity.Activity
class Activity: """用户动态类,请使用Author.activities获取.""" def __init__(self, act, session, author): """创建用户动态类实例. :param bs4.element.Tag act: 表示用户动态的页面元素 :param Session session: 使用的网络会话 :param Author author: Activity 所属的用户对象 :return: 用户动态对象 :rtype: Activity :说明: 根据Activity.type不同可以获取不同属性,具体请看 :class:`.ActType` """ self._session = session self._author = author self._type = ActType.from_str(act.attrs['data-type-detail']) useless_tag = act.div.find('a', class_='zg-link') if useless_tag is not None: useless_tag.extract() attribute = self._get_assemble_method(self.type)(act) self._attr = attribute.__class__.__name__.lower() setattr(self, self._attr, attribute) self._time = datetime.fromtimestamp(int(act['data-time'])) @property def type(self): """ :return: 用户动态类型, 具体参见 :class:`.ActType` :rtype: class:`.ActType` """ return self._type @property def content(self): """获取此对象中能提供的那个属性,对应表请查看 :class:`.ActType` 类. :return: 对象提供的对象 :rtype: Author or Question or Answer or Topic or Column or Post """ return getattr(self, self._attr) @property def time(self): """ :return: 返回用户执行 Activity 操作的时间 :rtype: datetime.datetime """ return self._time def __find_post(self, act): try: column_url = act.find('a', class_='column_link')['href'] column_name = act.find('a', class_='column_link').text column = Column(column_url, column_name, session=self._session) except TypeError: column = None try: author_tag = act.find('div', class_='author-info') author_url = Zhihu_URL + author_tag.a['href'] author_name = author_tag.a.text author_motto = author_tag.span.text if author_tag.span else '' author = Author(author_url, author_name, author_motto, session=self._session) except TypeError: author = ANONYMOUS post_url = act.find('a', class_='post-link')['href'] post_title = act.find('a', class_='post-link').text post_comment_num, post_upvote_num = self._parse_un_cn(act) return Post(post_url, column, author, post_title, post_upvote_num, post_comment_num, session=self._session) def _assemble_create_post(self, act): return self.__find_post(act) def _assemble_voteup_post(self, act): return self.__find_post(act) def _assemble_follow_column(self, act): return Column(act.div.a['href'], act.div.a.text, session=self._session) def _assemble_follow_topic(self, act): topic_url = Zhihu_URL + act.div.a['href'] topic_name = act.div.a['title'] return Topic(topic_url, topic_name, session=self._session) def _assemble_answer_question(self, act): question_url = Zhihu_URL + re_a2q.match( act.div.find_all('a')[-1]['href']).group(1) question_title = act.div.find_all('a')[-1].text.strip() question = Question(question_url, question_title, session=self._session) answer_url = Zhihu_URL + act.div.find_all('a')[-1]['href'] answer_comment_num, answer_upvote_num = self._parse_un_cn(act) return Answer(answer_url, question, self._author, answer_upvote_num, session=self._session) def _assemble_voteup_answer(self, act): question_url = Zhihu_URL + re_a2q.match(act.div.a['href']).group(1) question_title = act.div.a.text.strip() question = Question(question_url, question_title, session=self._session) try_find_author = act.find_all('a', class_='author-link', href=re.compile('^/people/[^/]*$')) if len(try_find_author) == 0: author_url = None author_name = '匿名用户' author_motto = '' else: try_find_author = try_find_author[-1] author_url = Zhihu_URL + try_find_author['href'] author_name = try_find_author.text try_find_motto = act.find('span', class_='bio') if try_find_motto is None: author_motto = '' else: author_motto = try_find_motto['title'] author = Author(author_url, author_name, author_motto, session=self._session) answer_url = Zhihu_URL + act.div.a['href'] answer_comment_num, answer_upvote_num = self._parse_un_cn(act) return Answer(answer_url, question, author, answer_upvote_num, session=self._session) def _assemble_ask_question(self, act): a = act.find("a", class_="question_link") url = Zhihu_URL + a['href'] title = a.text.strip(' \n') return Question(url, title, session=self._session) def _assemble_follow_question(self, act): return Question(Zhihu_URL + act.div.a['href'], act.div.a.text.strip(), session=self._session) def _assemble_follow_collection(self, act): url = act.div.a['href'] if not url.startswith('http'): url = Zhihu_URL + url return Collection(url, session=self._session) def _get_assemble_method(self, act_type): assemble_methods = { ActType.UPVOTE_POST: self._assemble_voteup_post, ActType.FOLLOW_COLUMN: self._assemble_follow_column, ActType.UPVOTE_ANSWER: self._assemble_voteup_answer, ActType.ANSWER_QUESTION: self._assemble_answer_question, ActType.ASK_QUESTION: self._assemble_ask_question, ActType.FOLLOW_QUESTION: self._assemble_follow_question, ActType.FOLLOW_TOPIC: self._assemble_follow_topic, ActType.PUBLISH_POST: self._assemble_create_post, ActType.FOLLOW_COLLECTION: self._assemble_follow_collection } if act_type in assemble_methods: return assemble_methods[act_type] else: raise ValueError('invalid activity type') @staticmethod def _parse_un_cn(act): upvote_num = act.find('a', class_='zm-item-vote-count').text if upvote_num.isdigit(): upvote_num = int(upvote_num) else: upvote_num = None comment = act.find('a', class_='toggle-comment') comment_text = next(comment.stripped_strings) comment_num_match = re_get_number.match(comment_text) comment_num = int( comment_num_match.group(1)) if comment_num_match is not None else 0 return comment_num, upvote_num
class Activity: '''用户动态类,请使用Author.activities获取.''' def __init__(self, act, session, author): '''创建用户动态类实例. :param bs4.element.Tag act: 表示用户动态的页面元素 :param Session session: 使用的网络会话 :param Author author: Activity 所属的用户对象 :return: 用户动态对象 :rtype: Activity :说明: 根据Activity.type不同可以获取不同属性,具体请看 :class:`.ActType` ''' pass @property def type(self): ''' :return: 用户动态类型, 具体参见 :class:`.ActType` :rtype: class:`.ActType` ''' pass @property def content(self): '''获取此对象中能提供的那个属性,对应表请查看 :class:`.ActType` 类. :return: 对象提供的对象 :rtype: Author or Question or Answer or Topic or Column or Post ''' pass @property def time(self): ''' :return: 返回用户执行 Activity 操作的时间 :rtype: datetime.datetime ''' pass def __find_post(self, act): pass def _assemble_create_post(self, act): pass def _assemble_voteup_post(self, act): pass def _assemble_follow_column(self, act): pass def _assemble_follow_topic(self, act): pass def _assemble_answer_question(self, act): pass def _assemble_voteup_answer(self, act): pass def _assemble_ask_question(self, act): pass def _assemble_follow_question(self, act): pass def _assemble_follow_collection(self, act): pass def _get_assemble_method(self, act_type): pass @staticmethod def _parse_un_cn(act): pass
21
5
10
1
8
1
2
0.17
0
12
8
0
15
5
16
16
176
25
129
67
108
22
101
63
84
4
0
2
26
1,571
7sDream/zhihu-py3
7sDream_zhihu-py3/zhihu/base.py
zhihu.base.BaseZhihu
class BaseZhihu: def _gen_soup(self, content): self.soup = BeautifulSoup(content) def _get_content(self): # use _url for question url = self._url if hasattr(self, '_url') else self.url if url.endswith('/'): resp = self._session.get(url[:-1]) else: resp = self._session.get(url) class_name = self.__class__.__name__ if class_name == 'Answer': if 'answer' in resp.url: self._deleted = False else: self._deleted = True elif class_name == 'Question': self._deleted = resp.status_code == 404 return resp.content def _make_soup(self): if self.url and not self.soup: self._gen_soup(self._get_content()) def refresh(self): # refresh self.soup's content self._gen_soup(self._get_content()) @classmethod def from_html(cls, content): obj = cls(url=None) obj._gen_soup(content) return obj
class BaseZhihu: def _gen_soup(self, content): pass def _get_content(self): pass def _make_soup(self): pass def refresh(self): pass @classmethod def from_html(cls, content): pass
7
0
6
0
5
0
2
0.07
0
0
0
7
4
2
5
5
36
6
28
13
21
2
24
12
18
6
0
2
11
1,572
99designs/colorific
99designs_colorific/tests/test_colorific.py
tests.test_colorific.ConversionTest
class ConversionTest(unittest.TestCase): def setUp(self): self.pairs = [ ((0, 0, 0), '#000000'), ((255, 255, 255), '#ffffff'), ((255, 0, 0), '#ff0000'), ((0, 255, 0), '#00ff00'), ((0, 0, 255), '#0000ff'), ] def test_hex_to_rgb(self): for rgb, hexval in self.pairs: self.assertEqual(colorific.hex_to_rgb(hexval), rgb) def test_rgb_to_hex(self): for rgb, hexval in self.pairs: self.assertEqual(colorific.rgb_to_hex(rgb), hexval)
class ConversionTest(unittest.TestCase): def setUp(self): pass def test_hex_to_rgb(self): pass def test_rgb_to_hex(self): pass
4
0
5
0
5
2
2
0.33
1
0
0
0
3
1
3
75
17
2
15
7
11
5
9
7
5
2
2
1
5
1,573
99designs/colorific
99designs_colorific/colorific/script.py
colorific.script.Application
class Application(object): def __init__(self): self.parser = self.create_option_parser() def create_option_parser(self): usage = '\n'.join([ "%prog [options]", "", "Reads a stream of image filenames from stdin, and outputs a ", "single line for each containing hex color values."]) parser = optparse.OptionParser(usage) parser.add_option( '-p', '--parallel', action='store', dest='n_processes', type='int', default=config.N_PROCESSES) parser.add_option( '--min-saturation', action='store', dest='min_saturation', default=config.MIN_SATURATION, type='float', help="Only keep colors which meet this saturation " "[%.02f]" % config.MIN_SATURATION) parser.add_option( '--max-colors', action='store', dest='max_colors', type='int', default=config.MAX_COLORS, help="The maximum number of colors to output per palette " "[%d]" % config.MAX_COLORS) parser.add_option( '--min-distance', action='store', dest='min_distance', type='float', default=config.MIN_DISTANCE, help="The minimum distance colors must have to stay separate " "[%.02f]" % config.MIN_DISTANCE) parser.add_option( '--min-prominence', action='store', dest='min_prominence', type='float', default=config.MIN_PROMINENCE, help="The minimum proportion of pixels needed to keep a color " "[%.02f]" % config.MIN_PROMINENCE) parser.add_option( '--n-quantized', action='store', dest='n_quantized', type='int', default=config.N_QUANTIZED, help="Speed up by reducing the number in the quantizing step " "[%d]" % config.N_QUANTIZED) parser.add_option( '-o', action='store_true', dest='save_palette', default=False, help="Output the palette as an image file") return parser def run(self): argv = sys.argv[1:] (options, args) = self.parser.parse_args(argv) if args: # image filenames were provided as arguments for filename in args: try: palette = extract_colors( filename, min_saturation=options.min_saturation, min_prominence=options.min_prominence, min_distance=options.min_distance, max_colors=options.max_colors, n_quantized=options.n_quantized) except Exception as e: # TODO: it's too broad exception. print >> sys.stderr, filename, e continue print_colors(filename, palette) if options.save_palette: save_palette_as_image(filename, palette) sys.exit(1) if options.n_processes > 1: # XXX add all the knobs we can tune color_stream_mt(n=options.n_processes) else: color_stream_st( min_saturation=options.min_saturation, min_prominence=options.min_prominence, min_distance=options.min_distance, max_colors=options.max_colors, n_quantized=options.n_quantized, save_palette=options.save_palette)
class Application(object): def __init__(self): pass def create_option_parser(self): pass def run(self): pass
4
0
34
2
31
1
3
0.03
1
2
0
0
3
1
3
3
105
9
94
12
90
3
31
11
27
6
1
3
8
1,574
99designs/colorific
99designs_colorific/tests/test_colorific.py
tests.test_colorific.ExtractionTest
class ExtractionTest(unittest.TestCase): def setUp(self): self.filename = os.path.join(os.path.dirname(__file__), 'nasa_ares_logo.png') def test_extraction(self): expected = [(0, 101, 185), (187, 214, 236), (255, 0, 0)] p = palette.extract_colors(self.filename) found = [c.value for c in p.colors] self.assertEquals(found, expected)
class ExtractionTest(unittest.TestCase): def setUp(self): pass def test_extraction(self): pass
3
0
5
0
5
0
1
0
1
0
0
0
2
1
2
74
12
1
11
7
8
0
8
7
5
1
2
0
2
1,575
99designs/colorific
99designs_colorific/tests/test_colorific.py
tests.test_colorific.VisualDistanceTest
class VisualDistanceTest(unittest.TestCase): def test_core_colors(self): for c1, c2 in itertools.combinations(CORE_COLORS, 2): assert not self.similar(c1, c2) def test_apparent_mistakes(self): mistakes = [ ('#f1f1f1', '#f2f2f2'), ('#f2f2f2', '#f3f3f3'), ('#fafafa', '#fbfbfb'), ('#7c7c7c', '#7d7d7d'), ('#29abe1', '#29abe2'), ] for c1, c2 in mistakes: assert self.similar(c1, c2) def distance(self, c1, c2): return colorific.distance( colorific.hex_to_rgb(c1), colorific.hex_to_rgb(c2), ) def similar(self, c1, c2): return self.distance(c1, c2) < colorific.MIN_DISTANCE
class VisualDistanceTest(unittest.TestCase): def test_core_colors(self): pass def test_apparent_mistakes(self): pass def distance(self, c1, c2): pass def similar(self, c1, c2): pass
5
0
5
0
5
1
2
0.24
1
1
0
0
4
0
4
76
25
4
21
8
16
5
12
8
7
2
2
1
6
1,576
9b/frisbee
9b_frisbee/frisbee/modules/bing.py
frisbee.modules.bing.Module
class Module(Base): """Custom search module.""" def __init__(self, domain=None, modifier=None, engine="bing", greedy=False, fuzzy=False, limit=500): """Setup the primary client instance.""" super(Base, self).__init__() self.name = "Bing" self.host = "https://www.bing.com" self.domain = domain self.modifier = modifier self.limit = limit self.greedy = greedy self.fuzzy = fuzzy self.results = list() self.data = list() self._start_time = None self._end_time = None self._duration = None def _format(self): """Format search queries to perform in bulk. Build up the URLs to call for the search engine. These will be ran through a bulk processor and returned to a detailer. """ self.log.debug("Formatting URLs to request") items = list() for i in range(0, self.limit, 10): query = '"%s" %s' % (self.domain, self.modifier) url = self.host + "/search?q=" + query + "&first=" + str(i) items.append(url) self.log.debug("URLs were generated") return items def _process(self, responses): """Process search engine results for detailed analysis. Search engine result pages (SERPs) come back with each request and will need to be extracted in order to crawl the actual hits. """ self.log.debug("Processing search results") items = list() for response in responses: try: soup = BeautifulSoup(response.content, 'html.parser', from_encoding="iso-8859-1") except: continue else: listings = soup.findAll('li', {'class': 'b_algo'}) items.extend([l.find('a')['href'] for l in listings]) self.log.debug("Search result URLs were extracted") return items def _fetch(self, urls): """Perform bulk collection of data and return the content. Gathering responses is handled by the base class and uses futures to speed up the processing. Response data is saved inside a local variable to be used later in extraction. """ responses = self._request_bulk(urls) self.log.debug("Converting responses to text") for response in responses: if len(response.content) > 3000000: continue try: soup = BeautifulSoup(response.content, 'html.parser', from_encoding="iso-8859-1") text = soup.get_text() # This will result in errors at times as it smashes text together with the email address except Exception: text = response.text self.data.append(text) # Opportunistic findings self.log.debug("Responses converted") return responses def _extract(self): """Extract email addresses from results. Text content from all crawled pages are ran through a simple email extractor. Data is cleaned prior to running pattern expressions. """ self.log.debug("Extracting emails from text content") for item in self.data: emails = extract_emails(item, self.domain, self.fuzzy) self.results.extend(emails) self.log.debug("Email extraction completed") return list(set(self.results)) def search(self): """Run the full search process. Simple public method to abstract the steps needed to produce a full search using the engine. """ requests = self._format() serps = self._fetch(requests) urls = self._process(serps) details = self._fetch(urls) emails = self._extract() self.log.debug("Job completed") return {'emails': emails, 'processed': len(self.data)}
class Module(Base): '''Custom search module.''' def __init__(self, domain=None, modifier=None, engine="bing", greedy=False, fuzzy=False, limit=500): '''Setup the primary client instance.''' pass def _format(self): '''Format search queries to perform in bulk. Build up the URLs to call for the search engine. These will be ran through a bulk processor and returned to a detailer. ''' pass def _process(self, responses): '''Process search engine results for detailed analysis. Search engine result pages (SERPs) come back with each request and will need to be extracted in order to crawl the actual hits. ''' pass def _fetch(self, urls): '''Perform bulk collection of data and return the content. Gathering responses is handled by the base class and uses futures to speed up the processing. Response data is saved inside a local variable to be used later in extraction. ''' pass def _extract(self): '''Extract email addresses from results. Text content from all crawled pages are ran through a simple email extractor. Data is cleaned prior to running pattern expressions. ''' pass def search(self): '''Run the full search process. Simple public method to abstract the steps needed to produce a full search using the engine. ''' pass
7
7
16
1
11
4
2
0.36
1
7
0
0
6
12
6
14
106
14
69
39
61
25
66
38
59
4
2
2
13
1,577
9b/frisbee
9b_frisbee/frisbee/__init__.py
frisbee.Frisbee
class Frisbee: """Class to interact with the core code.""" NAME: ClassVar[str] = "Frisbee" def __init__(self, project: str = namesgenerator.get_random_name(), log_level: int = logging.INFO, save: bool = False): """Creation. The moons and the planets are there.""" self.project: str = project self.project += "_%d" % (random.randint(100000, 999999)) self._log: logging.Logger = gen_logger(self.NAME, log_level) self.output: bool = save self.folder: str = os.getcwd() self._config_bootstrap() self._processed: List = list() self.results: List = list() self.saved: List = list() def _reset(self) -> None: """Reset some of the state in the class for multi-searches.""" self.project: str = namesgenerator.get_random_name() self.project += "_%d" % (random.randint(100000, 999999)) self._processed: List = list() self.results: List = list() def _config_bootstrap(self) -> None: """Handle the basic setup of the tool prior to user control. Bootstrap will load all the available modules for searching and set them up for use by this main class. """ if self.output: self.folder: str = os.getcwd() + "/results" if not os.path.exists(self.folder): os.mkdir(self.folder) self.folder += "/" + self.project os.mkdir(self.folder) def _progressive_save(self, job) -> None: """Save output to a dictionary as results stream in. Depending on the options used, Frisbee can run for quite a long time. Each individual job is written after its completed and includes the findings along with the job details. """ self._log.info("Saving results to '%s'" % self.folder) path: str = self.folder + "/" if job['domain'] in self.saved: return job['start_time'] = str_datetime(job['start_time']) job['end_time'] = str_datetime(job['end_time']) jid: int = random.randint(100000, 999999) filename: str = "%s_%s_%d_job.json" % (self.project, job['domain'], jid) handle = open(path + filename, 'w') handle.write(json.dumps(job, indent=4)) handle.close() filename = "%s_%s_%d_emails.txt" % (self.project, job['domain'], jid) handle = open(path + filename, 'w') for email in job['results']['emails']: handle.write(email + "\n") handle.close() self.saved.append(job['domain']) def search(self, jobs: List[Dict[str, str]], executor=None) -> None: """Perform searches based on job orders.""" if not isinstance(jobs, list): raise Exception("Jobs must be of type list.") self._log.info("Project: %s" % self.project) self._log.info("Processing jobs: %d", len(jobs)) if not executor: # Reuse the same executor pool when processing greedy jobs executor = ProcessPoolExecutor() futures = [executor.submit(collect, job) for job in jobs] for future in as_completed(futures): output = future.result() output.update({'project': self.project}) self._processed.append(output['domain']) self.results.append(output) self._progressive_save(output) if output['greedy']: bonus_jobs: List = list() observed: List = list() for item in output['results']['emails']: part_split = item.split('@') if len(part_split) == 1: continue found: str = item.split('@')[1] if found in self._processed or found in observed: continue observed.append(found) base: Dict = dict() base['limit'] = output['limit'] base['modifier'] = output['modifier'] base['engine'] = output['engine'] base['greedy'] = False base['domain'] = found bonus_jobs.append(base) if bonus_jobs: self.search(bonus_jobs, executor=executor) self._log.info("All jobs processed") def get_results(self) -> List: """Return results from the search.""" return self.results
class Frisbee: '''Class to interact with the core code.''' def __init__(self, project: str = namesgenerator.get_random_name(), log_level: '''Creation. The moons and the planets are there.''' pass def _reset(self) -> None: '''Reset some of the state in the class for multi-searches.''' pass def _config_bootstrap(self) -> None: '''Handle the basic setup of the tool prior to user control. Bootstrap will load all the available modules for searching and set them up for use by this main class. ''' pass def _progressive_save(self, job) -> None: '''Save output to a dictionary as results stream in. Depending on the options used, Frisbee can run for quite a long time. Each individual job is written after its completed and includes the findings along with the job details. ''' pass def search(self, jobs: List[Dict[str, str]], executor=None) -> None: '''Perform searches based on job orders.''' pass def get_results(self) -> List: '''Return results from the search.''' pass
7
7
17
2
13
2
3
0.19
0
7
0
0
6
7
6
6
113
18
80
30
72
15
79
29
72
9
0
4
18
1,578
9b/google-alerts
9b_google-alerts/google_alerts/__init__.py
google_alerts.MonitorNotFound
class MonitorNotFound(Exception): """Exception for missing monitors.""" pass
class MonitorNotFound(Exception): '''Exception for missing monitors.''' pass
1
1
0
0
0
0
0
0.5
1
0
0
0
0
0
0
10
3
0
2
1
1
1
2
1
1
0
3
0
0
1,579
9b/google-alerts
9b_google-alerts/google_alerts/__init__.py
google_alerts.InvalidState
class InvalidState(Exception): """Exception for invalid state.""" pass
class InvalidState(Exception): '''Exception for invalid state.''' pass
1
1
0
0
0
0
0
0.5
1
0
0
0
0
0
0
10
3
0
2
1
1
1
2
1
1
0
3
0
0
1,580
9b/google-alerts
9b_google-alerts/google_alerts/__init__.py
google_alerts.GoogleAlerts
class GoogleAlerts: NAME = "GoogleAlerts" LOG_LEVEL = logging.DEBUG LOGIN_URL = 'https://accounts.google.com/signin' AUTH_URL = 'https://accounts.google.com/signin/challenge/sl/password' ALERTS_URL = 'https://www.google.com/alerts' TEST_URL = 'https://myaccount.google.com/?pli=1' TEST_KEY = 'CREATE YOUR GOOGLE ACCOUNT' CAPTCHA_KEY = 'captcha-container' ALERTS_MODIFY_URL = 'https://www.google.com/alerts/modify?x={requestX}' ALERTS_CREATE_URL = 'https://www.google.com/alerts/create?x={requestX}' ALERTS_DELETE_URL = 'https://www.google.com/alerts/delete?x={requestX}' MONITOR_MATCH_TYPE = { 2: 'ALL', 3: 'BEST' } ALERT_FREQ = { 1: 'AS_IT_HAPPENS', 2: 'AT_MOST_ONCE_A_DAY', 3: 'AT_MOST_ONCE_A_WEEK', } DELIVERY = { 1: 'MAIL', 2: 'RSS' } HEADERS = { 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.90 Safari/537.36' } def __init__(self, email=None, password=None): self._log = self._logger() self._email = email self._password = password self._is_authenticated = False self._state = None self._session = requests.session() self._config_bootstrap() def _config_bootstrap(self): """Go through and establish the defaults on the file system. The approach here was stolen from the CLI tool provided with the module. Idea being that the user should not always need to provide a username and password in order to run the script. If the configuration file is already present with valid data, then lets use it. """ if not os.path.exists(CONFIG_PATH): os.makedirs(CONFIG_PATH) if not os.path.exists(CONFIG_FILE): json.dump(CONFIG_DEFAULTS, open(CONFIG_FILE, 'w'), indent=4, separators=(',', ': ')) config = CONFIG_DEFAULTS if self._email and self._password: # Save the configuration locally to pull later on config['email'] = self._email config['password'] = str(obfuscate(self._password, 'store')) self._log.debug("Caching authentication in config file") json.dump(config, open(CONFIG_FILE, 'w'), indent=4, separators=(',', ': ')) else: # Load the config file and override the class config = json.load(open(CONFIG_FILE)) if config.get('py2', PY2) != PY2: raise Exception("Python versions have changed. Please run `setup` again to reconfigure the client.") if config['email'] and config['password']: self._email = config['email'] self._password = obfuscate(str(config['password']), 'fetch') self._log.debug("Loaded authentication from config file") def _session_check(self): """Attempt to authenticate the user through a session file. This process is done to avoid having to authenticate the user every single time. It uses a session file that is saved when a valid session is captured and then reused. Because sessions can expire, we need to test the session prior to calling the user authenticated. Right now that is done with a test string found in an unauthenticated session. This approach is not an ideal method, but it works. """ if not os.path.exists(SESSION_FILE): self._log.debug("Session file does not exist") return False with open(SESSION_FILE, 'rb') as f: cookies = requests.utils.cookiejar_from_dict(pickle.load(f)) self._session.cookies = cookies self._log.debug("Loaded cookies from session file") response = self._session.get(url=self.TEST_URL, headers=self.HEADERS) if self.TEST_KEY in str(response.content): self._log.debug("Session file appears invalid") return False self._is_authenticated = True self._process_state() return True def _logger(self): """Create a logger to be used between processes. :returns: Logging instance. """ logger = logging.getLogger(self.NAME) logger.setLevel(self.LOG_LEVEL) shandler = logging.StreamHandler(sys.stdout) fmt = '\033[1;32m%(levelname)-5s %(module)s:%(funcName)s():' fmt += '%(lineno)d %(asctime)s\033[0m| %(message)s' shandler.setFormatter(logging.Formatter(fmt)) logger.addHandler(shandler) return logger def set_log_level(self, level): """Override the default log level of the class""" if level == 'info': level = logging.INFO if level == 'debug': level = logging.DEBUG if level == 'error': level = logging.ERROR self._log.setLevel(level) def _process_state(self): """Process the application state configuration. Google Alerts manages the account information and alert data through some custom state configuration. Not all values have been completely enumerated. """ self._log.debug("Capturing state from the request") response = self._session.get(url=self.ALERTS_URL, headers=self.HEADERS) soup = BeautifulSoup(response.content, "html.parser") p = re.compile('window.STATE=(.*);') for i in soup.findAll('script', {'src': False}): if not p.search(i.string): continue try: match = p.search(i.string) state = json.loads(match.group(0)[13:-6]) if state != "": self._state = state self._log.debug("State value set: %s" % self._state) except Exception as e: raise StateParseFailure( 'Google has changed their core protocol and a new parser must be built. ' + 'Please file a bug at https://github.com/9b/google-alerts/issues.' ) return self._state def _build_payload(self, term, options): if 'delivery' not in options: raise InvalidConfig("`delivery` is required in options.") region = options.get('region', 'US') language = options.get('language', 'en') imatch_type = {v: k for k, v in self.MONITOR_MATCH_TYPE.items()} monitor_match = imatch_type[options.get('monitor_match', 'ALL')] ialert_freq = {v: k for k, v in self.ALERT_FREQ.items()} freq_option = options.get('alert_frequency', 'AT_MOST_ONCE_A_DAY') freq_option = ialert_freq[freq_option] if 'alert_frequency' not in options: options['alert_frequency'] = 'AT_MOST_ONCE_A_DAY' if options.get('exact', False): term = "\"%s\"" % term if options['delivery'] == 'RSS': payload = [None, [None, None, None, [None, term, "com", [None, language, region], None, None, None, 0, 1], None, monitor_match, [[None, 2, "", [], 1, "en-US", None, None, None, None, None, "0", None, None, self._state[2]]]]] else: if options['alert_frequency'] == 'AT_MOST_ONCE_A_DAY': payload = [None, [None, None, None, [None, term, "com", [None, language, region], None, None, None, 0, 1], None, monitor_match, [[None, 1, self._email, [None, None, 3], freq_option, "en-US", None, None, None, None, None, "0", None, None, self._state[2]]]]] elif options['alert_frequency'] == 'AS_IT_HAPPENS': payload = [None, [None, None, None, [None, term, "com", [None, language, region], None, None, None, 0, 1], None, monitor_match, [[None, 1, self._email, [], freq_option, "en-US", None, None, None, None, None, "0", None, None, self._state[2]]]]] elif options['alert_frequency'] == 'AT_MOST_ONCE_A_WEEK': payload = [None, [None, None, None, [None, term, "com", [None, language, region], None, None, None, 0, 1], None, monitor_match, [[None, 1, self._email, [None, None, 0, 3], freq_option, "en-US", None, None, None, None, None, "0", None, None, self._state[2]]]]] if options.get('action') == 'MODIFY': payload.insert(1, options.get('monitor_id')) if 'rss_id' in options: payload[2][6][0][11] = options['rss_id'].split('/')[-1] return payload def authenticate(self): """Authenticate the user and setup our state.""" valid = self._session_check() if self._is_authenticated and valid: self._log.debug("[!] User has already authenticated") return init = self._session.get(url=self.LOGIN_URL, headers=self.HEADERS) soup = BeautifulSoup(init.content, "html.parser") soup_login = soup.find('form').find_all('input') post_data = dict() for u in soup_login: if u.has_attr('name') and u.has_attr('value'): post_data[u['name']] = u['value'] post_data['Email'] = self._email post_data['Passwd'] = self._password response = self._session.post(url=self.AUTH_URL, data=post_data, headers=self.HEADERS) if self.CAPTCHA_KEY in str(response.content): raise AccountCaptcha('Google is forcing a CAPTCHA. To get around this issue, run the google-alerts with the seed option to open an interactive authentication session. Once authenticated, this module will cache your session and load that in the future') cookies = [x.name for x in response.cookies] if 'SIDCC' not in cookies: raise InvalidCredentials("Email or password was incorrect.") with open(SESSION_FILE, 'wb') as f: cookies = requests.utils.dict_from_cookiejar(self._session.cookies) pickle.dump(cookies, f, protocol=2) self._log.debug("Saved session to disk for future reference") self._log.debug("User successfully authenticated") self._is_authenticated = True self._process_state() return def list(self, term=None): """List alerts configured for the account. At the time of processing, here are several state examples: - ['062bc676ab9e9d9b:5a96b75728adb9d4:com:en:US', [None, None, ['email_aih_all', 'com', ['en', 'US'], None, None, None, False], None, 2, [[1, '[email protected]', [], 1, 'en-US', 1, None, None, None, None, '7290377213681086747', None, None, 'AB2Xq4g1vxP5nJCT4SVMp8-8CeYubB7G0yQdZnM']]], '06449491676132715360'] - ['062bc676ab9e9d9b:eb34fff1681232ae:com:en:US', [None, None, ['email_aih_best', 'com', ['en', 'US'], None, None, None, False], None, 3, [[1, '[email protected]', [], 1, 'en-US', 1, None, None, None, None, '11048899972761343896', None, None, 'AB2Xq4ibeyRSs4e6CQEjGTYWRyQgHftJgjkGmdE']]], '06449491676132715360'] - ['062bc676ab9e9d9b:029a12ab092e4d48:com:en:US', [None, None, ['email_d_all', 'com', ['en', 'US'], None, None, None, False], None, 2, [[1, '[email protected]', [None, 18], 2, 'en-US', 1, None, None, None, None, '13677540305540568185', None, None, 'AB2Xq4iqyPDNCX_G_ZahmtXr3Ev1Xxk71J3A9o8']]], '06449491676132715360'] - ['062bc676ab9e9d9b:be633f8e2d769ed1:com:en:US', [None, None, ['email_d_best', 'com', ['en', 'US'], None, None, None, False], None, 3, [[1, '[email protected]', [None, 18], 2, 'en-US', 1, None, None, None, None, '3165773263851675895', None, None, 'AB2Xq4gAyl3SR-5AKh3NstCHFf3I5tOCH_8Te98']]], '06449491676132715360'] - ['062bc676ab9e9d9b:4064fca73997bea1:com:en:US', [None, None, ['email_w_all', 'com', ['en', 'US'], None, None, None, False], None, 2, [[1, '[email protected]', [None, 18, 0], 3, 'en-US', 1, None, None, None, None, '1277526588871069988', None, None, 'AB2Xq4jNqRCDJaqIvPfZTI6Sos2MMPb5q_6jS14']]], '06449491676132715360'] - ['062bc676ab9e9d9b:ed3adf6fd0968cb0:com:en:US', [None, None, ['email_w_best', 'com', ['en', 'US'], None, None, None, False], None, 3, [[1, '[email protected]', [None, 18, 0], 3, 'en-US', 1, None, None, None, None, '11943490843312281977', None, None, 'AB2Xq4gvnjg6s07wCxTs4Ag8_6uOC0u9-7Aiu8E']]], '06449491676132715360'] - ['062bc676ab9e9d9b:a92eace4d0488209:com:en:US', [None, None, ['rss_aih_best', 'com', ['en', 'US'], None, None, None, False], None, 3, [[2, '', [], 1, 'en-US', 1, None, None, None, None, '10457927733922767031', None, None, 'AB2Xq4jZ1IPZLS44ZpaXYn8Fh46euu8_so_2k7k']]], '06449491676132715360'] - ['062bc676ab9e9d9b:ac4752c338e8c363:com:en:US', [None, None, ['rss_all', 'com', ['en', 'US'], None, None, None, False], None, 2, [[2, '', [], 1, 'en-US', 1, None, None, None, None, '17387577876633356534', None, None, 'AB2Xq4h1wQcVxLfb0s835KmJWdw7bfUzzwpjUrg']]], '06449491676132715360'] """ if not self._state: raise InvalidState("State was not properly obtained from the app") self._process_state() if not self._state[0]: self._log.info("No monitors have been created yet.") return list() monitors = list() try: for monitor in self._state[0][0]: obj = dict() obj['monitor_id'] = monitor[0] obj['user_id'] = monitor[-1] obj['term'] = monitor[1][2][0] if term and obj['term'] != term: continue obj['language'] = monitor[1][2][2][0] obj['region'] = monitor[1][2][2][1] obj['delivery'] = self.DELIVERY[monitor[1][5][0][0]] obj['match_type'] = self.MONITOR_MATCH_TYPE[monitor[1][4]] if obj['delivery'] == 'MAIL': obj['alert_frequency'] = self.ALERT_FREQ[monitor[1][5][0][3]] obj['email_address'] = monitor[1][5][0][1] else: rss_id = monitor[1][5][0][10] url = "https://google.com/alerts/feeds/{uid}/{fid}" obj['rss_link'] = url.format(uid=obj['user_id'], fid=rss_id) monitors.append(obj) except Exception as e: raise StateParseFailure("Observed state differs from parser. Please file a bug at https://github.com/9b/google-alerts/issues.") return monitors def create(self, term, options): """Create a monitor using passed configuration.""" if not self._state: raise InvalidState("State was not properly obtained from the app") options['action'] = 'CREATE' payload = self._build_payload(term, options) url = self.ALERTS_CREATE_URL.format(requestX=self._state[2]) self._log.debug("Creating alert using: %s" % url) params = json.dumps(payload, separators=(',', ':')) data = {'params': params} response = self._session.post(url, data=data, headers=self.HEADERS) if response.status_code != 200: raise ActionError("Failed to create monitor: %s" % response.content) if options.get('exact', False): term = "\"%s\"" % term return self.list(term) def modify(self, monitor_id, options): """Create a monitor using passed configuration.""" if not self._state: raise InvalidState("State was not properly obtained from the app") monitors = self.list() # Get the latest set of monitors obj = None for monitor in monitors: if monitor_id != monitor['monitor_id']: continue obj = monitor if not monitor_id: raise MonitorNotFound("No monitor was found with that term.") options['action'] = 'MODIFY' options.update(obj) payload = self._build_payload(obj['term'], options) url = self.ALERTS_MODIFY_URL.format(requestX=self._state[2]) self._log.debug("Modifying alert using: %s" % url) params = json.dumps(payload, separators=(',', ':')) data = {'params': params} response = self._session.post(url, data=data, headers=self.HEADERS) if response.status_code != 200: raise ActionError("Failed to create monitor: %s" % response.content) return self.list() def delete(self, monitor_id): """Delete a monitor by ID.""" if not self._state: raise InvalidState("State was not properly obtained from the app") monitors = self.list() # Get the latest set of monitors bit = None for monitor in monitors: if monitor_id != monitor['monitor_id']: continue bit = monitor['monitor_id'] if not bit: raise MonitorNotFound("No monitor was found with that term.") url = self.ALERTS_DELETE_URL.format(requestX=self._state[2]) self._log.debug("Deleting alert using: %s" % url) payload = [None, monitor_id] params = json.dumps(payload, separators=(',', ':')) data = {'params': params} response = self._session.post(url, data=data, headers=self.HEADERS) if response.status_code != 200: raise ActionError("Failed to delete by ID: %s" % response.content) return True def delete_by_term(self, term): """Delete an alert by term.""" if not self._state: raise InvalidState("State was not properly obtained from the app") monitors = self.list() # Get the latest set of monitors monitor_id = None for monitor in monitors: if term != monitor['term']: continue monitor_id = monitor['monitor_id'] if not monitor_id: raise MonitorNotFound("No monitor was found with that term.") url = self.ALERTS_DELETE_URL.format(requestX=self._state[2]) self._log.debug("Deleting alert using: %s" % url) payload = [None, monitor_id] params = json.dumps(payload, separators=(',', ':')) data = {'params': params} response = self._session.post(url, data=data, headers=self.HEADERS) if response.status_code != 200: raise ActionError("Failed to delete by term: %s" % response.content) return True
class GoogleAlerts: def __init__(self, email=None, password=None): pass def _config_bootstrap(self): '''Go through and establish the defaults on the file system. The approach here was stolen from the CLI tool provided with the module. Idea being that the user should not always need to provide a username and password in order to run the script. If the configuration file is already present with valid data, then lets use it. ''' pass def _session_check(self): '''Attempt to authenticate the user through a session file. This process is done to avoid having to authenticate the user every single time. It uses a session file that is saved when a valid session is captured and then reused. Because sessions can expire, we need to test the session prior to calling the user authenticated. Right now that is done with a test string found in an unauthenticated session. This approach is not an ideal method, but it works. ''' pass def _logger(self): '''Create a logger to be used between processes. :returns: Logging instance. ''' pass def set_log_level(self, level): '''Override the default log level of the class''' pass def _process_state(self): '''Process the application state configuration. Google Alerts manages the account information and alert data through some custom state configuration. Not all values have been completely enumerated. ''' pass def _build_payload(self, term, options): pass def authenticate(self): '''Authenticate the user and setup our state.''' pass def list(self, term=None): '''List alerts configured for the account. At the time of processing, here are several state examples: - ['062bc676ab9e9d9b:5a96b75728adb9d4:com:en:US', [None, None, ['email_aih_all', 'com', ['en', 'US'], None, None, None, False], None, 2, [[1, '[email protected]', [], 1, 'en-US', 1, None, None, None, None, '7290377213681086747', None, None, 'AB2Xq4g1vxP5nJCT4SVMp8-8CeYubB7G0yQdZnM']]], '06449491676132715360'] - ['062bc676ab9e9d9b:eb34fff1681232ae:com:en:US', [None, None, ['email_aih_best', 'com', ['en', 'US'], None, None, None, False], None, 3, [[1, '[email protected]', [], 1, 'en-US', 1, None, None, None, None, '11048899972761343896', None, None, 'AB2Xq4ibeyRSs4e6CQEjGTYWRyQgHftJgjkGmdE']]], '06449491676132715360'] - ['062bc676ab9e9d9b:029a12ab092e4d48:com:en:US', [None, None, ['email_d_all', 'com', ['en', 'US'], None, None, None, False], None, 2, [[1, '[email protected]', [None, 18], 2, 'en-US', 1, None, None, None, None, '13677540305540568185', None, None, 'AB2Xq4iqyPDNCX_G_ZahmtXr3Ev1Xxk71J3A9o8']]], '06449491676132715360'] - ['062bc676ab9e9d9b:be633f8e2d769ed1:com:en:US', [None, None, ['email_d_best', 'com', ['en', 'US'], None, None, None, False], None, 3, [[1, '[email protected]', [None, 18], 2, 'en-US', 1, None, None, None, None, '3165773263851675895', None, None, 'AB2Xq4gAyl3SR-5AKh3NstCHFf3I5tOCH_8Te98']]], '06449491676132715360'] - ['062bc676ab9e9d9b:4064fca73997bea1:com:en:US', [None, None, ['email_w_all', 'com', ['en', 'US'], None, None, None, False], None, 2, [[1, '[email protected]', [None, 18, 0], 3, 'en-US', 1, None, None, None, None, '1277526588871069988', None, None, 'AB2Xq4jNqRCDJaqIvPfZTI6Sos2MMPb5q_6jS14']]], '06449491676132715360'] - ['062bc676ab9e9d9b:ed3adf6fd0968cb0:com:en:US', [None, None, ['email_w_best', 'com', ['en', 'US'], None, None, None, False], None, 3, [[1, '[email protected]', [None, 18, 0], 3, 'en-US', 1, None, None, None, None, '11943490843312281977', None, None, 'AB2Xq4gvnjg6s07wCxTs4Ag8_6uOC0u9-7Aiu8E']]], '06449491676132715360'] - ['062bc676ab9e9d9b:a92eace4d0488209:com:en:US', [None, None, ['rss_aih_best', 'com', ['en', 'US'], None, None, None, False], None, 3, [[2, '', [], 1, 'en-US', 1, None, None, None, None, '10457927733922767031', None, None, 'AB2Xq4jZ1IPZLS44ZpaXYn8Fh46euu8_so_2k7k']]], '06449491676132715360'] - ['062bc676ab9e9d9b:ac4752c338e8c363:com:en:US', [None, None, ['rss_all', 'com', ['en', 'US'], None, None, None, False], None, 2, [[2, '', [], 1, 'en-US', 1, None, None, None, None, '17387577876633356534', None, None, 'AB2Xq4h1wQcVxLfb0s835KmJWdw7bfUzzwpjUrg']]], '06449491676132715360'] ''' pass def create(self, term, options): '''Create a monitor using passed configuration.''' pass def modify(self, monitor_id, options): '''Create a monitor using passed configuration.''' pass def delete(self, monitor_id): '''Delete a monitor by ID.''' pass def delete_by_term(self, term): '''Delete an alert by term.''' pass
14
11
24
1
20
3
5
0.15
0
14
7
0
13
6
13
13
358
23
294
100
280
44
251
96
237
10
0
3
65
1,581
9b/google-alerts
9b_google-alerts/google_alerts/__init__.py
google_alerts.InvalidConfig
class InvalidConfig(Exception): """Exception for invalid configurations.""" pass
class InvalidConfig(Exception): '''Exception for invalid configurations.''' pass
1
1
0
0
0
0
0
0.5
1
0
0
0
0
0
0
10
3
0
2
1
1
1
2
1
1
0
3
0
0
1,582
9b/google-alerts
9b_google-alerts/google_alerts/__init__.py
google_alerts.AccountCaptcha
class AccountCaptcha(Exception): """Exception for account CAPTCHA.""" pass
class AccountCaptcha(Exception): '''Exception for account CAPTCHA.''' pass
1
1
0
0
0
0
0
0.5
1
0
0
0
0
0
0
10
3
0
2
1
1
1
2
1
1
0
3
0
0
1,583
9b/google-alerts
9b_google-alerts/google_alerts/__init__.py
google_alerts.InvalidCredentials
class InvalidCredentials(Exception): """Exception for invalid credentials.""" pass
class InvalidCredentials(Exception): '''Exception for invalid credentials.''' pass
1
1
0
0
0
0
0
0.5
1
0
0
0
0
0
0
10
3
0
2
1
1
1
2
1
1
0
3
0
0
1,584
9b/google-alerts
9b_google-alerts/google_alerts/__init__.py
google_alerts.ActionError
class ActionError(Exception): """Exception for generic failures on action.""" pass
class ActionError(Exception): '''Exception for generic failures on action.''' pass
1
1
0
0
0
0
0
0.5
1
0
0
0
0
0
0
10
3
0
2
1
1
1
2
1
1
0
3
0
0
1,585
9b/google-alerts
9b_google-alerts/google_alerts/__init__.py
google_alerts.StateParseFailure
class StateParseFailure(Exception): """Exception for failing to parse state.""" pass
class StateParseFailure(Exception): '''Exception for failing to parse state.''' pass
1
1
0
0
0
0
0
0.5
1
0
0
0
0
0
0
10
3
0
2
1
1
1
2
1
1
0
3
0
0
1,586
9seconds/pep3134
9seconds_pep3134/setup.py
setup.PyTest
class PyTest(test): user_options = [('pytest-args=', 'a', "Arguments to pass to py.test")] def initialize_options(self): test.initialize_options(self) self.pytest_args = None # pylint: disable=W0201 def finalize_options(self): test.finalize_options(self) self.test_args = [] # pylint: disable=W0201 self.test_suite = True # pylint: disable=W0201 def run_tests(self): # import here, cause outside the eggs aren't loaded import pytest import sys errno = pytest.main(self.pytest_args) sys.exit(errno)
class PyTest(test): def initialize_options(self): pass def finalize_options(self): pass def run_tests(self): pass
4
0
4
0
4
1
1
0.29
1
0
0
0
3
3
3
3
18
3
14
11
8
4
14
11
8
1
1
0
3
1,587
9seconds/pep3134
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/9seconds_pep3134/test_pep3134.py
test_pep3134.test_raise_custom.CustomException
class CustomException(Exception): def parameter(self): return 1
class CustomException(Exception): def parameter(self): pass
2
0
2
0
2
0
1
0
1
0
0
0
1
0
1
11
4
1
3
2
1
0
3
2
1
1
3
0
1
1,588
9seconds/pep3134
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/9seconds_pep3134/pep3134/utils.py
pep3134.utils.construct_exc_class.ProxyException
class ProxyException(cls, BaseException): __pep3134__ = True @property def __traceback__(self): if self.__fixed_traceback__: return self.__fixed_traceback__ current_exc, current_tb = sys.exc_info()[1:] if current_exc is self: return current_tb def __init__(self, instance=None): # pylint: disable=W0231 self.__original_exception__ = instance self.__fixed_traceback__ = None def __getattr__(self, item): return getattr(self.__original_exception__, item) def __repr__(self): return repr(self.__original_exception__) def __str__(self): return str(self.__original_exception__) def with_traceback(self, traceback): instance = copy.copy(self) instance.__fixed_traceback__ = traceback return instance
class ProxyException(cls, BaseException): @property def __traceback__(self): pass def __init__(self, instance=None): pass def __getattr__(self, item): pass def __repr__(self): pass def __str__(self): pass def with_traceback(self, traceback): pass
8
0
3
0
3
0
1
0.05
2
1
0
0
6
2
6
15
29
7
22
13
14
1
21
12
14
3
2
1
8
1,589
9wfox/tornadoweb
9wfox_tornadoweb/tornadoweb/__init__.py
tornadoweb.ACLGroupNode
class ACLGroupNode(ACLNode): def __init__(self, intro=None, category=None): (filename,line_number,function_name,text)=traceback.extract_stack()[-2] self.name = '{0}.{1}'.format(filename,text[:text.find('=')].strip()) self.name = self.name.replace(os.getcwd(),'') self.name = self.name.replace('/','.') self.name = self.name[1:].replace('.py','') self.intro = intro or name self.category = category self.handlers = [] def append(self, handler): self.handlers.append(handler) def fetch_module(self, module): ACL[CATEGORY][self.name] = self for k, v in getmembers(module, member_filter): self.append(v) v.__checkname__ = self.name v.check_access = check_access v.__needcheck__ = {'url':True} def fetch_handlers(self,*handlers): ACL[CATEGORY][self.name] = self for v in handlers: if not member_filter(v): continue self.append(v) v.__checkname__ = self.name v.check_access = check_access v.__needcheck__ = {'url':True}
class ACLGroupNode(ACLNode): def __init__(self, intro=None, category=None): pass def append(self, handler): pass def fetch_module(self, module): pass def fetch_handlers(self,*handlers): pass
5
0
7
0
7
0
2
0
1
0
0
0
4
4
4
5
31
4
27
12
22
0
28
12
23
3
2
2
7
1,590
9wfox/tornadoweb
9wfox_tornadoweb/tornadoweb/__init__.py
tornadoweb.ACLNode
class ACLNode(object): def __init__(self, handler): self.name = '{0}.{1}'.format(handler.__module__, handler.__name__) self.intro = handler.__doc__ or self.name self.handler = handler
class ACLNode(object): def __init__(self, handler): pass
2
0
4
0
4
0
1
0
1
0
0
1
1
3
1
1
5
0
5
5
3
0
5
5
3
1
1
0
1
1,591
9wfox/tornadoweb
9wfox_tornadoweb/tornadoweb/__init__.py
tornadoweb.MasterRoleNeed
class MasterRoleNeed(RoleNeed): def __init__(self): self.name = 'master' self.intro = 'Super'
class MasterRoleNeed(RoleNeed): def __init__(self): pass
2
0
3
0
3
0
1
0
1
0
0
0
1
2
1
3
4
0
4
4
2
0
4
4
2
1
2
0
1
1,592
9wfox/tornadoweb
9wfox_tornadoweb/tornadoweb/__init__.py
tornadoweb.RoleNeed
class RoleNeed(object): def __init__(self, name, intro=None, nodes=set(), ctx_vals={}): self.name = name self.intro = intro or name self.nodes = nodes self.ctx_vals = ctx_vals def require(self, **kwargs): def actual(handler): assert(issubclass(handler, tornado.web.RequestHandler)) handler.__needcheck__ = kwargs category = kwargs.get('category',CATEGORY) if not ACL.get(category,None):ACL[category] = {} groupnode = kwargs.get('group', None) if groupnode: ACL[category][groupnode.name] = groupnode groupnode.append(handler) handler.__checkname__ = groupnode.name else: aclnode = ACLNode(handler) ACL[category][aclnode.name] = aclnode handler.__checkname__ = aclnode.name handler.check_access = check_access return handler return actual
class RoleNeed(object): def __init__(self, name, intro=None, nodes=set(), ctx_vals={}): pass def require(self, **kwargs): pass def actual(handler): pass
4
0
17
4
13
0
2
0
1
3
1
1
2
4
2
2
32
8
24
11
20
0
24
11
20
3
1
1
5
1,593
9wfox/tornadoweb
9wfox_tornadoweb/tornadoweb/app.py
tornadoweb.app.Application
class Application(object): port = property(lambda self: self._port) handlers = property(lambda self: self._handlers) processes = 1 settings = property(lambda self: __conf__.__dict__) def __init__(self, port = None, callback = None): self._port = port or __conf__.PORT self._callback = callback self._handlers = self._get_handlers() self._webapp = self._get_webapp() def _get_handlers(self): members = {} for d in __conf__.ACTION_DIR_NAME: members.update(get_members(d, None, lambda m: isclass(m) and issubclass(m, RequestHandler) and hasattr(m, "__urls__") and m.__urls__)) handlers = [(pattern, order, h) for h in members.values() for pattern, order in h.__urls__] try: api_version = __conf__.API_VERSION except Exception as e: api_version = '' handlers = [(api_version + pattern, handler) for pattern, _, handler in handlers] handlers.append((r'^/upload/(.*?)$', tornado.web.StaticFileHandler, {"path":"upload", "default_filename":"index.html"})) from .web import BaseHandler handlers.append((r'^(.*?)$', BaseHandler)) return handlers def _get_webapp(self): settings = { "PORT" : self._port, "static_path" : app_path(__conf__.STATIC_DIR_NAME), "template_path" : app_path(__conf__.TEMPLATE_DIR_NAME), "debug" : __conf__.DEBUG, "cookie_secret" : __conf__.COOKIE_SECRET } self.settings.update(settings) return WebApplication(self._handlers, **settings) def _run_server(self): try: if __conf__.DEBUG: self._webapp.listen(self._port) else: server = HTTPServer(self._webapp) server.bind(self._port) server.start(0) IOLoop.current().start() except KeyboardInterrupt: print ("exit ...") def run(self): if self._callback: self._callback(self) self._run_server()
class Application(object): def __init__(self, port = None, callback = None): pass def _get_handlers(self): pass def _get_webapp(self): pass def _run_server(self): pass def run(self): pass
6
0
11
2
9
0
2
0
1
7
1
0
5
4
5
5
68
18
50
23
43
0
42
21
35
3
1
2
10
1,594
9wfox/tornadoweb
9wfox_tornadoweb/tornadoweb/config.py
tornadoweb.config.ConfigLoader
class ConfigLoader(object): @staticmethod def load(config = None): if config: pys = map(app_path, (config, )) else: pys = map(app_path, ("settings.py", )) dct = {} module = ModuleType("__conf__") for py in pys: scope = {} with open(py,'r') as f: body = f.read() exec(body, scope) for k, v in scope.items(): if k.startswith("__"): continue setattr(module, k, v) __builtin__.__conf__ = module
class ConfigLoader(object): @staticmethod def load(config = None): pass
3
0
20
4
16
0
5
0
1
1
0
0
0
0
1
1
23
5
18
11
15
0
17
9
15
5
1
4
5
1,595
9wfox/tornadoweb
9wfox_tornadoweb/tornadoweb/web.py
tornadoweb.web.BaseHandler
class BaseHandler(RequestHandler): """ Torando RequestHandler http://www.tornadoweb.org/ """ __UID__ = "__UID__" __USERNAME__ = "__USERNAME__" def get(self, *args, **kwargs): self.send_error(404) def post(self, *args, **kwargs): self.send_error(404) def get_current_user(self): return self.get_secure_cookie(self.__USERNAME__)
class BaseHandler(RequestHandler): ''' Torando RequestHandler http://www.tornadoweb.org/ ''' def get(self, *args, **kwargs): pass def post(self, *args, **kwargs): pass def get_current_user(self): pass
4
1
2
0
2
0
1
0.44
1
0
0
0
3
0
3
84
18
5
9
6
5
4
9
6
5
1
2
0
3
1,596
9wfox/tornadoweb
9wfox_tornadoweb/tornadoweb/project/logic/utility.py
logic.utility.LoginedRequestHandler
class LoginedRequestHandler(BaseHandler): uid = property(lambda self: (self.get_secure_cookie("__UID__") or '').decode()) username = property(lambda self: (self.get_secure_cookie("__USERNAME__") or '').decode()) def set_default_headers(self): self.set_header("Access-Control-Allow-Origin", "*") self.set_header("Access-Control-Allow-Headers", "x-requested-with") self.set_header('Access-Control-Allow-Methods', 'POST, GET') def options(self, *args, **kwargs): self.set_header("Access-Control-Allow-Origin", "*") self.set_header("Access-Control-Allow-Headers", "x-requested-with") self.set_header('Access-Control-Allow-Methods', 'POST, GET') def prepare(self): """ REQUEST BEFORE HOOK """ if not self.uid: self.send_error(403) # TODO ADD SELF ACCESS def on_finish(self): """ REQUEST FINISH HOOK """ pass
class LoginedRequestHandler(BaseHandler): def set_default_headers(self): pass def options(self, *args, **kwargs): pass def prepare(self): ''' REQUEST BEFORE HOOK ''' pass def on_finish(self): ''' REQUEST FINISH HOOK ''' pass
5
2
5
0
3
2
1
0.44
1
0
0
1
4
0
4
4
30
7
16
7
11
7
16
7
11
2
1
1
5
1,597
9wfox/tornadoweb
9wfox_tornadoweb/tornadoweb/project/action/user.py
action.user.LogoutHandler
class LogoutHandler(LoginedRequestHandler): def get(self): self.clear_cookie("__UID__") self.clear_cookie("__USERNAME__") self.write(dict(status = True, msg = "登出成功"))
class LogoutHandler(LoginedRequestHandler): def get(self): pass
2
0
4
0
4
0
1
0
1
1
0
0
1
0
1
5
5
0
5
2
3
0
5
2
3
1
2
0
1
1,598
9wfox/tornadoweb
9wfox_tornadoweb/tornadoweb/project/action/user.py
action.user.LoginHandler
class LoginHandler(BaseHandler): def post(self): username = self.get_argument('username') password = password_md5(self.get_argument('password')) # TODO LOGIN LOGIC self.set_secure_cookie("__UID__", "admin") self.set_secure_cookie("__USERNAME__", "admin") self.write(dict(status = True, msg = "登陆成功"))
class LoginHandler(BaseHandler): def post(self): pass
2
0
8
1
6
1
1
0.14
1
1
0
0
1
0
1
1
9
1
7
4
5
1
7
4
5
1
1
0
1
1,599
AASHE/python-membersuite-api-client
AASHE_python-membersuite-api-client/membersuite_api_client/mixins.py
membersuite_api_client.mixins.ChunkQueryMixin
class ChunkQueryMixin(object): """ A mixin for API client service classes that makes it easy to consistently request multiple queries from a MemberSuite endpoint. Membersuite will often time out on big queries, so this allows us to break it up into smaller requests. """ def get_long_query(self, base_object_query, limit_to=100, max_calls=None, start_record=0, verbose=False): """ Takes a base query for all objects and recursively requests them :param str base_object_query: the base query to be executed :param int limit_to: how many rows to query for in each chunk :param int max_calls: the max calls(chunks to request) None is infinite :param int start_record: the first record to return from the query :param bool verbose: print progress to stdout :return: a list of Organization objects """ if verbose: print(base_object_query) record_index = start_record result = run_object_query(self.client, base_object_query, record_index, limit_to, verbose) obj_search_result = (result['body']["ExecuteMSQLResult"]["ResultValue"] ["ObjectSearchResult"]) if obj_search_result is not None: search_results = obj_search_result["Objects"] else: return [] if search_results is None: return [] result_set = search_results["MemberSuiteObject"] all_objects = self.result_to_models(result) call_count = 1 """ continue to run queries as long as we - don't exceed the call call_count - don't see results that are less than the limited length (the end) """ while call_count != max_calls and len(result_set) >= limit_to: record_index += len(result_set) # should be `limit_to` result = run_object_query(self.client, base_object_query, record_index, limit_to, verbose) obj_search_result = (result['body']["ExecuteMSQLResult"] ["ResultValue"]["ObjectSearchResult"]) if obj_search_result is not None: search_results = obj_search_result["Objects"] else: search_results = None if search_results is None: result_set = [] else: result_set = search_results["MemberSuiteObject"] all_objects += self.result_to_models(result) call_count += 1 return all_objects def result_to_models(self, result): """ this is the 'transorm' part of ETL: converts the result of the SQL to Models """ mysql_result = result['body']['ExecuteMSQLResult'] if not mysql_result['Errors']: obj_result = mysql_result['ResultValue']['ObjectSearchResult'] if not obj_result['Objects']: return [] objects = obj_result['Objects']['MemberSuiteObject'] model_list = [] for obj in objects: model = self.ms_object_to_model(obj) model_list.append(model) return model_list else: raise ExecuteMSQLError(result)
class ChunkQueryMixin(object): ''' A mixin for API client service classes that makes it easy to consistently request multiple queries from a MemberSuite endpoint. Membersuite will often time out on big queries, so this allows us to break it up into smaller requests. ''' def get_long_query(self, base_object_query, limit_to=100, max_calls=None, start_record=0, verbose=False): ''' Takes a base query for all objects and recursively requests them :param str base_object_query: the base query to be executed :param int limit_to: how many rows to query for in each chunk :param int max_calls: the max calls(chunks to request) None is infinite :param int start_record: the first record to return from the query :param bool verbose: print progress to stdout :return: a list of Organization objects ''' pass def result_to_models(self, result): ''' this is the 'transorm' part of ETL: converts the result of the SQL to Models ''' pass
3
3
42
8
25
10
6
0.5
1
1
1
5
2
0
2
2
93
19
50
17
46
25
41
16
38
7
1
2
11