code
stringlengths
1
5.19M
package
stringlengths
1
81
path
stringlengths
9
304
filename
stringlengths
4
145
from decimal import Decimal import pytest from lxml.html import fromstring from price_parser import Price from zyte_parsers.price import extract_price @pytest.mark.parametrize( ["html", "currency_hint", "expected"], [ ("<p></p>", None, Price(None, None, None)), ("<p>23.5</p>", None, Price(Decimal(23.5), None, "23.5")), ("<p>$23.5</p>", None, Price(Decimal(23.5), "$", "23.5")), ("<p>23.5</p>", "USD", Price(Decimal(23.5), "USD", "23.5")), ("<p>$23.5</p>", "USD", Price(Decimal(23.5), "$", "23.5")), ("<p>£23.5</p>", "USD", Price(Decimal(23.5), "£", "23.5")), ("<p>23.5</p>", "<b>USD</b>", Price(Decimal(23.5), "USD", "23.5")), ("<p>23.5</p>", fromstring("<b>USD</b>"), Price(Decimal(23.5), "USD", "23.5")), ], ) def test_price_simple(html, currency_hint, expected): result = extract_price(fromstring(html), currency_hint=currency_hint) assert result == expected
zyte-parsers
/zyte-parsers-0.3.0.tar.gz/zyte-parsers-0.3.0/tests/test_price.py
test_price.py
from pathlib import Path TEST_DATA_ROOT = Path(__file__).parent / "data"
zyte-parsers
/zyte-parsers-0.3.0.tar.gz/zyte-parsers-0.3.0/tests/utils.py
utils.py
import json from typing import Optional, Tuple import pytest from lxml.html import fromstring from tests.utils import TEST_DATA_ROOT from zyte_parsers.breadcrumbs import ( Breadcrumb, _parse_breadcrumb_name, extract_breadcrumbs, ) @pytest.mark.parametrize( ["name", "expected"], [ (None, (None, None, None)), ("", (None, None, None)), (" ", (None, None, None)), (">", (">", None, None)), ("|", ("|", None, None)), ("->", ("->", None, None)), (" > ", (">", None, None)), (" >>> ", (">>>", None, None)), ("name", (None, "name", None)), ("some name", (None, "some name", None)), (" some name ", (None, "some name", None)), (" > some name ", (">", "some name", None)), (" >> some name ", (">>", "some name", None)), (" >some name ", (None, ">some name", None)), (" some name > ", (None, "some name", ">")), (" some name >> ", (None, "some name", ">>")), ("> some name >> ", (">", "some name", ">>")), ("> > some name > >> ", (">", "> some name >", ">>")), ("> >> ", (">", None, ">>")), ("> > >", (">", ">", ">")), ], ) def test_parsing_breadcrumbs_name(name, expected): result = _parse_breadcrumb_name(name) assert result == expected @pytest.mark.parametrize( "item", json.loads( (TEST_DATA_ROOT / "breadcrumb_items_extract.json").read_text(encoding="utf8") ), ids=lambda item: f"[{item['snippet_path']}] - {item['base_url']}", ) def test_extract_breadcrumbs(item): def print_breadcrumbs(breadcrumbs: Optional[Tuple[Breadcrumb, ...]]) -> None: if breadcrumbs is None: print("Breadcrumbs were not extracted") else: for b_item in breadcrumbs: print(b_item) if item.get("xfail"): pytest.xfail(item["xfail"]) snippets_dir = TEST_DATA_ROOT / "breadcrumb_items_snippets" snippet_filename = item["snippet_path"] html = (snippets_dir / snippet_filename).read_text("utf8") node = fromstring(html) result = extract_breadcrumbs(node, base_url=item["base_url"]) expected = tuple(Breadcrumb(**d) for d in item["expected"]) print("Expected:") print_breadcrumbs(expected) print("Result:") print_breadcrumbs(result) assert expected == result
zyte-parsers
/zyte-parsers-0.3.0.tar.gz/zyte-parsers-0.3.0/tests/test_breadcrumbs.py
test_breadcrumbs.py
import json import pytest from lxml.html import fromstring from tests.utils import TEST_DATA_ROOT from zyte_parsers.brand import extract_brand_name def test_extract_brand_simple(): root = fromstring( '<div id="brand">simple brand</div>' '<div id="wrapper">' '<img id="img-alt" alt="my alt brand" title="foo" src="image-alt.png"/>' '<IMG id="img-title" title="my title brand" src="image-title.png"/>' '<img id="img-bare" src="image-bare.png"/>' '<img id="img-long" alt="very LOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOONG brand" title="short brand"/>' "</div>" ) def exa(xpath): return extract_brand_name(root.xpath(xpath)[0], search_depth=2) assert exa('//div[@id="brand"]') == "simple brand" assert exa('//img[@id="img-alt"]') == "my alt brand" assert exa('//img[@id="img-title"]') == "my title brand" assert exa('//img[@id="img-bare"]') is None assert exa('//div[@id="wrapper"]') == "my alt brand" assert exa('//img[@id="img-long"]') == "short brand" @pytest.mark.parametrize( "item", json.loads((TEST_DATA_ROOT / "brand_values.json").read_text(encoding="utf8")), ) def test_extract_brand(item): if item.get("xfail"): pytest.xfail(item["xfail"]) brand_name = extract_brand_name(fromstring(item["html"]), search_depth=2) assert brand_name == item["value"]
zyte-parsers
/zyte-parsers-0.3.0.tar.gz/zyte-parsers-0.3.0/tests/test_brand.py
test_brand.py
from distutils.core import setup setup(name="zyte-scrapycloud-cli", version="0.0.0",classifiers=['Development Status :: 1 - Planning'])
zyte-scrapycloud-cli
/zyte-scrapycloud-cli-0.0.0.tar.gz/zyte-scrapycloud-cli-0.0.0/setup.py
setup.py
## Zyte-spmstats It is a small python module for interacting with Zyte Smart Proxy Manager Stats API ### Documentation [Zyte SPM Stats API Documentation](https://docs.zyte.com/smart-proxy-manager/stats.html) ### Installation `pip install zyte-spmstats` ### Usage 1. For a single domain/netloc: `python -m zyte.spmstats <ORG-API> amazon.com 2022-06-15T18:50:00 2022-06-17T23:00` Output: ` { "failed": 0, "clean": 29, "time_gte": "2022-06-10T18:55:00", "concurrency": 0, "domain": "amazon.com", "traffic": 3865060, "total_time": 1945 }, ` 2. For a multiple domain/netloc: `python -m zyte.spmstats <ORG-API> amazon.com,pharmamarket.be 2022-06-15T18:50:00 2022-06-17T23:00` Output: `"results": [ { "failed": 88, "clean": 230, "time_gte": "2022-06-13T07:50:00", "concurrency": 1, "domain": "pharmamarket.be", "traffic": 3690976, "total_time": 2386 }, { "failed": 224, "clean": 8497, "time_gte": "2022-06-16T01:45:00", "concurrency": 80, "domain": "amazon.com", "traffic": 2280046474, "total_time": 1373 }]`
zyte-spmstats
/zyte-spmstats-1.0.0.tar.gz/zyte-spmstats-1.0.0/README.md
README.md
import json import requests import sys def stats(): try: org_api = sys.argv[1] netlocs = sys.argv[2] start_date = sys.argv[3] end_date = sys.argv[4] url = f"https://crawlera-stats.scrapinghub.com/stats/?netlocs={netlocs}&start_date={start_date}&end_date={end_date}&groupby=day&domain-wise=true" payload = {} response = requests.request("GET", url, auth=(org_api, 'x'), data=payload) response = json.loads(response.text) return print(json.dumps(response, indent=3)) except IndexError: return print( "Please enter all the Arguments as given below: \npython -m zyte.spmstats <ORG-API> amazon.com " "2022-06-15T18:50:00 2022-06-17T23:00") if __name__ == '__main__': stats()
zyte-spmstats
/zyte-spmstats-1.0.0.tar.gz/zyte-spmstats-1.0.0/src/zyte/spmstats.py
spmstats.py
from distutils.core import setup setup(name="zyte", version="0.0.0",classifiers=['Development Status :: 1 - Planning'])
zyte
/zyte-0.0.0.tar.gz/zyte-0.0.0/setup.py
setup.py
from distutils.core import setup setup(name="zytesc", version="0.0.0",classifiers=['Development Status :: 1 - Planning'])
zytesc
/zytesc-0.0.0.tar.gz/zytesc-0.0.0/setup.py
setup.py
#!/usr/bin/env python import re import setuptools version = "1.0.3" setuptools.setup( name="zytestpip", version=version, author="bwz0328", author_email="[email protected]", description="This is the SDK for example.", long_description="", long_description_content_type="text/markdown", url="http://example.com", install_requires=[ 'requests!=2.9.0', 'lxml>=4.2.3', 'monotonic>=1.5', ], packages=setuptools.find_packages(exclude=("test")) )
zytestpip
/zytestpip-1.0.3.tar.gz/zytestpip-1.0.3/setup.py
setup.py
import inspect from functools import singledispatch from typing import Union, Callable, Tuple, Optional from zython import var from zython.operations.constraint import Constraint from zython.operations.operation import Operation from zython.var_par.array import ArrayMixin from zython.var_par.types import is_range, ZnSequence, get_type @singledispatch def _get_variable(seq) -> var: if is_range(seq): return var(int) assert False, f"{type(seq)} isn't supported, please use Sequence or Array here" @_get_variable.register(ArrayMixin) # TODO: newer versions of python support type evaluation from hints def _(seq: ArrayMixin): return var(seq.type) @_get_variable.register(list) @_get_variable.register(tuple) def _(seq: Union[list, tuple]): if seq: v = var(get_type(seq[0])) else: raise ValueError("empty sequences are not supported as constraint parameter") return v def _extract_func_var_and_op(seq: ZnSequence, func: Union[Constraint, Callable]) -> Tuple[Optional[var], Operation]: variable = None parameters = inspect.signature(func).parameters if len(parameters) > 1: raise ValueError("only functions and lambdas with one arguments are supported") elif len(parameters) == 1: variable = _get_variable(seq) variable._name, _ = dict(parameters).popitem() func_op = func(variable) else: func_op = func() return variable, func_op def get_iter_var_and_op(seq, func): iter_var = None if callable(func): iter_var, func = _extract_func_var_and_op(seq, func) return iter_var, func
zython
/operations/_iternal.py
_iternal.py
from typing import Union, Callable, Optional from zython.operations import _iternal from zython.operations._op_codes import _Op_code from zython.operations.constraint import Constraint from zython.operations.operation import Operation from zython.var_par.array import ArrayMixin from zython.var_par.types import ZnSequence def exists(seq: ZnSequence, func: Optional[Union["Constraint", Callable]] = None) -> Constraint: """ Specify constraint which should be true for `at least` one element in ``seq``. The method has the same signature as ``forall``. See Also -------- forall Examples -------- >>> import zython as zn >>> class MyModel(zn.Model): ... def __init__(self): ... self.a = zn.var(range(0, 10)) ... self.b = zn.var(range(0, 10)) ... self.c = zn.var(range(0, 10)) ... self.constraints = [zn.exists((self.a, self.b, self.c), lambda elem: elem > 0)] >>> model = MyModel() >>> result = model.solve_satisfy() >>> sorted((result["a"], result["b"], result["c"])) [0, 0, 1] """ iter_var, operation = _iternal.get_iter_var_and_op(seq, func) return Constraint.exists(seq, iter_var, operation) def forall(seq: ZnSequence, func: Optional[Union["Constraint", Callable]] = None) -> Constraint: """ Takes expression (that is, constraint) or function which return constraint and make them a single constraint which should be true for every element in the array. Parameters ---------- seq: range, array of var, or sequence (list or tuple) of var sequence to apply ``func`` func: Constraint or Callable, optional Constraint every element in seq should satisfy or function which returns such constraint. If function or lambda it should be with 0 or 1 arguments only. Returns ------- result: Constraint resulted constraint Examples -------- >>> import zython as zn >>> class MyModel(zn.Model): ... def __init__(self): ... self.a = zn.Array(zn.var(int), shape=3) ... self.constraints = [zn.forall(self.a, lambda elem: elem > 0)] >>> model = MyModel() >>> model.solve_satisfy() Solution(a=[1, 1, 1]) """ iter_var, operation = _iternal.get_iter_var_and_op(seq, func) return Constraint.forall(seq, iter_var, operation) def sum(seq: ZnSequence, func: Optional[Union["Constraint", Callable]] = None) -> Operation: """ Calculate the sum of the ``seq`` according with ``func`` Iterates through elements in seq and calculate their sum, you can modify summarized expressions by specifying ``func`` parameter. Parameters ---------- seq: range, array of var, or sequence (list or tuple) of var sequence to sum up func: Operation or Callable, optional Operation which will be executed with every element and later sum up. Or function which returns such operation. If function or lambda it should be with 0 or 1 arguments only. Returns ------- result: Operation Operation which will calculate the sum Examples -------- >>> import zython as zn >>> class MyModel(zn.Model): ... def __init__(self): ... self.a = zn.Array(zn.var(range(1, 10)), shape=4) >>> model = MyModel() >>> model.solve_minimize(zn.sum(model.a)) Solution(objective=4, a=[1, 1, 1, 1]) # find minimal integer sides of the right triangle >>> import zython as zn >>> class MyModel(zn.Model): ... def __init__(self): ... self.a = zn.var(int) ... self.b = zn.var(int) ... self.c = zn.var(int) ... self.constraints = [self.c ** 2 == zn.sum((self.a, self.b), lambda i: i ** 2), ... zn.forall((self.a, self.b, self.c), lambda i: i > 0)] >>> model = MyModel() >>> model.solve_minimize(model.c) Solution(objective=5, a=4, b=3, c=5) """ iter_var, operation = _iternal.get_iter_var_and_op(seq, func) if isinstance(seq, ArrayMixin) and operation is None: type_ = seq.type else: type_ = operation.type if type_ is None: raise ValueError("Can't derive the type of {} expression".format(func)) return Operation.sum(seq, iter_var, operation, type_=type_) def count(seq: ZnSequence, value: Union[int, Operation, Callable[[ZnSequence], Operation]]) -> Operation: """ Returns the number of occurrences of ``value`` in ``seq``. Parameters ---------- seq: range, array of var, or sequence (list or tuple) of var Sequence to count ``value`` in value: Operation or Callable, optional Operation or constant which will be counted in ``seq``. Or function which returns such value. If function or lambda it should be with 0 or 1 arguments only. Returns ------- result: Operation Operation which will calculate the number of ``value`` in ``seq``. Examples -------- Simple timeshedule problem: you with your neighbor wanted to deside who will wash the dishes in the next week. You should do it 3 days (because you've bought fancy doormat) and your neighbour - 4 days. >>> from collections import Counter >>> import zython as zn >>> class MyModel(zn.Model): ... def __init__(self): ... self.a = zn.Array(zn.var(range(2)), shape=7) ... self.constraints = [zn.count(self.a, 0) == 3, zn.count(self.a, 1) == 4] >>> model = MyModel() >>> result = model.solve_satisfy() >>> Counter(result["a"]) Counter({1: 4, 0: 3}) ``zn.alldifferent`` could be emulated via ``zn.count`` >>> import zython as zn >>> class MyModel(zn.Model): ... def __init__(self): ... self.a = zn.Array(zn.var(range(10)), shape=4) ... self.constraints = [zn.forall(range(self.a.size(0)), ... lambda i: zn.count(self.a, lambda elem: elem == self.a[i]) == 1)] >>> model = MyModel() >>> result = model.solve_satisfy() >>> Counter(result["a"]) Counter({3: 1, 2: 1, 1: 1, 0: 1}) """ iter_var, operation = _iternal.get_iter_var_and_op(seq, value) return Operation.count(seq, iter_var, operation, type_=int) def min(seq: ZnSequence, key: Union[Operation, Callable[[ZnSequence], Operation], None] = None) -> Operation: """ Finds the smallest object in ``seq``, according to ``key`` Parameters ---------- seq: range, array of var, or sequence (list or tuple) of var Sequence to find smallest element in key: Operation or Callable, optional The parameter has the same semantic as in python: specify the operation which result will be latter compared. Returns ------- result: Operation Operation which will find the smallest element. See Also -------- max Examples -------- >>> import zython as zn >>> class MyModel(zn.Model): ... def __init__(self): ... self.a = zn.Array([[1, 2, 3], [-1, -2, -3]]) ... self.m = zn.min(self.a) >>> model = MyModel() >>> model.solve_satisfy() Solution(m=-3) """ iter_var, operation = _iternal.get_iter_var_and_op(seq, key) return Operation.min(seq, iter_var, operation, type_=int) def max(seq: ZnSequence, key: Union[Operation, Callable[[ZnSequence], Operation], None] = None) -> Operation: """ Finds the biggest object in ``seq``, according to ``key`` Parameters ---------- seq: range, array of var, or sequence (list or tuple) of var Sequence to find smallest element in key: Operation or Callable, optional The parameter has the same semantic as in python: specify the operation which result will be latter compared. Returns ------- result: Operation Operation which will find the biggest element. See Also -------- min Examples -------- >>> import zython as zn >>> class MyModel(zn.Model): ... def __init__(self): ... self.a = zn.Array([[1, 2, 3], [-1, -2, -3]]) ... self.m = zn.max(range(self.a.size(0)), lambda row: zn.count(self.a[row, :], lambda elem: elem < 0)) >>> model = MyModel() >>> model.solve_satisfy() Solution(m=3) """ iter_var, operation = _iternal.get_iter_var_and_op(seq, key) return Operation.max(seq, iter_var, operation, type_=int) class alldifferent(Constraint): """ requires all the variables appearing in its argument to be different Parameters ---------- seq: range, array of var, or sequence (list or tuple) of var sequence which elements of which should be distinct except0: bool, optional if set - ``seq`` can contain any amount of 0. See Also -------- allequal ndistinct Examples -------- >>> import zython as zn >>> class MyModel(zn.Model): ... def __init__(self): ... self.a = zn.Array(zn.var(range(1, 10)), shape=5) ... self.x = zn.var(range(3)) ... self.y = zn.var(range(3)) ... self.z = zn.var(range(3)) ... self.constraints = [zn.alldifferent(self.a[:3]), zn.alldifferent((self.x, self.y, self.z))] >>> model = MyModel() >>> model.solve_satisfy() Solution(a=[3, 2, 1, 1, 1], x=2, y=1, z=0) If ``except0`` flag is set constraint doesn't affect 0'es in the ``seq`` >>> from collections import Counter >>> import zython as zn >>> class MyModel(zn.Model): ... def __init__(self): ... self.a = zn.Array(zn.var(range(5)), shape=6) ... self.constraints = [zn.alldifferent(self.a, except0=True), zn.sum(self.a) == 10] >>> model = MyModel() >>> result = model.solve_satisfy() >>> Counter(result["a"]) == {0: 2, 4: 1, 3: 1, 2: 1, 1: 1} True """ def __init__(self, seq: ZnSequence, except0: Optional[bool] = None): if except0: super().__init__(_Op_code.alldifferent_except_0, seq) else: super().__init__(_Op_code.alldifferent, seq) class allequal(Constraint): """ requires all the variables appearing in its argument to be equal Parameters ---------- seq: range, array of var, or sequence (list or tuple) of var sequence which elements of which should be distinct See Also -------- alldifferent ndistinct Examples -------- >>> import zython as zn >>> class MyModel(zn.Model): ... def __init__(self): ... self.a = zn.Array(zn.var(range(1, 10)), shape=(2, 4)) ... self.constraints = [self.a[0, 0] == 5, zn.allequal(self.a)] >>> model = MyModel() >>> model.solve_satisfy() Solution(a=[[5, 5, 5, 5], [5, 5, 5, 5]]) """ def __init__(self, seq: ZnSequence): super().__init__(_Op_code.allequal, seq) class ndistinct(Operation): """ returns the number of distinct values in ``seq``. Parameters ---------- seq: range, array of var, or sequence (list or tuple) of var sequence which elements of which should be distinct See Also -------- alldifferent ndistinct Returns ------- n: Operation Operation, which calculates the number of distinct values in ``seq`` Examples -------- >>> import zython as zn >>> class MyModel(zn.Model): ... def __init__(self, n): ... self.a = zn.Array(zn.var(range(1, 10)), shape=5) ... self.constraints = [zn.ndistinct(self.a) == n] >>> model = MyModel(3) >>> result = model.solve_satisfy() >>> len(set(result["a"])) 3 """ def __init__(self, seq: ZnSequence): super().__init__(_Op_code.ndistinct, seq) class circuit(Constraint): """ Constrains the elements of ``seq`` to define a circuit where x[i] = j means that j is the successor of i. Examples -------- >>> import zython as zn >>> class MyModel(zn.Model): ... def __init__(self): ... self.a = zn.Array(zn.var(range(5)), shape=5) ... self.constraints = [zn.circuit(self.a)] >>> model = MyModel() >>> model.solve_satisfy() Solution(a=[2, 4, 3, 1, 0]) """ def __init__(self, seq: ZnSequence): super().__init__(_Op_code.circuit, seq)
zython
/operations/functions_and_predicates.py
functions_and_predicates.py
import zython from typing import Union, Optional, Callable, Sequence from zython.operations._op_codes import _Op_code class Constraint: def __init__(self, op, *params, type_=None): self.op = op self.params = params self._type = type_ @property def type(self): return self._type def __invert__(self): return Constraint(_Op_code.invert, self) def __xor__(self, other): return Constraint(_Op_code.xor, self, other) def __or__(self, other): return Constraint(_Op_code.or_, self, other) def __and__(self, other): return Constraint(_Op_code.and_, self, other) @staticmethod def exists(seq: Union["zython.var_par.types._range", "zython.var_par.types.orig_range", "zython.var_par.array.ArrayMixin", Sequence["zython.var"]], iter_var: Optional["zython.var"] = None, func: Optional[Union["Constraint", Callable]] = None) -> "Constraint": return Constraint(_Op_code.exists, seq, iter_var, func) @staticmethod def forall(seq: Union["zython.var_par.types._range", "zython.var_par.types.orig_range", "zython.var_par.array.ArrayMixin", Sequence["zython.var"]], iter_var: Optional["zython.var"] = None, func: Optional[Union["Constraint", Callable]] = None) -> "Constraint": return Constraint(_Op_code.forall, seq, iter_var, func)
zython
/operations/constraint.py
constraint.py
from numbers import Number from typing import Optional, Callable, Union, Type import zython from zython.operations._op_codes import _Op_code from zython.operations.constraint import Constraint def _get_wider_type(left, right): return int class Operation(Constraint): def __init__(self, op, *params, type_=None): super(Operation, self).__init__(op, *params, type_=type_) def __pow__(self, power, modulo=None): return self.pow(self, power, modulo) def __mul__(self, other): return self.mul(self, other) def __rmul__(self, other): return self.mul(other, self) # def __truediv__(self, other): # op = _Operation(_Op_code.truediv, self, other) # op._type = _get_wider_type(self, other) # return op # # def __rtruediv__(self, other): # op = _Operation(_Op_code.mul, other, self) # op._type = _get_wider_type(self, other) # return op def __floordiv__(self, other): return self.floordiv(self, other) def __rfloordiv__(self, other): return self.floordiv(other, self) def __mod__(self, other): return self.mod(self, other) def __rmod__(self, other): return self.mod(other, self) def __add__(self, other): return self.add(self, other) def __radd__(self, other): return self.add(other, self) def __sub__(self, other): return self.sub(self, other) def __rsub__(self, other): return self.sub(other, self) def __eq__(self, other): return Operation(_Op_code.eq, self, other, type_=int) def __ne__(self, other): return Operation(_Op_code.ne, self, other, type_=int) def __lt__(self, other): return Operation(_Op_code.lt, self, other, type_=int) def __gt__(self, other): return Operation(_Op_code.gt, self, other, type_=int) def __le__(self, other): return Operation(_Op_code.le, self, other, type_=int) def __ge__(self, other): return Operation(_Op_code.ge, self, other, type_=int) # below method is used for validation and control of _Operation creation # when you create _Operation as Operation(_Op_code.sum, seq, iter_var, func) # it is easy to forgot the order and number of variables, so it is better to call # Operation.sum which has param names and type hints @staticmethod def add(left, right): return Operation(_Op_code.add, left, right, type_=_get_wider_type(left, right)) @staticmethod def sub(left, right): return Operation(_Op_code.sub, left, right, type_=_get_wider_type(left, right)) @staticmethod def pow(base, power, modulo=None): if modulo is not None: raise ValueError("modulo is not supported") return Operation(_Op_code.pow, base, power, type_=_get_wider_type(base, power)) @staticmethod def mul(left, right): return Operation(_Op_code.mul, left, right, type_=_get_wider_type(left, right)) @staticmethod def floordiv(left, right): _validate_div(left, right) return Operation(_Op_code.floordiv, left, right, type_=_get_wider_type(left, right)) @staticmethod def mod(left, right): _validate_div(left, right) return Operation(_Op_code.mod, left, right, type_=_get_wider_type(left, right)) @staticmethod def size(array: "zython.var_par.array.ArrayMixin", dim: int): if 0 <= dim < array.ndims(): return Operation(_Op_code.size, array, dim, type_=int) raise ValueError(f"Array has 0..{array.ndims()} dimensions, but {dim} were specified") @staticmethod def sum(seq: "zython.var_par.types.ZnSequence", iter_var: Optional["zython.var_par.var.var"] = None, func: Optional[Union["Operation", Callable]] = None, type_: Optional[Type] = None): return Operation(_Op_code.sum_, seq, iter_var, func, type_=type_) @staticmethod def count(seq: "zython.var_par.types.ZnSequence", iter_var: Optional["zython.var_par.var.var"] = None, func: Optional[Union["Operation", Callable]] = None, type_: Optional[Type] = None): return Operation(_Op_code.count, seq, iter_var, func, type_=type_) @staticmethod def min(seq: "zython.var_par.types.ZnSequence", iter_var: Optional["zython.var_par.var.var"] = None, func: Optional[Union["Operation", Callable]] = None, type_: Optional[Type] = None): return Operation(_Op_code.min_, seq, iter_var, func, type_=type_) @staticmethod def max(seq: "zython.var_par.types.ZnSequence", iter_var: Optional["zython.var_par.var.var"] = None, func: Optional[Union["Operation", Callable]] = None, type_: Optional[Type] = None): return Operation(_Op_code.max_, seq, iter_var, func, type_=type_) def _validate_div(left, right): if isinstance(right, Number) and right == 0 or getattr(right, "value", 1) == 0: raise ValueError("right part of expression can't be 0")
zython
/operations/operation.py
operation.py
import enum class _Op_code(enum.Enum): add = enum.auto() sub = enum.auto() eq = enum.auto() ne = enum.auto() lt = enum.auto() gt = enum.auto() le = enum.auto() ge = enum.auto() invert = enum.auto() xor = enum.auto() and_ = enum.auto() or_ = enum.auto() mul = enum.auto() truediv = enum.auto() floordiv = enum.auto() mod = enum.auto() pow = enum.auto() forall = enum.auto() # 3 params: (seq, iter_var=None, func=None) exists = enum.auto() sum_ = enum.auto() count = enum.auto() min_ = enum.auto() max_ = enum.auto() size = enum.auto() alldifferent = enum.auto() alldifferent_except_0 = enum.auto() allequal = enum.auto() ndistinct = enum.auto() circuit = enum.auto()
zython
/operations/_op_codes.py
_op_codes.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright 2012 Zhang ZY<http://idupx.blogspot.com/> # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. # # Copyright 2009 Facebook # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import distutils.core import sys # Importing setuptools adds some features like "setup.py develop", but # it's optional so swallow the error if it's not there. try: import setuptools except ImportError: pass kwargs = {} major, minor = sys.version_info[:2] python_26 = (major > 2 or (major == 2 and minor >= 6)) version = "1.1.3" if major >= 3: import setuptools # setuptools is required for use_2to3 kwargs["use_2to3"] = True distutils.core.setup( name="zyutil", version=version, author="Zhang ZY", author_email="[email protected]", url="https://github.com/bufferx/pyutil", license="http://www.apache.org/licenses/LICENSE-2.0", description="pyutil is a set of tools collection for python programming", packages = setuptools.find_packages(exclude=["test", "*.log"]), **kwargs )
zyutil
/zyutil-1.1.3.tar.gz/zyutil-1.1.3/setup.py
setup.py
# author:灵岩([email protected]) #coding=utf-8 # 创建于: 11/30 0027 16:26 from distutils.core import setup setup( name = 'zyw', version='1.0.0', author = '灵岩', author_email='[email protected]', # py_modules = 'zyw', url = 'http://www.xxxxx.com', description='这是一个测试打包的过程', py_modules = ['zyw'] )
zyw
/zyw-1.0.0.tar.gz/zyw-1.0.0/setup.py
setup.py
# author:灵岩([email protected]) # 创建于: 11/30 0030 17:02 print("hello world")
zyw
/zyw-1.0.0.tar.gz/zyw-1.0.0/zyw.py
zyw.py
this is home page
zyxTest
/zyxTest-1.0.tar.gz/zyxTest-1.0/README.md
README.md
import setuptools from pathlib import Path setuptools.setup( name="zyxTest", version=1.0, long_description=Path("README.md").read_text(), packages=setuptools.find_packages(exclude=["test", "data"]) )
zyxTest
/zyxTest-1.0.tar.gz/zyxTest-1.0/setup.py
setup.py
def test2func(): print("test in test2")
zyxTest
/zyxTest-1.0.tar.gz/zyxTest-1.0/testPublish/test2.py
test2.py
def test1func(): print("test in test1")
zyxTest
/zyxTest-1.0.tar.gz/zyxTest-1.0/testPublish/test.py
test.py
""" The Zyxel T50 modem """ """ I used these as a starting point: https://github.com/ThomasRinsma/vmg8825scripts """ import base64 import json import logging from Crypto.Cipher import PKCS1_v1_5 from Crypto.PublicKey import RSA import requests from .helpers import decrypt_response, encrypt_request _LOGGER = logging.getLogger(__name__) class ZyxelT50Modem: def __init__(self, password=None, host='192.168.1.1', username='admin') -> None: self.url = host self.user = username self.password = password self.r = requests.Session() self.r.trust_env = False # ignore proxy settings # we define the AesKey ourselves self.aes_key = b'\x42' * 32 self.enc_aes_key = None self.sessionkey = None self._model = None self._sw_version = None self._unique_id = None def connect(self) -> None: """Set up a Zyxel modem.""" self.enc_aes_key = self.__get_aes_key() try: self.__login() except CannotConnect as exp: _LOGGER.error("Failed to connect to modem") raise exp status = self.get_device_status() device_info = status["DeviceInfo"] if self._unique_id is None: self._unique_id = device_info["SerialNumber"] self._model = device_info["ModelName"] self._sw_version = device_info["SoftwareVersion"] def __get_aes_key(self): # ONCE # get pub key response = self.r.get(f"http://{self.url}/getRSAPublickKey") pubkey_str = response.json()['RSAPublicKey'] # Encrypt the aes key with RSA pubkey of the device pubkey = RSA.import_key(pubkey_str) cipher_rsa = PKCS1_v1_5.new(pubkey) return cipher_rsa.encrypt(base64.b64encode(self.aes_key)) def __login(self): login_data = { "Input_Account": self.user, "Input_Passwd": base64.b64encode(self.password.encode('ascii')).decode('ascii'), "RememberPassword": 0, "SHA512_password": False } enc_request = encrypt_request(self.aes_key, login_data) enc_request['key'] = base64.b64encode(self.enc_aes_key).decode('ascii') response = self.r.post(f"http://{self.url}/UserLogin", json.dumps(enc_request)) decrypted_response = decrypt_response(self.aes_key, response.json()) if decrypted_response is not None: response = json.loads(decrypted_response) self.sessionkey = response['sessionkey'] return 'result' in response and response['result'] == 'ZCFG_SUCCESS' _LOGGER.error("Failed to decrypt response") raise CannotConnect def logout(self): response = self.r.post(f"http://{self.url}/cgi-bin/UserLogout?sessionKey={self.sessionkey}") response = response.json() if 'result' in response and response['result'] == 'ZCFG_SUCCESS': return True else: return False def __get_device_info(self, oid): response = self.r.get(f"http://{self.url}/cgi-bin/DAL?oid={oid}") decrypted_response = decrypt_response(self.aes_key, response.json()) if decrypted_response is not None: json_string = decrypted_response.decode('utf8').replace("'", '"') json_data = json.loads(json_string) return json_data['Object'][0] _LOGGER.error("Failed to get device status") return None def get_device_status(self): result = self.__get_device_info("cardpage_status") if result is not None: return result _LOGGER.error("Failed to get device status") return None def get_connected_devices(self): result = self.__get_device_info("lanhosts") if result is not None: devices = {} for device in result['lanhosts']: devices[device['PhysAddress']] = { "hostName": device['HostName'], "physAddress": device['PhysAddress'], "ipAddress": device['IPAddress'], } return devices _LOGGER.error("Failed to connected devices") return [] class CannotConnect(Exception): """Error to indicate we cannot connect."""
zyxel-t50-modem
/zyxel_t50_modem-0.0.2-py3-none-any.whl/zyxelt50/modem.py
modem.py
import base64 import json import logging from Crypto.Cipher import AES from Crypto.Util.Padding import pad, unpad _LOGGER = logging.getLogger(__name__) def encrypt_request(aes_key, data): iv = b'\x42'*16 cipher = AES.new(aes_key, AES.MODE_CBC, iv) content = cipher.encrypt(pad(json.dumps(data).encode('ascii'), 16)) request = { "content": base64.b64encode(content).decode('ascii'), "iv": base64.b64encode(iv).decode('ascii'), "key": "" } return request def decrypt_response(aes_key, data): if not 'iv' in data or not 'content' in data: _LOGGER.error("Response not encrypted! Response: %s", data) return None iv = base64.b64decode(data['iv'])[:16] content = data['content'] cipher = AES.new(aes_key, AES.MODE_CBC, iv) return unpad(cipher.decrypt(base64.b64decode(content)), 16)
zyxel-t50-modem
/zyxel_t50_modem-0.0.2-py3-none-any.whl/zyxelt50/helpers.py
helpers.py
# zyxelprometheus # Copyright (C) 2020 Andrew Wilkinson # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from base64 import b64decode import json import unittest from zyxelprometheus import prometheus XDSL = open("example_xdsl.txt", "rb").read().decode("utf8") IFCONFIG = open("example_ifconfig.txt", "rb").read().decode("utf8") class TestPrometheus(unittest.TestCase): def test_values(self): prom = prometheus(XDSL, IFCONFIG) self.assertIn("""zyxel_line_rate{bearer="0",stream="up"} 7833000""", prom) self.assertIn("""zyxel_packets{stream="tx",iface="ppp2.3"}""" + """ 7334759""", prom)
zyxelprometheus
/zyxelprometheus-0.5.5-py3-none-any.whl/tests/test_prometheus.py
test_prometheus.py
# zyxelprometheus # Copyright (C) 2020 Andrew Wilkinson # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import io import json from datetime import datetime, timedelta import unittest from zyxelprometheus.server import Handler, Scraper from .mock_sshclient import MockSSHClient, MockSSHSession XDSL = open("example_xdsl.txt", "rb").read().decode("utf8") IFCONFIG = open("example_ifconfig.txt", "rb").read().decode("utf8") class MockHandler(Handler): def __init__(self): self.wfile = io.BytesIO() self.requestline = "GET" self.client_address = ("127.0.0.1", 8000) self.request_version = "1.0" self.command = "GET" class TestServer(unittest.TestCase): def setUp(self): MockSSHClient.reset() session = MockSSHSession() session.add_cmd("ifconfig\n", IFCONFIG) session.add_cmd("xdslctl info\n", XDSL) MockSSHClient.add_session("192.168.1.1", "testuser", "testpassword", session) def test_index(self): handler = MockHandler() handler.path = "/" handler.do_GET() handler.wfile.seek(0) self.assertTrue("/metrics" in handler.wfile.read().decode("utf8")) def test_error(self): handler = MockHandler() handler.path = "/error" handler.do_GET() handler.wfile.seek(0) self.assertTrue("404" in handler.wfile.read().decode("utf8")) def test_metrics(self): class Args: host = "192.168.1.1" user = "testuser" passwd = "testpassword" ifconfig_only = False xdsl_only = False MockHandler.scraper = Scraper(Args()) handler = MockHandler() handler.path = "/metrics" handler.do_GET() handler.wfile.seek(0) self.assertTrue( "zyxel_line_rate" in handler.wfile.read().decode("utf8"))
zyxelprometheus
/zyxelprometheus-0.5.5-py3-none-any.whl/tests/test_server.py
test_server.py
# zyxelprometheus # Copyright (C) 2020 Andrew Wilkinson # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import os import unittest from zyxelprometheus import get_arguments, InvalidArguments class TestArguments(unittest.TestCase): def setUp(self): os.environ = {} def test_user_environ(self): os.environ["ZYXEL_USER"] = "testuser" args = get_arguments(["--passwd", "testpassword"]) self.assertEqual("testuser", args.user) self.assertEqual("testpassword", args.passwd) def test_passwd_environ(self): os.environ["ZYXEL_PASSWD"] = "testpassword" args = get_arguments([]) self.assertEqual("testpassword", args.passwd) def test_bind_without_port(self): os.environ["ZYXEL_PASSWD"] = "testpassword" args = get_arguments(["--bind", "192.168.1.2"]) self.assertEqual("192.168.1.2", args.bind[0]) self.assertEqual(9100, args.bind[1]) def test_no_passwd(self): self.assertRaises(InvalidArguments, get_arguments, []) def test_serve_and_raise(self): self.assertRaises(InvalidArguments, get_arguments, ["--passwd", "testpassword", "-d", "--raw"])
zyxelprometheus
/zyxelprometheus-0.5.5-py3-none-any.whl/tests/test_arguments.py
test_arguments.py
# zyxelprometheus # Copyright (C) 2020 Andrew Wilkinson # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import json import unittest from zyxelprometheus import login, scrape_ifconfig, scrape_xdsl from .mock_sshclient import MockSSHClient, MockSSHSession, MockHungSSHSession IFCONFIG = open("example_ifconfig.txt", "rb").read().decode("utf8") XDSL = open("example_xdsl.txt", "rb").read().decode("utf8") class TestScrape(unittest.TestCase): def setUp(self): MockSSHClient.reset() session = MockSSHSession() session.add_cmd("ifconfig\n", IFCONFIG) session.add_cmd("xdslctl info\n", XDSL) MockSSHClient.add_session("192.168.1.1", "admin", "testpassword", session) def test_scrape_ifconfig(self): session = login("192.168.1.1", "admin", "testpassword") ifconfig = scrape_ifconfig(session) self.assertTrue("192.168.1.1" in ifconfig) def test_scrape_xdsl(self): session = login("192.168.1.1", "admin", "testpassword") xdsl = scrape_xdsl(session) self.assertTrue("Status: Showtime" in xdsl) def test_timeout(self): session = MockHungSSHSession() MockSSHClient.add_session("192.168.1.1", "admin", "testpassword", session) session = login("192.168.1.1", "admin", "testpassword") xdsl = scrape_xdsl(session)
zyxelprometheus
/zyxelprometheus-0.5.5-py3-none-any.whl/tests/test_scrape.py
test_scrape.py
# zyxelprometheus # Copyright (C) 2020 Andrew Wilkinson # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import time from paramiko.ssh_exception import AuthenticationException, \ NoValidConnectionsError PROMPT = "ZySH> ".encode("utf8") class MockSSHClient: mock_sessions = {} def __init__(self): self.missing_host_key_policy = None self.current_session = None def connect(self, hostname, username, password): if (hostname, username, password) in self.mock_sessions: self.current_session = self.mock_sessions[(hostname, username, password)] return for session_key in self.mock_sessions.keys(): if hostname == session_key[0]: raise AuthenticationException("Authentication failed.") raise NoValidConnectionsError({(hostname, 22): True}) def set_missing_host_key_policy(self, policy): self.missing_host_key_policy = policy def exec_command(self, cmd, get_pty=False): return self.current_session, self.current_session, None def close(self): self.current_session = None @classmethod def reset(cls): cls.mock_sessions = {} @classmethod def add_session(cls, host, user, password, session): cls.mock_sessions[(host, user, password)] = session class MockSSHSession: def __init__(self): self.cmds = {} self.channel = MockChannel() self.recv_buffer = PROMPT def add_cmd(self, cmd, response): self.cmds[cmd] = response.encode("utf8") def write(self, cmd): if cmd in self.cmds: self.recv_buffer = cmd.replace("\n", "\r\n").encode("utf8") \ + self.cmds[cmd] else: raise ValueError(f"Unset command used. {repr(cmd)}") def read(self, count): if len(self.recv_buffer) <= count: data = self.recv_buffer self.recv_buffer = PROMPT return data else: data = self.recv_buffer[:count] self.recv_buffer = self.recv_buffer[count:] return data class MockHungSSHSession: def __init__(self): self.channel = MockChannel() def write(self, cmd): pass def read(self, count): time.sleep(6) return "".encode("utf8") class MockChannel: def __init__(self): self.eof_received = False def close(self): pass
zyxelprometheus
/zyxelprometheus-0.5.5-py3-none-any.whl/tests/mock_sshclient.py
mock_sshclient.py
# zyxelprometheus # Copyright (C) 2020 Andrew Wilkinson # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from .mock_sshclient import MockSSHClient import paramiko.client paramiko.client.SSHClient = MockSSHClient from .test_arguments import TestArguments # noqa from .test_login import TestLogin # noqa from .test_prometheus import TestPrometheus # noqa from .test_scrape import TestScrape # noqa from .test_server import TestServer # noqa
zyxelprometheus
/zyxelprometheus-0.5.5-py3-none-any.whl/tests/__init__.py
__init__.py
# zyxelprometheus # Copyright (C) 2020 Andrew Wilkinson # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from base64 import b64decode import json import unittest from unittest.mock import patch from zyxelprometheus import login, logout, InvalidPassword from .mock_sshclient import MockSSHClient, MockSSHSession RESPONSE = json.dumps({ "sessionkey": 816284860, "ThemeColor": "", "changePw": False, "showSkipBtn": False, "quickStart": False, "loginAccount": "admin", "loginLevel": "medium", "result": "ZCFG_SUCCESS" }) class TestLogin(unittest.TestCase): def setUp(self): MockSSHClient.reset() session = MockSSHSession() MockSSHClient.add_session("192.168.1.1", "admin", "testpassword", session) def test_correct_password(self): session = login("192.168.1.1", "admin", "testpassword") self.assertIsNotNone(session.current_session) def test_wrong_password(self): with self.assertRaises(InvalidPassword): login("192.168.1.1", "admin", "wrongpassword") def test_logout(self): session = login("192.168.1.1", "admin", "testpassword") logout(session) self.assertIsNone(session.current_session)
zyxelprometheus
/zyxelprometheus-0.5.5-py3-none-any.whl/tests/test_login.py
test_login.py
#Author: Franklin #Date: 7/10/2020 #Decription: from __future__ import print_function from zyytif import * from setuptools import setup, find_packages import sys setup( name='zyytif', version='0.1.2', description='Scientific computing for TIF', author='Franklin', author_email='[email protected]', maintainer='Franklin', maintainer_email='[email protected]', license='MIT License', packages=find_packages(), platforms=["all"], classifiers=[ 'Operating System :: OS Independent', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', 'Topic :: Software Development :: Libraries' ], install_requires=[ 'GDAL', 'numpy' ], zip_safe=True )
zyytif
/zyytif-0.1.2.tar.gz/zyytif-0.1.2/setup.py
setup.py
readme hello world
zyz-hello-world
/zyz-hello-world-0.0.1.tar.gz/zyz-hello-world-0.0.1/README.md
README.md
from setuptools import setup, find_packages with open("README.md", "r") as fh: long_description = fh.read() setup( name='zyz-hello-world', version='0.0.1', packages=find_packages(), url='https://github.com/pypa/sampleproject', license='MIT', author='Yizhe Zeng', author_email='[email protected]', description='A small example package', long_description=long_description, long_description_content_type="text/markdown", install_requires=[], classifiers=[ "Programming Language :: Python :: 3", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", ], python_requires='>=3.6', )
zyz-hello-world
/zyz-hello-world-0.0.1.tar.gz/zyz-hello-world-0.0.1/setup.py
setup.py
#!/usr/bin/env python import socket import threading def echo_server(client: socket.socket, address: tuple): print('欢迎来自{}:{}的新客户端'.format(address[0], address[1])) client.send('Welcome from{}:{}'.format(address[0], address[1]).encode('utf-8')) while True: data = client.recv(1024) if data == b'exit': break elif data: print(data.decode('utf-8')) else: break print('客户端推出了!') client.close() #创建socket对象实例,采用IPV4和TCP协议 server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server.bind(('127.0.0.1', 2018)) server.listen(5) print('Server start! Listening 127.0.0.1:2018') while True: client, address = server.accept() t = threading.Thread(target=echo_server, args=[client, address]) t.start() # echo_server(client, address)
zyz-hello-world
/zyz-hello-world-0.0.1.tar.gz/zyz-hello-world-0.0.1/compar/tcp_server.py
tcp_server.py
import re import sys # 控制仓数据 # 25(起始位)00(仓位数据)ttttpppppppphhhh(温湿度大气压模块传感器数据)xxxxyyyyzzzzxxxxyyyyzzzzRRRRPPPPYYYYxxxxyyyyzzzz(九轴数据)DDDDcccc(声呐数据)WWWWdddd(水深传感器)0000(奇偶校验位)FFFF(结束位) class base_parser(): def __init__(self): self.re_ = None self.pattern = None def parse(self, sentence): match = self.pattern.match(sentence) if not match: print('unregular sentence') sys.exit() sentence_dict_hex = match.groupdict() print(sentence_dict_hex) sentence_dict_dec = {} for key, value in sentence_dict_hex.items(): sentence_dict_dec[key] = int(value, 16) print(sentence_dict_dec) return sentence_dict_hex, sentence_dict_dec class up_parser(base_parser): def __init__(self): super().__init__() self.re_ = '(?P<起始位>25)' \ '(?P<仓位>00|01)' \ '(?P<温度>([0-9]|[a-f]|[A-F]){4})' \ '(?P<气压>([0-9]|[a-f]|[A-F]){8})' \ '(?P<湿度>([0-9]|[a-f]|[A-F]){4})' \ '(?P<加速度Ax>([0-9]|[a-f]|[A-F]){4})' \ '(?P<加速度Ay>([0-9]|[a-f]|[A-F]){4})' \ '(?P<加速度Az>([0-9]|[a-f]|[A-F]){4})' \ '(?P<角速度Wx>([0-9]|[a-f]|[A-F]){4})' \ '(?P<角速度Wy>([0-9]|[a-f]|[A-F]){4})' \ '(?P<角速度Wz>([0-9]|[a-f]|[A-F]){4})' \ '(?P<角度Roll>([0-9]|[a-f]|[A-F]){4})' \ '(?P<角度Pitch>([0-9]|[a-f]|[A-F]){4})' \ '(?P<角度Yaw>([0-9]|[a-f]|[A-F]){4})' \ '(?P<磁场Hx>([0-9]|[a-f]|[A-F]){4})' \ '(?P<磁场Hy>([0-9]|[a-f]|[A-F]){4})' \ '(?P<磁场Hz>([0-9]|[a-f]|[A-F]){4})' \ '(?P<声呐>([0-9]|[a-f]|[A-F]){8})' \ '(?P<声呐确信度>([0-9]|[a-f]|[A-F]){4})' \ '(?P<水温>([0-9]|[a-f]|[A-F]){4})' \ '(?P<水深>([0-9]|[a-f]|[A-F]){4})' \ '(?P<确认位>([0-9]|[a-f]|[A-F]){2})' \ '(?P<结束位>([0-9]|[a-f]|[A-F]){4})' self.pattern = re.compile(self.re_) # def parse(self, sentence): # match = self.pattern.match(sentence) # if not match: # print('unregular sentence') # sys.exit() # sentence_dict_hex = match.groupdict() # print(sentence_dict_hex) # sentence_dict_dec = {} # for key, value in sentence_dict_hex.items(): # sentence_dict_dec[key] = int(value, 16) # print(sentence_dict_dec) # return sentence_dict_dec # 起始位 前进后退 旋转或侧推 垂直 灯光 云台 传送 机械臂1 机械臂2 机械臂3 机械臂4 机械臂5 机械臂6 预留PWM 模式开关 验证位 结束位 # 0x25 500-2500 500-2500 500-2500 500-2500 500-2500 500-2500 500-2500 500-2500 500-2500 500-2500 500-2500 500-2500 500-2500 0x21 # 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 class down_parser(base_parser): def __init__(self): self.re_ = '(?P<起始位>25)' \ '(?P<前进后退>([0-9]|[a-f]|[A-F]){4})' \ '(?P<旋转或侧推>([0-9]|[a-f]|[A-F]){4})' \ '(?P<垂直>([0-9]|[a-f]|[A-F]){4})' \ '(?P<灯光>([0-9]|[a-f]|[A-F]){4})' \ '(?P<云台>([0-9]|[a-f]|[A-F]){4})' \ '(?P<传送>([0-9]|[a-f]|[A-F]){4})' \ '(?P<机械臂1>([0-9]|[a-f]|[A-F]){4})' \ '(?P<机械臂2>([0-9]|[a-f]|[A-F]){4})' \ '(?P<机械臂3>([0-9]|[a-f]|[A-F]){4})' \ '(?P<机械臂4>([0-9]|[a-f]|[A-F]){4})' \ '(?P<机械臂5>([0-9]|[a-f]|[A-F]){4})' \ '(?P<机械臂6>([0-9]|[a-f]|[A-F]){4})' \ '(?P<预留PWM>([0-9]|[a-f]|[A-F]){4})' \ '(?P<模式开关>([0-9]|[a-f]|[A-F]){2})' \ '(?P<验证位>([0-9]|[a-f]|[A-F]){2})' \ '(?P<结束位>21)' self.pattern = re.compile(self.re_) # def parse(self, sentence): # match = self.pattern.match(sentence) # if not match: # print('unregular sentence') # sys.exit() # sentence_dict_hex = match.groupdict() # print(sentence_dict_hex) # sentence_dict_dec = {} # for key, value in sentence_dict_hex.items(): # sentence_dict_dec[key] = int(value, 16) # print(sentence_dict_dec) if __name__ == '__main__': x = up_parser() x.parse('25001234123456780bcddddaaaacccceeeeffff99990000777755554444ccccaaaaaaaacccc1111dddd00FFFFeeeee') y = down_parser() y.parse('2505DC05DC05DC05DC05DC05DC05DC05DC05DC05DC05DC05DC05DC080021')
zyz-hello-world
/zyz-hello-world-0.0.1.tar.gz/zyz-hello-world-0.0.1/compar/sentence_parser.py
sentence_parser.py
#!/usr/bin/env python import socket #创建socket对象实例,采用IPV4和TCP协议 client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) client.connect(('127.0.0.1', 2018)) for i in range(100): client.send('Hello World!'.encode('utf-8')) reply = client.recv(1024) print(reply.decode('utf-8')) client.send(b'exit') client.close()
zyz-hello-world
/zyz-hello-world-0.0.1.tar.gz/zyz-hello-world-0.0.1/compar/tcp_client.py
tcp_client.py
#!/usr/bin/env python import socket sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock.sendto('Hello'.encode('utf-8'), ('127.0.0.1', 60011)) sock.close()
zyz-hello-world
/zyz-hello-world-0.0.1.tar.gz/zyz-hello-world-0.0.1/compar/client.py
client.py
import argparse import sentence_parser import udp if __name__ == '__main__': parser_ = argparse.ArgumentParser() parser_.add_argument('--udp_server_ip', type=str, required=False, default='127.0.0.1', help='udp服务端的ip地址') parser_.add_argument('--udp_server_port', type=int, required=False, default='60002', help='udp服务端的端口号') args = parser_.parse_args() print(args) x = udp.udp_hex(args.udp_server_ip, args.udp_server_port) par = sentence_parser.up_parser() while True: sentence = x.listenonce() par.parse(par)
zyz-hello-world
/zyz-hello-world-0.0.1.tar.gz/zyz-hello-world-0.0.1/compar/demo.py
demo.py
import socket class udp_hex(): def __init__(self, ip, port): self.ip = ip self.port = port self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) self.sock.bind((self.ip, self.port)) # 持续监听来自127.0.01.1:60002的udp消息 def listen(self): while True: data, address = self.sock.recvfrom(10240) print('收到来自 {}:{} 的消息'.format(address[0], address[1])) # print(type(data)) # print(data) print(data.hex()) # print(type(data.hex())) def listenonce(self): data, address = self.sock.recvfrom(10240) print('收到来自 {}:{} 的消息'.format(address[0], address[1])) # print(type(data)) # print(data) print(data.hex()) # print(type(data return data.hex() # 发送一条udp消息到127.0.01.1:60003 def send(self): x_str = '252d 3d 4d6d' x_bytes = bytes.fromhex(x_str) self.sock.sendto(x_bytes, (self.udp_server_ip, 60003)) # sock.close()
zyz-hello-world
/zyz-hello-world-0.0.1.tar.gz/zyz-hello-world-0.0.1/compar/udp.py
udp.py
#!/usr/bin/env python import socket sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock.bind(('0.0.0.0', 60011)) while True: data, address = sock.recvfrom(1024) print('收到来自 {}:{} 的消息'.format(address[0], address[1])) print(data.decode('utf-8'))
zyz-hello-world
/zyz-hello-world-0.0.1.tar.gz/zyz-hello-world-0.0.1/compar/server.py
server.py
#!/usr/bin/env python import socket sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect(('www.baidu.com', 80)) sock.send(b'GET / HTTP/1.1\r\nHOST: www.baidu.com\r\nConnection:close\r\n\r\n') buffer = [] while True: content = sock.recv(1024) if content: buffer.append(content) else: break web_content = b''.join(buffer) print(web_content) http_header, http_content = web_content.split(b'\r\n\r\n',1) with open('baidu.html', 'wb') as f: f.write(http_content)
zyz-hello-world
/zyz-hello-world-0.0.1.tar.gz/zyz-hello-world-0.0.1/compar/tcp.py
tcp.py
import datetime def logdemo(): cyear = str(datetime.datetime.now().year) print("Demo: Hello world " + cyear + ", This is a demo line ...")
zyz
/zlog/__init__.py
__init__.py
哈哈,就这样吧,安装必备
zyzFlask
/zyzFlask-0.2.0.tar.gz/zyzFlask-0.2.0/README.md
README.md
from setuptools import setup print("===========================================================") setup( name = 'zyzFlask', version = '0.2.0', packages = ['configs', 'core'], author = 'Asian.zhang', author_email = '[email protected]', url='', license = "MIT License", description = '基于flask封装的web开发包' )
zyzFlask
/zyzFlask-0.2.0.tar.gz/zyzFlask-0.2.0/setup.py
setup.py
import uuid import json import urllib.parse from flask import request def get_trace_id(): try: if request.trace_id is None: return uuid.uuid1() else: return request.trace_id except Exception: return str(uuid.uuid1()) def is_none(arg): return not arg or str(arg) in ['null','none','false'] def get_version(): try: return request.version except AttributeError: pass return request.args.get('version') def get_ip_address(): try: if request.headers.get('x-forwarded-for') is not None: ip_address = str(request.headers.get('x-forwarded-for')) if "," in ip_address: return ip_address.split(",")[0] return ip_address except: pass return '127.0.0.1' # 获取get请求时,传的参数params并解url def get_request_params(): try: request_params = json.loads(urllib.parse.unquote_plus(request.args.get('params'))) params = get_common_params(request_params) except Exception: params = None return params # 获取post请求时,传的参数params并解json def post_request_params(): try: request_params = json.loads(request.data) params = get_common_params(request_params) except Exception: params = None return params # 获取form_data中的参数并转换为字典格式 def form_data_to_dict(): return {key: dict(request.form)[key][0] for key in dict(request.form)} # 获取公共参数并加到params中 def get_common_params(params): try: if request.args.get('platform') is not None: params['platform'] = request.args.get('platform') except Exception: pass return params
zyzFlask
/zyzFlask-0.2.0.tar.gz/zyzFlask-0.2.0/core/common.py
common.py
import os import uuid from datetime import timedelta from threading import Lock from flask import Flask, Blueprint,cli from flask.helpers import get_debug_flag, _PackageBoundObject, _endpoint_from_view_func from flask.templating import _default_template_ctx_processor from werkzeug.routing import Rule, Map, MapAdapter,RequestSlash, RequestRedirect, RequestAliasRedirect, _simple_rule_re from werkzeug.urls import url_quote, url_join from werkzeug.datastructures import ImmutableDict from werkzeug._internal import _encode_idna, _get_environ from werkzeug._compat import to_unicode, string_types, wsgi_decoding_dance from werkzeug.exceptions import BadHost, NotFound, MethodNotAllowed # 自定义flask蓝图,给所有路由增加'methods': ['GET', 'POST']参数。不用每个都写 class ZyzBlueprint(Blueprint): def __init__(self, name, import_name, default_methods=None, static_folder=None,static_url_path=None, template_folder=None, url_prefix=None, subdomain=None, url_defaults=None, root_path=None): super().__init__(name, import_name, static_folder=static_folder, static_url_path=static_url_path, template_folder=template_folder, url_prefix=url_prefix, subdomain=subdomain, url_defaults=url_defaults, root_path=root_path) self.default_methods = default_methods # 装饰器 def route(self,rule,**options): # 设置默认请求 methods = options.get('methods') if not methods: options['methods'] = self.default_methods # 给函数名增加版本号,多个版本使用相同函数名时,蓝图存储监听时可以区分。 def decorator(f): endpoint = options.pop("endpoint", f.__name__ + str(options.get('version')).replace('.','_')) # add_url_rule 函数,就是将路由和函数名的对应关系,生成一个flask对象,存在Blueprint类中的deferred_functions类属性中 # rule: 路由 例:/userInfo/get.json # endpoint : 函数名,自定义加上了版本号 例:login_mobile['3_1_2'] # f : 函数 例:<function sheng_portal.backend.app.versions.version_1_3_1.controller.user.user.login_check> # **options : 路由后面带的参数 例{'methods': ['GET', 'POST'], 'version': ['1.3.1']} self.add_url_rule(rule, endpoint, f, **options) return f return decorator class ZyzRule(Rule): def __init__(self, string, version=None, **options): self.version = version super().__init__(string, **options) class ZyzFlask(Flask): url_rule_class = ZyzRule # 默认设置,配置参数 default_config = ImmutableDict({ 'DEBUG': get_debug_flag(), # 启用/禁用调试模式 'TESTING': False, # 启用/禁用测试模式 'PROPAGATE_EXCEPTIONS': None, # 显式地允许或禁用异常的传播。如果没有设置或显式地设置为 None ,当 TESTING 或 DEBUG 为真时,这个值隐式地为 true. 'PRESERVE_CONTEXT_ON_EXCEPTION': None, # 你同样可以用这个设定来强制启用(允许调试器内省),即使没有调试执行,这对调试生产应用很有用(但风险也很大) 'SECRET_KEY': None, # 密匙 还不知道干嘛用的 'PERMANENT_SESSION_LIFETIME': timedelta(days=31), # 控制session的过期时间 'USE_X_SENDFILE': False, # 启用/禁用 x-sendfile(一种下载文件的工具),打开后,下载不可控,可能有漏洞,需谨慎 'LOGGER_NAME': None, # 日志记录器的名称 'LOGGER_HANDLER_POLICY': 'always', # 可以通过配置这个来组织flask默认记录日志 'SERVER_NAME': None, # 服务器名和端口。需要这个选项来支持子域名 (例如: 'myapp.dev:5000' ) 'APPLICATION_ROOT': None, # 如果应用不占用完整的域名或子域名,这个选项可以被设置为应用所在的路径。这个路径也会用于会话 cookie 的路径值。如果直接使用域名,则留作 None 'SESSION_COOKIE_NAME': 'session', # 会话 cookie 的名称。 'SESSION_COOKIE_DOMAIN': '.mofanghr.com', # 会话 cookie 的域。如果不设置这个值,则 cookie 对 SERVER_NAME 的全部子域名有效 'SESSION_COOKIE_PATH': '/', # 会话 cookie 的路径。如果不设置这个值,且没有给 '/' 设置过,则 cookie 对 APPLICATION_ROOT 下的所有路径有效 'SESSION_COOKIE_HTTPONLY': True, # 控制 cookie 是否应被设置 httponly 的标志, 默认为 True 'SESSION_COOKIE_SECURE': False, # 控制 cookie 是否应被设置安全标志,默认为 False 'SESSION_REFRESH_EACH_REQUEST': True, # 如果被设置为 True (这是默认值),每一个请求 cookie 都会被刷新。如果设置为 False ,只有当 cookie 被修改后才会发送一个 set-cookie 的标头 'MAX_CONTENT_LENGTH': None, # 如果设置为字节数, Flask 会拒绝内容长度大于此值的请求进入,并返回一个 413 状态码 'SEND_FILE_MAX_AGE_DEFAULT': timedelta(hours=12), # 默认缓存控制的最大期限,以秒计, 'TRAP_BAD_REQUEST_ERRORS': False, # 这个设置用于在不同的调试模式情形下调试,返回相同的错误信息 BadRequest 'TRAP_HTTP_EXCEPTIONS': False, # 如果这个值被设置为 True ,Flask不会执行 HTTP 异常的错误处理 'EXPLAIN_TEMPLATE_LOADING': False, # 解释模板加载 'PREFERRED_URL_SCHEME': 'http', # 生成URL的时候如果没有可用的 URL 模式话将使用这个值。默认为 http 'JSON_AS_ASCII': True, # 默认情况下 Flask 使用 ascii 编码来序列化对象。如果这个值被设置为 False , Flask不会将其编码为 ASCII,并且按原样输出,返回它的 unicode 字符串 'JSON_SORT_KEYS': True, # Flask 按照 JSON 对象的键的顺序来序来序列化它。这样做是为了确保键的顺序不会受到字典的哈希种子的影响,从而返回的值每次都是一致的,不会造成无用的额外 HTTP 缓存 'JSONIFY_PRETTYPRINT_REGULAR': True, # 如果这个配置项被 True (默认值), 如果不是 XMLHttpRequest 请求的话(由 X-Requested-With 标头控制) json 字符串的返回值会被漂亮地打印出来。 'JSONIFY_MIMETYPE': 'application/json', 'TEMPLATES_AUTO_RELOAD': None, }) def __init__( self, import_name, static_path=None, static_url_path=None, static_folder='static', template_folder='templates', instance_path=None, instance_relative_config=False, root_path=None ): self.version_dict = {} _PackageBoundObject.__init__( self, import_name, template_folder=template_folder, root_path=root_path ) if static_path is not None: from warnings import warn warn(DeprecationWarning('static_path is now called static_url_path'), stacklevel=2) static_url_path = static_path if static_url_path is not None: self.static_url_path = static_url_path if static_folder is not None: self.static_floder = static_folder if instance_path is None: instance_path = self.auto_find_instance_path() elif not os.path.isabs(instance_path): raise ValueError('If an instance path is provided it must be ' 'absolute. A relative path was given instead.') # 保存实例文件夹的路径。 versionadded:: 0.8 self.instance_path = instance_path # 这种行为就像普通字典,但支持其他方法从文件加载配置文件。 self.config = self.make_config(instance_relative_config) # 准备记录日志的设置 self._logger = None self.logger_name = self.import_name # 注册所有视图函数的字典。钥匙会是:用于生成URL的函数名值是函数对象本身。 # 注册一个视图函数,使用:route装饰器 self.view_functions = {} # 支持现在不推荐的Error处理程序属性。现在将使用 self._error_handlers = {} #: A dictionary of all registered error handlers. The key is ``None`` #: for error handlers active on the application, otherwise the key is #: the name of the blueprint. Each key points to another dictionary #: where the key is the status code of the http exception. The #: special key ``None`` points to a list of tuples where the first item #: is the class for the instance check and the second the error handler #: function. #: #: To register a error handler, use the :meth:`errorhandler` #: decorator. self.error_handler_spec = {None: self._error_handlers} #: A list of functions that are called when :meth:`url_for` raises a #: :exc:`~werkzeug.routing.BuildError`. Each function registered here #: is called with `error`, `endpoint` and `values`. If a function #: returns ``None`` or raises a :exc:`BuildError` the next function is #: tried. #: #: .. versionadded:: 0.9 self.url_build_error_handlers = [] self.before_request_funcs = {} self.before_first_request_funcs = [] self.after_request_funcs = {} self.teardown_request_funcs = {} self.teardown_appcontext_funcs = [] self.url_value_preprocessors = {} self.url_default_functions = {} self.template_context_processors = { None: [_default_template_ctx_processor] } self.shell_context_processor = [] self.blueprints = {} self._blueprint_order = [] self.extensions = {} # 使用这个可以在创建类之后改变路由转换器的但是在任何线路连接之前 # from werkzeug.routing import BaseConverter #: class ListConverter(BaseConverter): #: def to_python(self, value): #: return value.split(',') #: def to_url(self, values): #: return ','.join(BaseConverter.to_url(value) #: for value in values) #: #: app = Flask(__name__) #: app.url_map.converters['list'] = ListConverter #: @list.route("/job.json") >>> /list/job.json self.url_map = ZyzMap() # 如果应用程序已经处理至少一个,则在内部跟踪 self._got_first_request = False self._before_request_lock = Lock() if self.has_static_folder: self.add_url_rule(self.static_url_path + '/<path:filename>', endpoint='static', view_func=self.send_static_file) self.cli = cli.AppGroup(self.name) def make_config(self, instance_relative=False): """用于通过flask构造函数创建config属性。从构造函数传递“nstance_relative”参数 flask(名为“instance_relative_config”),并指示是否配置应该与实例路径或 根路径相对应。""" root_path = self.root_path if instance_relative: root_path = self.instance_path return self.config_class(root_path, self.default_config) def create_url_adapter(self, request): if request is not None: # 设置 request_id request.trace_id = str(uuid.uuid4()) # 设置 app version request.version = get_version(request) return self.url_map.bind_to_environ(request.environ, request=request, version_dict=self.version_dict, server_name=self.config['SERVER_NAME']) if self.config['SERVER_NAME'] is not None: return self.url_map.bind( self.config['SERVER_NAME'], script_name=self.config['APPLICATION_ROOT'] or '/', url_scheme=self.config['PREFERRED_URL_SCHEME'] ) def add_url_rule(self, rule, endpoint=None, view_func=None, **options): if endpoint is None: endpoint = _endpoint_from_view_func(view_func) options['endpoint'] = endpoint methods = options.pop('methods', None) if methods is None: methods = getattr(view_func,'methods',None) or ('GET',) methods = set(methods) required_methods = set(getattr(view_func, 'required_methods', ())) provide_automatic_options = getattr(view_func, 'provide_automatic_options', None) if provide_automatic_options is None: if "OPTIONS" not in methods: provide_automatic_options = True required_methods.add('OPTIONS') else: provide_automatic_options = False # 设置 version_dict if self.version_dict.get(rule) is None: self.version_dict[rule] = [] version_list = self.version_dict.get(rule.strip()) # 添加version list version = options.get('version') if version and isinstance(version, list): for item in version: if item not in version_list: version_list.append(item) # 增加回调时 的 methods methods |= required_methods rule = self.url_rule_class(rule, methods=methods, **options) rule.provide_automatic_options = provide_automatic_options self.url_map.add(rule) if view_func is not None: old_func = self.view_functions.get(endpoint) if old_func is not None and old_func != view_func: raise AssertionError('View function mapping is overwriting an ' 'existing endpoint function: %s' % endpoint) self.view_functions[endpoint] = view_func class ZyzMap(Map): def bind(self, server_name, script_name=None, subdomain=None, url_scheme='http', default_method='GET', path_info=None, query_args=None, request=None, version_dict=None): server_name = server_name.lower() if self.host_matching: if subdomain is not None: raise RuntimeError('host matching enabled and a ' 'subdomain was provided') elif subdomain is None: subdomain = self.default_subdomain if script_name is None: script_name = '/' try: server_name = _encode_idna(server_name) except UnicodeError: raise BadHost() return ZyzMapAdapter(self,server_name, script_name, subdomain, url_scheme, path_info, default_method, query_args, request, version_dict) def bind_to_environ(self, environ, server_name=None, subdomain=None, request=None, version_dict=None): environ = _get_environ(environ) if 'HTTP_HOST' in environ: wsgi_server_name = environ['HTTP_HOST'] if environ['wsgi.url_scheme'] == 'http' and wsgi_server_name.endswith(':80'): wsgi_server_name = wsgi_server_name[:-3] elif environ['wsgi.url_scheme'] == 'https' and wsgi_server_name.endswith(':443'): wsgi_server_name = wsgi_server_name[:-4] else: wsgi_server_name = environ['SERVER_NAME'] if (environ['wsgi.url_scheme'],environ['SERVER_PORT']) not in (('https','443'),('http','80')): wsgi_server_name += ':' + environ['SERVER_PORT'] wsgi_server_name = wsgi_server_name.lower() if server_name is None: server_name = wsgi_server_name else: server_name = server_name.lower() if subdomain is None and not self.host_matching: cur_server_name = wsgi_server_name.split('.') real_server_name = server_name.split('.') offset = -len(real_server_name) if cur_server_name[offset:] != real_server_name: subdomain = '<invalid>' else: subdomain = '.'.join(filter(None, cur_server_name[:offset])) def _get_wsgi_string(name): val = environ.get(name) if val is not None: return wsgi_decoding_dance(val, self.charset) script_name = _get_wsgi_string('SCRIPT_NAME') path_info = _get_wsgi_string('PATH_INFO') query_args = _get_wsgi_string('QUERY_STRING') return ZyzMap.bind(self, server_name, script_name, subdomain, environ['wsgi.url_scheme'], environ['REQUEST_METHOD'], path_info, query_args=query_args, request=request, version_dict=version_dict) class ZyzMapAdapter(MapAdapter): def __init__(self, map, server_name, script_name, subdomain, url_scheme, path_info, default_method, query_args=None, request = None, version_dict = None): self.request = request self.version_dict = version_dict if version_dict is not None else {} super().__init__(map, server_name, script_name, subdomain, url_scheme, path_info, default_method, query_args) def match(self, path_info=None, method=None, return_rule=False, query_args=None): self.map.update() if path_info is None: path_info = self.path_info else: path_info = to_unicode(path_info, self.map.charset) if query_args is None: query_args = self.query_args method = (method or self.default_method).upper() path = u'%s|%s' % ( self.map.host_matching and self.server_name or self.subdomain, path_info and '/%s' % path_info.lstrip('/') ) have_match_for = set() for rule in self.map.rules: try: rv = rule.match(path) except RequestSlash: raise RequestRedirect(self.make_redirect_url( url_quote(path_info, self.map.charset, safe='/:|+') + '/', query_args)) except RequestAliasRedirect as e: raise RequestRedirect(self.make_alias_redirect_url( path, rule.endpint, e.matched_values, method,query_args)) if rv is None: continue if rule.methods is not None and method not in rule.methods: have_match_for.update(rule.methods) continue # 确定版本 version = get_version(self.request) if self.request and version: if not isinstance(rule.version, list) or not rule.version: rule.version = list() version_list = self.version_dict.get(rule.rule) if len(rule.version) == 0 \ and version_list is not None \ and version in version_list: continue elif len(rule.version) != 0 and version not in rule.version: continue self.request.rule_version = rule.version if self.map.redirect_defaults: redirect_url = self.get_default_redirect(rule, method, rv, query_args) if redirect_url is not None: if isinstance(rule.redirect_to,string_types): def _handle_match(match): value = rv[match.group(1)] return rule._converters[match.group(1)].to_url(value) redirect_url =_simple_rule_re.sub(_handle_match,rule.redirect_to) else: redirect_url = rule.redirect_to(self, **rv) raise RequestRedirect(str(url_join('%s://%s%s%s' % ( self.url_scheme or 'http', self.subdomain and self.subdomain + '.' or '', self.server_name, self.script_name ),redirect_url))) if return_rule: return rule, rv else: return rule.endpint, rv if have_match_for: raise MethodNotAllowed(valid_methods=list(have_match_for)) raise NotFound() def get_version(request): try: return request.version except AttributeError: pass return request.args.get('version')
zyzFlask
/zyzFlask-0.2.0.tar.gz/zyzFlask-0.2.0/core/zyz_flask.py
zyz_flask.py
import time import json import redis import hashlib import requests import traceback import urllib.parse from functools import wraps from flask import make_response, request from core.log import logger from core.utils import get_randoms, AesCrypt, get_hashlib from core.common import get_trace_id, is_none, get_version from core.global_settings import * from core.exceptions import BusinessException from core.check_param import build_check_rule, CheckParam from configs import AES_KEY, REDIS_HOST, REDIS_PORT, REDIS_PASSWORD, AUTH_COOKIE_KEY, SSO_VERSION, \ CALL_SYSTEM_ID check_param = CheckParam() class BaseError(object): def __init__(self): pass @staticmethod def not_login(): return return_data(code=LOGIN_FAIL, msg='用户未登录') @staticmethod def not_local_login(): return return_data(code=OTHER_LOGIN_FAIL, msg='您的帐号已在其他设备上登录\n请重新登录') @staticmethod def system_exception(): return return_data(code=REQUEST_FAIL, msg='后台系统异常') @staticmethod def request_params_incorrect(): return return_data(code=REQUEST_FAIL, msg='请求参数不正确') @staticmethod def common_feild_null(feild): raise BusinessException(code=-99, msg=feild + '不能为空') @staticmethod def common_feild_wrong(feild): raise BusinessException(code=-99, msg=feild + '错误') class Redis(object): def __init__(self,db=None): self.db = db if not hasattr(Redis,'REDIS_POOL_CACHE'): self.getRedisCoon() self.get_server() def getRedisCoon(self): REDIS_ = redis.ConnectionPool(host=REDIS_HOST, port=REDIS_PORT, password=REDIS_PASSWORD) REDIS_1 = redis.ConnectionPool(host=REDIS_HOST, port=REDIS_PORT, password=REDIS_PASSWORD, db=1) REDIS_2 = redis.ConnectionPool(host=REDIS_HOST, port=REDIS_PORT, password=REDIS_PASSWORD, db=2) REDIS_3 = redis.ConnectionPool(host=REDIS_HOST, port=REDIS_PORT, password=REDIS_PASSWORD, db=3) REDIS_4 = redis.ConnectionPool(host=REDIS_HOST, port=REDIS_PORT, password=REDIS_PASSWORD, db=4) self.REDIS_POOL_CACHE = { '0': REDIS_, '1': REDIS_1, '2': REDIS_2, '3': REDIS_3, '4': REDIS_4 } def __get_pool(self): if self.db is None: self.db = '0' return self.REDIS_POOL_CACHE.get(self.db) def get_server(self): self.conn = redis.Redis(connection_pool=self.__get_pool()) return self.conn def set_variable(self, name, value, ex=None, px=None, nx=False, xx=False): # 设置普通键值对 # EX — seconds – 设置键key的过期时间,单位时秒 (datetime.timedelta 格式) # PX — milliseconds – 设置键key的过期时间,单位时毫秒 (datetime.timedelta 格式) # NX – 只有键key不存在的时候才会设置key的值 (布尔值) # XX – 只有键key存在的时候才会设置key的值 (布尔值) self.conn.set(name, value, ex, px, nx, xx) def get_variable(self, name): # 获取普通键值对的值 return self.conn.get(name) def delete_variable(self, *names): # 删除指定的一个或多个键 根据`names` self.conn.delete(*names) def get_hget(self, name, key): return self.conn.hget(name, key) def get_hgetall(self, name): return self.conn.hgetall(name) def set_hset(self, name, key, value): self.conn.hset(name, key, value) def set_rpush(self, name, value): # 列表结尾中增加值 self.conn.rpush(name, value) def get_lpop(self, name): # 弹出列表的第一个值(非阻塞) self.conn.lpop(name) def set_blpop(self, *name, timeout=0): # 弹出传入所有列表的第一个有值的(阻塞),可以设置阻塞超时时间 self.conn.blpop(*name, timeout) def get_llen(self, name): # 返回列表的长度(列表不存在时返回0) self.conn.llen(name) def set_sadd(self, name, value): # 集合中增加元素 self.conn.sadd(name, value) def delete_srem(self, name, *value): # 删除集合中的一个或多个元素 self.conn.srem(name, *value) def spop(self, name): # 随机移除集合中的一个元素并返回 return self.get_server().spop(name) def smembers(self, name): return self.conn.smembers(name) def sismember(self, name, value): # 判断value是否是集合name中的元素。是返回1 ,不是返回0 return self.conn.sismember(name,value) def expire(self,name,time): # 设置key的过期时间 self.conn.expire(name,time) class LoginAndReturn(object): def __init__(self): pass def login_required(f): @wraps(f) # 不改变使用装饰器原有函数的结构(如__name__, __doc__) def decorated_function(*args, **kw): #### 所有注释都是进行单点登录操作的 !!!!!!! auth_token = request.cookies.get('auth_token') refresh_time = request.cookies.get('refresh_time') user_id = get_cookie_info().get('user_id') # 这个个方法里存在单点登录状态 sso_code = get_cookie_info().get('sso_code') if is_none(auth_token) or is_none(refresh_time) or is_none(user_id): return BaseError.not_login() # 去redis中取 组装cookie时存的随机数 _redis = Redis() _sso_code = _redis.get_hget("app_sso_code", user_id) # 校验cookie解析出来的随机数 和存在redis中的随机数是否一致 if not is_none(_sso_code) and not is_none(sso_code) and sso_code != _sso_code: logger.info("账号在其他设备登陆了%s"% user_id) return BaseError.not_local_login() # 解密auth_token中的sign sign = aes_decrypt(auth_token) # 利用user_id + '#$%' + redis中随机数 + '#$%' + md5加密后的字符串 组装_sign _sign = hashlib.sha1(AUTH_COOKIE_KEY + user_id + refresh_time + sso_code).hexdigest() if sign == _sign: return f(*args, **kw) else: return BaseError.not_login() return decorated_function # 制作response并返回的函数,包括制作response的请求头和请求体 # login_data : 登录操作时必传参数,必须包括user_id,其余可以包括想带入cookie中的参数 格式{“user_id”:“12345”} def return_data(code=200, data=None, msg=u'成功', login_data=None): data = {} if data is None else data data_json = json.dumps({'traceID': get_trace_id(), 'code': code, 'msg': msg, 'data': data}) response = make_response(data_json, 200) response.headers['Content-Type'] = 'application/json' if request.headers.get('Origin') in MOBILE_ORIGIN_URL: response.headers['Access-Control-Allow-Origin'] = request.headers.get('Origin') else: response.headers['Access-Control-Allow-Origin'] = 'https://i.mofanghr.com' response.headers['Access-Control-Allow-Methods'] = 'PUT,GET,POST,DELETE' response.headers['Access-Control-Allow-Credentials'] = 'true' response.headers['Access-Control-Allow-Headers'] = "Referer,Accept,Origin,User-Agent" create_auth_cookie(response, login_data) return response def create_auth_cookie(response, login_data): # 进场获取缓存cookie中的信息 auth_token = request.cookies.get('auth_token') refresh_time = request.cookies.get('refresh_time') # refresh_time = 1482222171524 cookie_info = request.cookies.get('cookie_info') # 设置cookie过期时间点, time.time() + 60 表示一分钟后 outdate = time.time() + 60 * 60 * 24 * 30 # 记录登录态三天 _redis = Redis() #login 如果是登录操作,cookie中所有信息重新生成 if not is_none(login_data) and not is_none(login_data.get('user_id')): user_id = login_data.get('user_id') sso_code = "vJjPtawUC8" # 如果当前版本不设置单点登录,则使用固定随机码 if get_version() in SSO_VERSION: # 如果版本设置单点登录,随机生成10位随机数,当做单机唯一登录码,存在redis中方便对比 # 只要不清除登录态,单点登录则不会触发 sso_code = get_randoms(10) _redis.set_hset("app_sso_code", user_id, sso_code) # 产生新的refresh_time 和新的auth_token refresh_time = str(int(round(time.time() * 1000))) sign = get_hashlib(AUTH_COOKIE_KEY + user_id + refresh_time + sso_code) auth_token = aes_encrypt(sign) login_data['sso_code'] = sso_code cookie_info = aes_encrypt(json.dumps(login_data)) #not login 如果不是登录操作,并且cookie中auth_token和refresh_time存在 if not is_none(auth_token) and not is_none(refresh_time): now_time = int(round(time.time() * 1000)) differ_minuts = (now_time - int(refresh_time)) / (60*1000) if differ_minuts >= 30 and is_none(login_data): user_id = get_cookie_info().get('user_id') if not is_none(user_id): refresh_time = str(int(round(time.time() * 1000))) sso_code = _redis.get_hget("app_sso_code", user_id) # 获取单点登录码 sign = get_hashlib(AUTH_COOKIE_KEY + user_id + refresh_time + sso_code) auth_token = aes_encrypt(sign) response.set_cookie('auth_token', auth_token, path='/', domain='.mofanghr.com', expires=outdate) response.set_cookie('refresh_time', str(refresh_time), path='/', domain='.mofanghr.com', expires=outdate) response.set_cookie('cookie_info', cookie_info, path='/', domain='.mofanghr.com', expires=outdate) return response def request_check(func): @wraps(func) def decorator(*args, **kw): # 校验参数 try: check_rule = build_check_rule(str(request.url_rule),str(request.rule_version), list(request.url_rule.methods & set(METHODS))) check_func = check_param.get_check_rules().get(check_rule) if check_func: check_func(*args, **kw) except BusinessException as e: if not is_none(e.func): return e.func elif not is_none(e.code) and not is_none(e.msg): business_exception_log(e) return return_data(code=e.code, msg=e.msg) # 监听抛出的异常 try: if request.trace_id is not None and request.full_path is not None: logger.info('trace_id is:' + request.trace_id + ' request path:' + request.full_path) return func(*args, **kw) except BusinessException as e: if e.func is not None: return e.func() elif e.code is not None and e.msg is not None: business_exception_log(e) if e.code == SYSTEM_CODE_404 or e.code == SYSTEM_CODE_503: return return_data(code=e.code, msg='很抱歉服务器异常,请您稍后再试') else: return return_data(code=e.code, msg=e.msg) else: return request_fail() except Exception: return request_fail() return decorator # 使用AES算法对字符串进行加密 def aes_encrypt(text): aes_crypt = AesCrypt(AES_KEY) # 初始化密钥 encrypt_text = aes_crypt.encrypt(text) # 加密字符串 return encrypt_text # 使用AES算法对字符串进行解密 def aes_decrypt(text): aes_crypt = AesCrypt(AES_KEY) # 初始化密钥 decrypt_text = aes_crypt.decrypt(text) # 解密成字符串 return decrypt_text # 获取并解析cookie_info def get_cookie_info(): req_cookie = request.cookies.get('cookie_info') if req_cookie is not None: try: aes_crypt = AesCrypt(AES_KEY) # 初始化密钥 aes_crypt_cookie = aes_crypt.decrypt(req_cookie) req_cookie = json.loads(aes_crypt_cookie) return req_cookie except: return {} else: return {} def business_exception_log(e): if not is_none(request.trace_id) and not is_none(request.full_path): logger.error('BusinessException, code: %s, msg: %s trace_id: %s request path: %s' % (e.code, e.msg, request.trace_id, request.full_path)) else: logger.error('BusinessException, code: %s, msg: %s' % (e.code, e.msg)) def request_fail(func=BaseError.system_exception): if not is_none(request.trace_id): logger.error('request fail trace id is:' + str(request.trace_id)) logger.error(traceback.format_exc()) return func() # 工厂模式,根据不同的后端项目域名生成不同的项目对象,传入request_api中组成接口 # 针对不同的后端服务项目,实例化后生成不同的service对象 # 有三个属性 service.url 后端项目的域名 || "http://user.service.mofanghr.com/" # service.params 项目通用普通参数,放在params中 || {“userID”:"12345"} # service.common_params 项目通用公共参数,拼在url问号?后面 || {“userID”:"12345"} class Service_api(object): def __init__(self,url,params=None,common_params=None): self.url = url self.params = params self.common_params = common_params def __str__(self): return self.url # 工厂模式,根据传如的不同项目加上不同的后端接口生成不同的接口函数,请求接口并处理返回值 # base_prj 针对不同的后端服务项目,实例化后的service对象, # 有三个属性 base_prj.url 后端项目的域名 || "http://user.service.mofanghr.com/" # base_prj.params 项目通用普通参数,放在params中 || {“userID”:"12345"} # base_prj.common_params 项目通用公共参数,拼在url问号?后面 || {“userID”:"12345"} # # fixUrl 接口的后缀url,拼在项目域名后,形成完整的访问接口 # baseParams 如果同一个接口需要增加相同的参数,可以放在baseParams中,增加拓展性 || {‘reqSource’:‘Mf1.0’} class Requests_api(object): def __init__(self, base_prj, fixUrl, baseParams=None): self.base_prj = base_prj self.url = base_prj.url + fixUrl self.baseParams = baseParams # 执行请求后端的函数,get请求 # fixUrl 同一个项目下的不同接口后缀 || inner/careerObjective/get.json # params 访问携带参数 || {“userID”:"12345"} def implement_get(self, params, **kwargs): self.url_add_common_param() self.url_add_business_param(params) logger.info(self.url) resp = requests.get(self.url, **kwargs) if resp.status_code == 200: ret_data = resp.json() else: raise BusinessException(code=resp.status_code, msg=resp.text, url=resp.url) # 如果请求成功,但是后端返回的code不是200,则记录日志 if 'code' not in ret_data or ret_data.get('code') != 200: logger.error( 'api_return_error, code: %s, msg: %s, url: %s' % (ret_data.get('code'), ret_data.get('msg'), self.url)) return ret_data # 执行请求后端的函数,post请求 # headers 请求头,如果有特殊的请求头要求,可以使用||{'Content-Type': 'application/json;charset=utf-8'} def implement_post(self, params, headers=None,**kwargs): self.url_add_common_param() params = {'params':json.dumps(params)} resp = requests.post(self.url, data=params, headers=headers, **kwargs) logger.info(self.url) if resp.status_code == 200: ret_data = resp.json() else: raise BusinessException(code=resp.status_code, msg=resp.text, url=resp.url) if 'code' not in ret_data or ret_data.get('code') != 200: logger.error( 'api_return_error, code: %s, msg: %s, url: %s' % (ret_data.get('code'), ret_data.get('msg'), self.url)) return ret_data # 格式化params,并组装URL的函数,将参数值转化为url编码拼接到self.url后面 # self.url http://user.service.mofanghr.com/inner/crm/getSessionAndJobList.json?params=%22%3a+%22jobStandardCardID%24% def url_add_business_param(self, params): # 如果存在需要整个项目传的参数,则增加进params中 if not is_none(self.base_prj.params): for _service_key in self.base_prj.params: params[_service_key] =self.base_prj.params.get(_service_key) # 如果存在需要整个接口传的参数,则增加进params中 if not is_none(self.baseParams): for _key in self.baseParams: params[_key] = self.baseParams.get(_key) self.url = self.url + '&params=' + urllib.parse.quote_plus(json.dumps(params)) # 给URL增加公共参数,所有接口都会有的参数 # self.base_prj.common_params 个性化公共参数,个别接口可以根据需求自行添加 || {“serviceName”:“send”} def url_add_common_param(self): self.url = self.url + '?traceID=' + get_trace_id() + '&callSystemID=' + str(CALL_SYSTEM_ID) if not is_none(self.base_prj.common_params): for key,value in self.base_prj.common_params.items(): self.url = self.url + "&" + str(key) + "=" + str(value) def __str__(self): return self.url # 例子 # SEARCH_API_URL = Service_api("http://search.service.mofanghr.com/", common_params={"callSystemID":str(CALL_SYSTEM_ID)}) # 每个service实例化一个 # job_search = Requests_api(SEARCH_API_URL,"inner/all/job/search.json") # 每个接口实例化一个 # # result = job_search.implement_get({"userID":"12345"}) # 前端函数中使用
zyzFlask
/zyzFlask-0.2.0.tar.gz/zyzFlask-0.2.0/core/core.py
core.py
import os import time import importlib import warnings from core import global_settings from core.exceptions import ImproperlyConfigured class Settings: def __init__(self, settings_module): # update this dict from global settings (but only for ALL_CAPS settings) for setting in dir(global_settings): if setting.isupper(): setattr(self, setting, getattr(global_settings, setting)) # store the settings module in case someone later cares self.SETTINGS_MODULE = settings_module mod = importlib.import_module(self.SETTINGS_MODULE) tuple_settings = ( "INSTALLED_APPS", "TEMPLATE_DIRS", "LOCALE_PATHS", ) self._explicit_settings = set() for setting in dir(mod): if setting.isupper(): setting_value = getattr(mod, setting) if (setting in tuple_settings and not isinstance(setting_value, (list, tuple))): raise ImproperlyConfigured("The %s setting must be a list or a tuple. " % setting) setattr(self, setting, setting_value) self._explicit_settings.add(setting) if not self.SECRET_KEY: raise ImproperlyConfigured("The SECRET_KEY setting must not be empty.") if self.is_overridden('DEFAULT_CONTENT_TYPE'): warnings.warn('The DEFAULT_CONTENT_TYPE setting is deprecated.', RemovedInDjango30Warning) if hasattr(time, 'tzset') and self.TIME_ZONE: # When we can, attempt to validate the timezone. If we can't find # this file, no check happens and it's harmless. zoneinfo_root = '/usr/share/zoneinfo' if (os.path.exists(zoneinfo_root) and not os.path.exists(os.path.join(zoneinfo_root, *(self.TIME_ZONE.split('/'))))): raise ValueError("Incorrect timezone setting: %s" % self.TIME_ZONE) # Move the time zone info into os.environ. See ticket #2315 for why # we don't do this unconditionally (breaks Windows). os.environ['TZ'] = self.TIME_ZONE time.tzset() def is_overridden(self, setting): return setting in self._explicit_settings def __repr__(self): return '<%(cls)s "%(settings_module)s">' % { 'cls': self.__class__.__name__, 'settings_module': self.SETTINGS_MODULE, }
zyzFlask
/zyzFlask-0.2.0.tar.gz/zyzFlask-0.2.0/core/conf.py
conf.py
from core.core import BaseError from core.core import return_data class Error(BaseError): @staticmethod def mobile_null_error(): return return_data(code=-100, msg=u'手机号不能为空') @staticmethod def password_null_error(): return return_data(code=-101, msg=u'密码不能为空') @staticmethod def account_status_close(): return return_data(code=-102, data={'phone':'01056216855'}, msg=u'抱歉,您的账号已经被冻结\n如有疑问请联系客服010-56216855') @staticmethod def account_not_exist(): return return_data(code=-103, msg=u'账号不存在') @staticmethod def invalid_verify_code(): return return_data(code=-104, msg=u'验证码错误') @staticmethod def invalid_account_password(): return return_data(code=-105, msg=u'账号不存在或密码错误') @staticmethod def verify_code_null(): return return_data(code=-106, msg=u'验证码不能为空') @staticmethod def user_info_null(): return return_data(code=-107, msg=u'用户信息不存在') @staticmethod def user_update_fail(): return return_data(code=-108, msg=u'更新用户资料失败') @staticmethod def verify_code_app_key_null(): return return_data(code=-109, msg=u'验证码appkey不能为空') @staticmethod def verify_code_verify_type_null(): return return_data(code=-110, msg=u'验证码verifyType不能为空') @staticmethod def verify_code_sms_limit(): return return_data(code=-111, msg=u'短信验证码请求超过上限,请使用语音验证码') @staticmethod def change_identity_fail(): return return_data(code=-112, msg=u'用户身份选择失败') @staticmethod def reset_password_fail(): return return_data(code=-113, msg=u'重置密码失败') @staticmethod def account_null(): return return_data(code=-114, msg=u'账号不能为空') @staticmethod def verify_code_limit(): return return_data(code=-115, msg=u'验证码请求超过上限,请明天再试') @staticmethod def password_null(): return return_data(code=-116, msg=u'您的账号没有设置密码\n请使用验证码进入') @staticmethod def update_company_permission(): return return_data(code=-117, msg=u'您没有修改公司权限') @staticmethod def company_no_repetition_binding(): return return_data(code=-118, msg=u'该用户已绑定其它公司\n不能再绑定') @staticmethod def verify_code_past_due(): return return_data(code=-119, msg=u'验证码错误') @staticmethod def verify_code_voice_limit(): return return_data(code=-120, msg=u'语音验证码请求超过6次') @staticmethod def save_fail(): return return_data(code=-121, msg=u'保存信息失败') @staticmethod def get_fail(): return return_data(code=-122, msg=u'获取信息失败') @staticmethod def upload_fail(): return return_data(code=-123, msg=u'上传失败') @staticmethod def send_job_fail(): return return_data(code=-124, msg=u'很遗憾,贵公司今天已经发布20个职位,请明天再来吧!') @staticmethod def enterprise_send_job_fail(): return return_data(code=-125, msg=u'您的账号尚未认证,认证后才能发布更多职位喔!') @staticmethod def old_password_fail(): return return_data(code=-126, msg=u'旧密码错误') @staticmethod def old_password_null(): return return_data(code=-127, msg=u'原密码不能为空') @staticmethod def password_type_error(): return return_data(code=-128, msg=u'修改密码类型不正确') @staticmethod def resume_not_full(): return return_data(code=-130, msg=u'简历信息不完整') @staticmethod def reserved_repeated(): return return_data(code=-131, msg=u'你已申请过,不能重复申请') @staticmethod def no_point(): return return_data(code=-132, msg=u'抱歉,账户余额不足\n可赚取积分或联系我们(010-56216855)充值M币') @staticmethod def limit_call_phone(): return return_data(code=-133, msg=u'拨打电话超过上限') @staticmethod def limit_im_unautherized_count(): return return_data(code=-135, msg=u'很抱歉,认证后才能与更多候选人主动发起沟通') @staticmethod def can_not_cancel_hr_auth(): return return_data(code=-136, msg=u'您的认证已通过\n不可取消认证') #所有时段都已预约已满 @staticmethod def reserved_full(): return return_data(code=-139, msg=u'该职位预约已满\n去看看更多好职位吧') #报错时,和可预约时段为0时 @staticmethod def session_overdue(): return return_data(code=-139, msg=u'非常遗憾!\n该职位没有可预约的场次\n去看看更多好职位吧') # 过期,还有其他场次可预约 @staticmethod def has_effective_session(): return return_data(code=-140, msg=u'该时段面试已经开始\n换个时段吧') # 已满,还有其他场次可预约 @staticmethod def has_effective_session2(): return return_data(code=-141, msg=u'该时段面试预约已满\n换个时段吧') # 已暂停,还有其他场次可预约 @staticmethod def no_session_reserve2(): return return_data(code=-172, msg=u'该时段面试已暂停\n换个时段吧') # 已取消,还有其他场次可预约 @staticmethod def cancel_has_session(): return return_data(code=-171, msg=u'该时段面试已取消\n换个时段吧') # 没有可预约的时段 @staticmethod def no_session_reserve(): return return_data(code=-170, msg=u'没有可预约的时段\n去看看更多好职位吧') @staticmethod def verify_code_risk_limit(): return return_data(code=-142, data={'phone':'01056216855'}, msg=u'验证码请求超出上限,如您需要紧急登录请联系客服(010-56216855)') @staticmethod def invalid_image_verify_code(): return return_data(code=-143, msg=u'请先输入正确的图片验证码') @staticmethod def update_mobile_error(): return return_data(code=-144, msg=u'手机号码已经存在') @staticmethod def mobile_exist_error(): return return_data(code=-145, msg=u'手机号码已经存在') @staticmethod def created_job_error(): return return_data(code=-146, msg=u'请勿发布重复职位') @staticmethod def backend_system_error(): return return_data(code=-147, msg=u'后台系统异常') @staticmethod def verify_code_limit2(): return return_data(code=-148, data={'phone':'01056216855'}, msg=u'验证码请求超过上限,请明天尝试\n如需紧急修改手机号码,请联系客服(010-56216855)') @staticmethod def verify_code_risk_limit2(): return return_data(code=-149, data={'phone': '01056216855'}, msg=u'验证码请求超过上限,请明天尝试\n如需紧急修改手机号码,请联系客服(010-56216855)') @staticmethod def verify_code_risk_limit3(): return return_data(code=-150, data={'phone': '01056216855'}, msg=u'验证码请求超过上限,请明天尝试\n如需紧急修改密码,请联系客服(010-56216855)') @staticmethod def invalid_uuid_code(): return return_data(code=-151, msg=u'二维码过期') @staticmethod def get_resume_error(): return return_data(code=-152, msg=u'获取简历失败') @staticmethod def invalid_uuid_key(): return return_data(code=-153, msg=u'校验参数不合法') @staticmethod def get_question_error(): return return_data(code=-154, msg=u'获取答题失败') @staticmethod def get_company_error(): return return_data(code=-155, msg=u'获取公司失败') @staticmethod def delete_resume_error(): return return_data(code=-156, msg=u'删除简历失败') @staticmethod def send_email_error(): return return_data(code=-157, msg=u'发送邮件失败') @staticmethod def no_flow_ok(): return return_data(code=-158, msg=u'没有需要确认的面试') @staticmethod def get_company_list_error(): return return_data(code=-159, msg=u'获取公司列表信息失败') @staticmethod def get_advisor_seror(): return return_data(code=-160, msg=u'获取顾问信息失败') @staticmethod def get_postion_seror(): return return_data(code=-161, msg=u'获取职位信息失败') @staticmethod def no_career_Area(): return return_data(code=-163, msg=u'求职期望城市为空') @staticmethod def no_gender(): return return_data(code=-164, msg=u'性别为空') @staticmethod def get_survey_answer_error(): return return_data(code=-165, msg=u'获取答题失败') @staticmethod def open_red_packet_error(): return return_data(code=-166, msg=u'打开红包失败') @staticmethod def user_payment_error(): return return_data(code=-167, msg=u'提现失败') @staticmethod def user_wechat_mapping_error(): return return_data(code=-167, msg=u'微信绑定失败') @staticmethod def withdraw_filed_fail(): return return_data(code=-167, msg=u'提现失败') @staticmethod def withdraw_filed_not_enouth(): return return_data(code=-160, msg=u'余额小于20,不可提现,继续努力吧!') @staticmethod def create_resume_error(): return return_data(code=-168, msg=u'创建简历失败') @staticmethod def upload_number_error(): return return_data(code=-169, msg=u'上传简历数量超过限制')
zyzFlask
/zyzFlask-0.2.0.tar.gz/zyzFlask-0.2.0/core/error.py
error.py
REQUEST_SUCCESS = 1 REQUEST_FAIL = -1 LOGIN_FAIL = -401 OTHER_LOGIN_FAIL = -402 SYSTEM_CODE_404 = 404 SYSTEM_CODE_503 = 503 SYSTEM_ERROR = '很抱歉服务器异常,请您稍后再试' METHODS = ["GET", "POST", "DELETE", "PUT"] DEFAULT_METHODS = ["GET", "POST"] MOBILE_ORIGIN_URL = ['https://chart.mofanghr.com', 'https://i.mofanghr.com', 'https://m.mofanghr.com', 'https://ad.mofanghr.com', 'http://crm.mofanghr.com', 'http://crm1.mofanghr.com', 'https://vip.mofanghr.com']
zyzFlask
/zyzFlask-0.2.0.tar.gz/zyzFlask-0.2.0/core/global_settings.py
global_settings.py
import random import string import hashlib from Crypto.Cipher import AES from binascii import b2a_hex, a2b_hex def get_randoms(num): ran_str = ''.join(random.sample(string.ascii_letters + string.digits, num)) return ran_str def get_hashlib(text): return hashlib.sha1(text).hexdigest() class AesCrypt(object): def __init__(self,key): self.key = key self.iv = key self.mode = AES.MODE_CBC # CBC模式是目前公认AES中最安全的加密模式 # 加密函数,如果text不是16的倍数【加密文本text必须为16的倍数!】,那就补足为16的倍数 def encrypt(self,text): cipher = AES.new(self.key, self.mode, self.iv) # 参数(密钥,加密模式,偏移量) # 这里密钥key 长度必须为16(AES-128)、24(AES-192)、或32(AES-256)Bytes 长度.目前AES-128足够用 length = 16 add = length - (len(text) % length) text = text + ('\0' * add) self.ciphertext = cipher.encrypt(text) # 因为AES加密时候得到的字符串不一定是ascii字符集的,输出到终端或者保存时候可能存在问题 # 所以这里统一把加密后的字符串转化为16进制字符串 ,当然也可以转换为base64加密的内容,可以使用b2a_base64(self.ciphertext) return b2a_hex(self.ciphertext) def decrypt(self,text): cipher = AES.new(self.key, self.mode, self.iv) plain_text = cipher.decrypt(a2b_hex(text)) return plain_text.rstrip('\0') # 删掉后面补位用的‘\0’
zyzFlask
/zyzFlask-0.2.0.tar.gz/zyzFlask-0.2.0/core/utils.py
utils.py
class CheckParam(object): def __init__(self): self.check_rules = dict() def register_check_param(self, check_param=None, url_prefix=''): if not isinstance(check_param, SubCheckParam): raise RuntimeError('check_param is not a SubCheckParam object. ' 'type: %s' % type(check_param)) check_rules = check_param.get_check_rules() for check_rule in check_rules: url = check_rule.url version = check_rule.version methods = check_rule.methods f = check_rule.f self.check_rules[str({'url':url_prefix + url, 'version':sorted(version), 'methods': sorted(methods)})] = f def get_check_rules(self): return self.check_rules class SubCheckParam(object): def __init__(self,default_methods): self.check_rules = list() self.default_methods = default_methods def check(self, url=None, version=None, methods=None): methods = methods if methods is not None else self.default_methods def decorator(f): if not url: raise ValueError('A non-empty url is required.') if not methods: raise ValueError('A non-empty method is required.') self.__add_check_rule(url, version, methods, f) return f return decorator def __add_check_rule(self, url, version, methods, f): if version and isinstance(version, list): version = sorted(version) else: version = [] self.check_rules.append(CheckRule(url=url, version=version, methods=methods, f=f)) def get_check_rules(self): return self.check_rules class CheckRule(object): def __init__(self,url, version, methods, f): self.url = url self.version = version self.methods = methods self.f = f def build_check_rule(url=None, version=None, methods=None): if not url: raise ValueError('A non-empty url is required.') if not methods: raise ValueError('A non-empty method is required.') if version and isinstance(version, list): version = sorted(version) else: version = [] return str({'url': url,'version': version,'methods': sorted(methods)})
zyzFlask
/zyzFlask-0.2.0.tar.gz/zyzFlask-0.2.0/core/check_param.py
check_param.py
import os import re import time import fcntl import shutil import logging.config from configs import LOGGING_PATH from stat import ST_MTIME from logging import FileHandler, StreamHandler from logging.handlers import TimedRotatingFileHandler, RotatingFileHandler class StreamHandler_MP(StreamHandler): """ 一个处理程序类,它将日志记录适当地格式化,写入流。用于多进程 """ def emit(self, record): """ 发出一个记录。首先seek(写文件流时控制光标的)到文件的最后,以便多进程登录到同一个文件。 """ try: if hasattr(self.stream, "seek"): self.stream.seek(0, 2) except IOError as e: pass StreamHandler.emit(self, record) class FileHandler_MP(FileHandler,StreamHandler_MP): """ 为多进程写入格式化日志记录到磁盘文件的处理程序类。 """ def emit(self, record): """ 发出一条记录。 如果因为在构造函数中指定了延迟而未打开流,则在调用超类发出之前打开它。 """ if self.stream is None: self.stream = self._open() StreamHandler_MP.emit(self,record) class RotatingFileHandler_MP(RotatingFileHandler,FileHandler_MP): """ 处理程序,用于记录一组文件,当当前文件达到一定大小时,该文件从一个文件切换到下一个文件。 基于logging.RotatingFileHandler文件处理程序,用于多进程的修正 """ _lock_dir = '.lock' if os.path.exists(_lock_dir): pass else: os.mkdir(_lock_dir) def doRollover(self): """ 做一个翻转,如__init__()中所描述的,对于多进程,我们使用深拷贝(shutil.copy)而不是重命名。 """ self.stream.close() if self.backupCount > 0: for i in range(self.backupCount - 1, 0, -1): sfn = "%s.%d" % (self.baseFilename, i) dfn = "%s.%d" % (self.baseFilename, i + 1) if os.path.exists(sfn): if os.path.exists(dfn): os.remove(dfn) shutil.copy(sfn, dfn) dfn = self.baseFilename + ".1" if os.path.exists(dfn): os.remove(dfn) if os.path.exists(self.baseFilename): shutil.copy(self.baseFilename, dfn) self.mode = "w" self.stream = self._open() def emit(self, record): """ 发送一条记录, 将记录输出到文件中,如doRollover().对于多进程,我们使用文件锁。还有更好的方法吗? """ try: if self.shouldRollover(record): self.doRollover() FileLock = self._lock_dir + '/' + os.path.basename(self.baseFilename) + '.' + record.levelName f = open(FileLock, "w+") fcntl.flock(f.fileno(), fcntl.LOCK_EX) FileHandler_MP.emit(self, record) fcntl.flock(f.fileno(), fcntl.LOCK_UN) f.close() except (KeyboardInterrupt, SystemExit): raise except: self.handleError(record) class TimedRoeatingFileHandler_MP(TimedRotatingFileHandler, FileHandler_MP): """ 处理程序,用于logging文件,以一定的时间间隔旋转日志文件。 如果 backupCount > 0,则在进行翻转时,保持不超过backupCount个数的文件。 最老的被删除。 """ _lock_dir = '.lock' if os.path.exists(_lock_dir): pass else: os.mkdir(_lock_dir) def __init__(self, filename, when='h', interval=1, backupCount=0, encoding=None, delay=0, utc=0): FileHandler_MP.__init__(self, filename, 'a', encoding, delay) self.encoding = encoding self.when = when self.backupCount = backupCount self.utc = utc # 计算实际更新间隔,这只是更新之间的秒数。还设置在更新发生时使用的文件名后缀。 # 当前的'when'为什么是时得到支持: # S - Seconds 秒 # M - Minutes 分钟 # H - Hours 小时 # D - Days 天 # 在夜里进行文件更新 # W{0-6} -在某一天更新;0代表星期一 6代表星期日 # “when” 的的情况并不重要;小写或大写字母都会起作用。 if self.when == 'S': self.suffix = "%Y-%m-%d_%H-%M-%S" self.extMatch = r"^\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2}$" elif self.when == "M": self.suffix = "%Y-%m-%d_%H-%M" self.extMatch = r"^\d{4}-\d{2}-\d{2}_\d{2}-\d{2}$" elif self.when == "H": self.suffix = "%Y-%m-%d_%H" self.extMatch = r"^\d{4}-\d{2}-\d{2}_\d{2}$" elif self.when == "D" or self.when == "MIDNIGHT": self.suffix = "%Y-%m-%d" self.extMatch = r"^\d{4}-\d{2}-\d{2}$" elif self.when.startswith('W'): if len(self.when) != 2: raise ValueError("你必须指定每周更新日志的时间从0到6(0是星期一): %s" % self.when) if self.when[1] < '0' or self.when[1] > '6': raise ValueError("每周更新时间是无效日期: %s" % self.when) self.dayOfWeek = int(self.when[1]) self.suffix = "%Y-%m-%d" self.extMatch = r"^\d{4}-\d{2}-\d{2}" else: raise ValueError("指定的更新间隔无效: %s" % self.when) self.extMatch = re.compile(self.extMatch) if interval != 1: raise ValueError("无效翻滚间隔,必须为1。") def shouldRollover(self, record): """ 确定是否发生翻滚。记录不被使用,因为我们只是比较时间,但它需要方法签名是相同的。 """ if not os.path.exists(self.baseFilename): # print(“文件不存在”) return 0 cTime = time.localtime(time.time()) mTime = time.localtime(os.stat(self.baseFilename)[ST_MTIME]) if self.when == "S" and cTime[5] != mTime[5]: # print("cTime:",cTime[5],"mTime:",mTime[5]) return 1 elif self.when == "M" and cTime[4] != mTime[4]: # print("cTime:",cTime[4],"mTime:",mTime[4]) return 1 elif self.when == "H" and cTime[3] != mTime[3]: # print("cTime:",cTime[3],"mTime:",mTime[3]) return 1 elif (self.when == "MIDNIGHT" or self.when == 'D') and cTime[2] != mTime[2]: # print("cTime:",cTime[2],"mTime:",mTime[2]) return 1 elif self.when == "W" and cTime[1] != mTime[1]: # print("cTime:",cTime[1],"mTime:",mTime[1]) return 1 else: return 0 def doRollover(self): """ 更新日志文件; 在这种情况下,当发生翻滚时,日期/时间戳被附加到文件名。但是,您希望文件被命名为间隔开始,而不是当前时间。 如果有一个备份计数,那么我们必须得到一个匹配的文件名列表,对它们进行排序,并删除具有最长后缀的列表。 对于多进程,我们使用深拷贝(shutil.copy)而不是重命名。 """ if self.stream: self.stream.close() # 获得这个序列开始的时间,并使它成为一个时间表. # t = self.rolloverAT - self.interval t = int(time.time()) if self.utc: timeTuple = time.gmtime(t) else: timeTuple = time.localtime(t) dfn = self.baseFilename + '.' + time.strftime(self.suffix, timeTuple) if os.path.exists(dfn): os.remove(dfn) if os.path.exists(self.baseFilename): shutil.copy(self.baseFilename,dfn) # print("%s -> %s" %(self.baseFilename, dfn)) # os.rename(self.baseFilename,dfn) if self.backupCount > 0: # 查找最旧的日志文件并删除它 # s = glob.glob(self.baseFilename + ".20*") # if len(s) > self.backupCount: # s.sort() # os.remove(s[0]) for s in self.getFilesToDelete(): os.remove(s) self.mode = 'w' self.stream = self._open() def emit(self, record): """ 发送一条记录 将记录输出到文件中,如SE所述。对于多进程,我们使用文件锁。还有更好的方法吗? """ try: if self.shouldRollover(record): self.doRollover() FileLock = self._lock_dir + '/' + os.path.basename(self.baseFilename) + '.' + record.levelname f = open(FileLock,"w+") fcntl.flock(f.fileno(), fcntl.LOCK_EX) FileHandler_MP.emit(self,record) fcntl.flock(f.fileno(), fcntl.LOCK_UN) f.close() except (KeyboardInterrupt, SystemExit): raise except: self.handleError(record) logging.config.fileConfig(LOGGING_PATH) # 这个路径是log日志,的配置文件的路径 logger = logging.getLogger()
zyzFlask
/zyzFlask-0.2.0.tar.gz/zyzFlask-0.2.0/core/log.py
log.py
class BusinessException(Exception): def __init__(self, code=None, msg=None, func=None, url=None): self.code = code self.msg = msg self.func = func self.url = url class PermissionDenied(Exception): """The user did not have permission to do that""" pass class ViewDoesNotExist(Exception): """The requested view does not exist""" pass class MiddlewareNotUsed(Exception): """This middleware is not used in this server configuration""" pass class ImproperlyConfigured(Exception): """Django is somehow improperly configured""" pass class FieldError(Exception): """Some kind of problem with a model field.""" pass
zyzFlask
/zyzFlask-0.2.0.tar.gz/zyzFlask-0.2.0/core/exceptions.py
exceptions.py
AES_KEY = 'magicCube-moFang-r' AUTH_COOKIE_KEY = 'moFangHr-r' REDIS_HOST = '10.0.3.6' REDIS_PORT = 6379 REDIS_PASSWORD = 'SDOjx2HcHu' SQLALCHEMY_DATABASE_URI = 'postgresql://mfmobile:[email protected]:3433/mofang_mobile' SQLALCHEMY_POOL_SIZE = 50 SQLALCHEMY_TRACK_MODIFICATIONS = True
zyzFlask
/zyzFlask-0.2.0.tar.gz/zyzFlask-0.2.0/configs/prod_setting.py
prod_setting.py
AES_KEY = 'magicCube-moFang-d' AUTH_COOKIE_KEY = 'moFangHr-d' REDIS_HOST = '10.0.3.6' REDIS_PORT = 6379 REDIS_PASSWORD = 'SDOjx2HcHu' SQLALCHEMY_DATABASE_URI = 'postgresql://mftest:[email protected]:5432/mofang_mobile' SQLALCHEMY_POOL_SIZE = 50 SQLALCHEMY_TRACK_MODIFICATIONS = True
zyzFlask
/zyzFlask-0.2.0.tar.gz/zyzFlask-0.2.0/configs/dev_setting.py
dev_setting.py
SECRET_KEY = 'zyz_secret_key_32459' SESSION_TYPE = 'filesystem' DEFAULT_METHODS = ['POST', 'GET'] CALL_SYSTEM_ID = 1 PLATFORM = 1203 SSO_VERSION = ['3.6.0'] # 进行单点登录限制的版本 LOGGING_PATH = 'configs/logging.conf' USER_API_URL = 'http://user.service.mofanghr.com/' VERIFY_API_URL = 'http://verify.service.mofanghr.com/' FILE_API_URL = 'http://file.service.mofanghr.com/' RELATION_API_URL = 'http://relation.service.mofanghr.com/' SEARCH_API_URL = 'http://search.service.mofanghr.com/' TAG_API_URL = 'http://tag.service.mofanghr.com/' MESSAGE_API_URL = 'http://message.service.mofanghr.com/' BEHAVIOUR_API_URL = 'http://behaviour.service.mofanghr.com/' WALLET_API_URL = 'http://service.service.mofanghr.com/' FLOW_API_URL = 'http://flow.service.mofanghr.com/' ORDER_API_URL = 'http://order.service.mofanghr.com/' B_API_URL = 'http://b.service.mofanghr.com/' USERTASK_API_URL = 'http://usertask.service.mofanghr.com/' SUPPORT_API_URL = 'http://crmsupport.service.mofanghr.com/' RISK_API_URL = 'http://risk.service.mofanghr.com/' EMG_SJ_API_URL = 'http://172.16.25.36:9034/' OLD_API_URL = 'http://172.16.22.6:9090/' AVCHAT_URL = 'http://avchat.mofanghr.com/' H5_URL_URL = 'https://i.mofanghr.com/' CRM_API_URL = 'http://crm.mofanghr.com/' CRM1_API_URL = 'http://crm1.mofanghr.com/' EMG_API_URL = 'http://emg.mofanghr.com/' PAYMENT_API_URL = 'http://payment.mofanghr.com/'
zyzFlask
/zyzFlask-0.2.0.tar.gz/zyzFlask-0.2.0/configs/base_setting.py
base_setting.py
import os from configs.base_setting import * flask_env = os.getenv('FLASK_ENV') print('FLASK_ENV: %s' % flask_env) if flask_env == "PROD": print('Loading config: PROD') from configs.prod_setting import * else: print('Loading config: DEV') from configs.dev_setting import *
zyzFlask
/zyzFlask-0.2.0.tar.gz/zyzFlask-0.2.0/configs/__init__.py
__init__.py
# pypi-helloworld This is a demo pypi helloworld project to show a PyPI project end2end workflow. Enjoy!
zyzhi
/zyzhi-0.2.1.tar.gz/zyzhi-0.2.1/README.md
README.md
from setuptools import setup, find_packages import io with io.open('README.md', 'rt', encoding='utf8') as f: readme = f.read() setup( name='zyzhi', license='Apache License 2.0', version='0.2.1', maintainer='Yuanzhen Zhou', maintainer_email='[email protected]', packages=find_packages(include=['zyzhi', 'zyzhi.*']), zip_safe=False, include_package_data=True, url='https://github.com/zhouyuanzhen/pypi-helloworld', author='Yuanzhen Zhou', author_email='[email protected]', description='A sample PyPI helloworld project', long_description=readme, install_requires=[], extras_require={ 'test': [ 'pytest', 'coverage', ], }, )
zyzhi
/zyzhi-0.2.1.tar.gz/zyzhi-0.2.1/setup.py
setup.py
======== ``zyzz`` ======== ------------------- Python util modules -------------------
zyzz
/zyzz-1.0.1.tar.gz/zyzz-1.0.1/README.rst
README.rst
import os from setuptools import setup, find_packages def read(fname): return open(os.path.join(os.path.abspath(os.path.dirname(__file__)), fname)).read() setup( name = 'zyzz', version = '1.0.1', description = u'Python util modules', long_description = read('README.rst'), author = 'Dmitry Bashkatov', author_email = '[email protected]', url = 'http://github.com/nailgun/zyzz/', classifiers = [ 'Development Status :: 4 - Beta', 'Environment :: Console', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Topic :: Utilities', ], package_dir = {'': 'src'}, packages = find_packages('src'), include_package_data = True, install_requires = [], )
zyzz
/zyzz-1.0.1.tar.gz/zyzz-1.0.1/setup.py
setup.py
import requests import time class CrawlAPI(object): VERSION = 0.2 @classmethod def wrap_api(cls, json_data): json_data["meta"]["version"] = CrawlAPI.VERSION @classmethod def get_task_id(cls): url = 'http://127.0.0.1:3000/get-task-id' task_id = requests.get(url).text return task_id @classmethod def get_create_time(cls): creat_time = int(round(time.time() * 1000)) return creat_time @classmethod def upload(cls, data): url_post = 'http://127.0.0.1:3000/kno-storage-req' input = requests.post(url_post, json=data) if input.status_code == 200: print("插入成功") else: raise Exception("插入失败") return input.status_code
zz-crawler-api
/zz_crawler_api-0.1-py3-none-any.whl/zz_crawler_api/zz_crawl_api.py
zz_crawl_api.py
# 本代码是有关消息中间件组件的一些使用 ##rabbimq ``` import zz_spider from zz_spider.rabbit_mq.MqDeal import DealRabbitMQ ``` ### 使用 ``` # -*- coding: utf-8 -*- # @Time : 10/14/21 5:38 PM # @Author : ZZK # @File : test_spider.py # @describe : from zz_spider.RabbitMq import DealRabbitMQ host = xxx port = xxx user = xxx password = xxx queue_name = xxx url_port = xxx def spider(res): """ :param res: :return: """ for i in res: data =i #mongo(data) print(i) mqobeject = DealRabbitMQ(host,user=user,passwd=password,port=port,url_port=url_port) #spider_main 放置抓取的主要函数 mqobeject.consumer_mq(spider_main=spider,queue_name=queue_name) #将错误数据写入失败队列中,后缀名必须为_error mqobeject.send_mq(queue_name='123_error',msg={'1':1}) ``` ##kafka ``` # 发送 producer = KkProducer( bootstrap_servers=bootstrap_servers, options_name=options_name, try_max_times=try_max_times ) params: bootstrap_servers 创建连接域名:端口; (例:127.0.0.1:9092) options_name 话题名称:topics (例:topic_{flow_id}_{execute_id}_{data_time}) try_max_times 失败重试最大次数, 默认为 3 test:测试连接 test_send.py # 接收 ``` > 如需帮助请联系 [email protected]
zz-spider
/zz_spider-1.0.0.tar.gz/zz_spider-1.0.0/README.md
README.md
# -*- coding: utf-8 -*- # @Time : 10/14/21 6:55 PM # @Author : ZZK # @File : setup.py # @describe : import setuptools with open('README.md', 'r', encoding='utf-8') as fh: long_description = fh.read() setuptools.setup( name='zz_spider', version='1.0.0', author='zzk', author_email='[email protected]', description='python使用MQ的场景', long_description=long_description, long_description_content_type="text/markdown", url='https://github.com/qpzzk/zz_spider', packages=setuptools.find_packages(), classifiers=[ 'Programming Language :: Python :: 3.7', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent' ], install_requires=[ "requests>=2.22.0", "pika>=1.2.0", "retrying>=1.3.3", "environs==9.4.0", "confluent-kafka==1.8.2", "kafka==1.3.5", "kafka-python==2.0.2", "pykafka==2.8.0", "loguru==0.5.3", ], )
zz-spider
/zz_spider-1.0.0.tar.gz/zz_spider-1.0.0/setup.py
setup.py
from zz_spider import KkProducer, KafkaReceive, KkOffset class KafkaClient(object): _INSTANCE = None def __new__(cls, *args, **kwargs): if not cls._INSTANCE: cls._INSTANCE = super().__new__(cls) return cls._INSTANCE _shortcut = { "product": KkProducer, "KafkaReceive": KafkaReceive, "KkOffset": KkOffset } def __init__(self, bootstrap_servers: str, options_name: str, task_info: dict, try_max_times: int = 3, type: int=0 ): self.bootstrap_servers = bootstrap_servers self.options_name = options_name self.task_info = task_info self.type = type self.try_max_times = try_max_times self.session = self._session @property def _session(self): return self._shortcut[list(self._shortcut.keys())[self.type]]
zz-spider
/zz_spider-1.0.0.tar.gz/zz_spider-1.0.0/zz_spider/KafkaClient.py
KafkaClient.py
# -*- coding:utf-8 -*- import json from confluent_kafka import cimpl from kafka import (SimpleClient, KafkaConsumer) from kafka.common import (OffsetRequestPayload, TopicPartition) from confluent_kafka.admin import (AdminClient, NewTopic) class KkOffset(object): def __init__(self, bootstrap_servers=None, topic=None, group_id=None): self.bootstrap_servers = bootstrap_servers self.topic = topic self.group_id = group_id self.get_topic_offset = self._get_topic_offset self.get_group_offset = self._get_group_offset self.surplus_offset = self._surplus_offset @property def _get_topic_offset(self): # topic的offset总和 client = SimpleClient(self.bootstrap_servers) partitions = client.topic_partitions[self.topic] offset_requests = [OffsetRequestPayload(self.topic, p, -1, 1) for p in partitions.keys()] offsets_responses = client.send_offset_request(offset_requests) return sum([r.offsets[0] for r in offsets_responses]) @property def _get_group_offset(self): # topic特定group已消费的offset的总和 consumer = KafkaConsumer(bootstrap_servers=self.bootstrap_servers, group_id=self.group_id, ) pts = [TopicPartition(topic=self.topic, partition=i) for i in consumer.partitions_for_topic(self.topic)] result = consumer._coordinator.fetch_committed_offsets(pts) return sum([r.offset for r in result.values()]) @property def _surplus_offset(self) -> int: """ :param topic_offset: topic的offset总和 :param group_offset: topic特定group已消费的offset的总和 :return: 未消费的条数 """ lag = self.get_topic_offset - self.get_group_offset if lag < 0: return 0 return lag def watch_topics(topic: str, bootstrap_servers: str): # 查看所有话题 consumer = KafkaConsumer(topic, bootstrap_servers=bootstrap_servers, group_id=('',), value_deserializer=json.loads, auto_offset_reset='earliest', enable_auto_commit=True, auto_commit_interval_ms=1000) return consumer.topics() def create_topics(topic_list: list, bootstrap_servers: str): """ :param host_port_and: 10.0.0.1:9092,10.0.0.2:9092,10.0.0.3:9092 :type list: The split with "," and same as port :return: create topics infos """ a = AdminClient({'bootstrap.servers': bootstrap_servers}) new_topics = [ NewTopic(topic, num_partitions=3, replication_factor=1) for topic in topic_list ] fs = a.create_topics(new_topics) for topic, f in fs.items(): try: f.result() # result‘s itself 为空 return {'status': True, 'data': f"创建成功: {topic}"} except cimpl.KafkaException: return {'status': True, 'data': "话题已存在"} except Exception as ex: return {'status': False, 'msg': f"请检查连接异常: {ex}"} finally: pass
zz-spider
/zz_spider-1.0.0.tar.gz/zz_spider-1.0.0/zz_spider/KafkaInstant.py
KafkaInstant.py
# -*- coding:utf-8 -*- from __future__ import absolute_import from anti_useragent import UserAgent import json import re import time from kafka import KafkaProducer import sys, os sys.path.append(os.path.abspath('..')) try: from module import logging from exceptions import KafkaInternalError from KafkaInstant import (KkOffset, create_topics, watch_topics) except: from ..module import logging from ..exceptions import KafkaInternalError from ..KafkaInstant import (KkOffset, create_topics, watch_topics) """ :param 生产消息队列 : 传输时的压缩格式 compression_type="gzip" 每条消息的最大大小 max_request_size=1024 * 1024 * 20 重试次数 retries=3 """ class KkProducer(KafkaProducer): pending_futures = [] log = logging.get_logger('kafka_product') def __init__(self, options_name, try_max_times=3, *args, **kwargs): super(KkProducer, self).__init__( value_serializer=lambda m: json.dumps(m).encode('ascii'), retries=try_max_times, metadata_max_age_ms=10000000, request_timeout_ms=30000000, *args, **kwargs) self.topic = options_name self.try_max_times = try_max_times self.flush_now = self._flush def sync_producer(self, data_li: list or dict, partition=0, times: int = 0): """ 同步发送 数据 :param data_li: 发送数据 :return: """ if not self.det_topic(): raise KafkaInternalError(err_code=-1, err_msg='创建topic失败') if times > self.try_max_times: return False if not isinstance(data_li, list): future = self.send(self.topic, data_li, partition=partition) record_metadata = future.get(timeout=10) # 同步确认消费 partition = record_metadata.partition # 数据所在的分区 offset = record_metadata.offset # 数据所在分区的位置 print('save success:{0}, partition: {1}, offset: {2}'.format(record_metadata, partition, offset)) for data in data_li: if not isinstance(data, dict): raise TypeError data.update({ "options_name": self.topic, "data": data, }) future = self.send(self.topic, data, partition=partition) record_metadata = future.get(timeout=10) # 同步确认消费 partition = record_metadata.partition # 数据所在的分区 offset = record_metadata.offset # 数据所在分区的位置 print('save success:{0}, partition: {1}, offset: {2}'.format(record_metadata, partition, offset)) def asyn_producer_callback(self, data_li: list or dict, partition=0, times: int = 0): """ 异步发送数据 + 发送状态处理 :param data_li:发送数据 :return: """ if not self.det_topic(): raise KafkaInternalError(err_code=-1, err_msg='创建topic失败') if times > self.try_max_times: # 异常数据 self.log.debug( f'【数据丢失】:发送数据失败:{data_li}' ) return False data_item = { "data": None, "queue_name": self.topic, "result": None, } try: if isinstance(data_li, list): for data in data_li: if data and (len(data) > 0): result = True else: result = False data_item.update({"data": data, "result": result}) self.send(topic=self.topic, value=data_item, partition=partition).add_callback( self.send_success, data_item).add_errback(self.send_error, data_item, times + 1, self.topic) else: data_item.update({"data": data_li}) self.send(topic=self.topic, value=data_item, partition=partition).add_callback( self.send_success, data_item).add_errback(self.send_error, data_item, times + 1, self.topic) except Exception as ex: raise KafkaInternalError(err_code=-1, err_msg=ex) # pass finally: self.flush() # 批量提交 # self.flush_now() # 批量提交 print('这里批量提交') def det_topic(self): create_topics([self.topic], bootstrap_servers=self.config['bootstrap_servers']) all_topic = watch_topics(self.topic, bootstrap_servers=self.config['bootstrap_servers']) if self.topic not in all_topic: create_topics([self.topic], bootstrap_servers=self.config['bootstrap_servers']) return False else: return True def origin_length(self, datas, max_nums: int = 1000000): # 判断数据数量 if not datas: return {'status': False, 'msg': u'数据为空'} if not isinstance(datas, list): return {'status': True, 'data': 1} if len(datas) > max_nums: return {'status': False, 'msg': u'批次数据量过大'} return {'status': True, 'data': len(datas)} @classmethod def send_success(*args, **kwargs): """异步发送成功回调函数""" print('save success is', args) return True @classmethod def send_error(*args, **kwargs): """异步发送错误回调函数""" print('save error', args) with open('/opt/ldp/{0}.json'.format(args[2]), 'a+', encoding='utf-8') as wf: json.dump(obj=args[0], fp=wf) return False def save_local(self, file_name: str, data_origin: dict): try: with open( f'{file_name}.json', 'a+', encoding='utf-8' ) as wf: json.dump(obj=data_origin, fp=wf) except Exception as ex: return ex @property def _flush(self, timeout=None): flush = super().flush(timeout=timeout) for future in self.pending_futures: if future.failed(): # raise KafkaError(err_code='flush', err_msg='Failed to send batch') pass self.pending_futures = [] return flush
zz-spider
/zz_spider-1.0.0.tar.gz/zz_spider-1.0.0/zz_spider/KafakProduct.py
KafakProduct.py
import json import os import re import time import threading, multiprocessing from kafka import KafkaConsumer from KafakProduct import KkProducer from module import logging class SavePipeline: """ :parameter data save pipeline as file :param save_data to localfile.json """ def __init__(self, file_name, log_path=os.path.abspath(os.path.dirname(os.getcwd())) + '/'): self.log_path = log_path self.file_name = file_name def __setitem__(self, key, value): return getattr(key, value) def __getitem__(self, item): return self def save_data(self, doing_type: str = 'a+', data_item: dict = lambda d: json.loads(d)): """ 数据存储 :param doing_type: str :param data_item: dict :return: 写入json文件 """ whole_path = self.log_path + '{0}.json'.format(self.file_name) print(whole_path, 'A' * 20) try: with open(whole_path, doing_type, encoding='utf-8') as wf: result = wf.write(json.dumps(data_item) + '\n') if not result: return {'status': False, 'msg': '写入失败'} return {'status': True, 'data': '写入成功'} except Exception as e: return {'status': False, 'msg': str(e)} finally: pass class KafkaReceive(threading.Thread): log = logging.get_logger('kafka_consume') def __init__(self, bootstrap_servers, topic, group_id, client_id=''): self.bootstrap_servers = bootstrap_servers self.topic = topic self.group_id = group_id self.client_id = client_id threading.Thread.__init__(self) self.stop_event = threading.Event() def stop(self): self.stop_event.set() def run(self): consumer = KafkaConsumer(bootstrap_servers=self.bootstrap_servers, group_id=self.group_id, auto_offset_reset='latest', consumer_timeout_ms=1000) consumer.subscribe([self.topic]) sucess_is = 0 error_is = 0 get_list = [] for msg in consumer: self.log.info(f'topic: {msg.topic}') self.log.info(f'partition: {msg.partition}') self.log.info(f'key: {msg.key}; value: {msg.value}') self.log.info(f'offset: {msg.offset}') msg_item = json.loads(json.dumps(msg.value.decode('utf-8'))) result = SavePipeline(self.topic).save_data(data_item=msg_item) if result.get('status', False): sucess_is += 1 else: error_is += 1 get_list.append(msg_item) consumer.close() return sucess_is, error_is, get_list def restart_program(): import sys python = sys.executable os.execl(python, python, * sys.argv) def task(bootstrap_servers, topic, times_count: int = 4): from KafkaInstant import KkOffset offset = KkOffset( bootstrap_servers=bootstrap_servers, topic=topic, group_id=topic ) print(offset.surplus_offset, type(offset.surplus_offset)) import time tasks = [ KafkaReceive( bootstrap_servers=bootstrap_servers, topic=topic, group_id=topic) for c in range(times_count) ] for t in tasks: t.start() time.sleep(10) for task in tasks: task.stop() for task in tasks: task.join() if __name__ == '__main__': # task() KafkaReceive( bootstrap_servers='', topic='', group_id='').run()
zz-spider
/zz_spider-1.0.0.tar.gz/zz_spider-1.0.0/zz_spider/KafkaConsume.py
KafkaConsume.py
# -*- coding: utf-8 -*- # @Time : 10/14/21 6:53 PM # @Author : ZZK # @File : __init__.py # @describe : from __future__ import absolute_import from zz_spider.RabbitMq import * name = "zz_spider"
zz-spider
/zz_spider-1.0.0.tar.gz/zz_spider-1.0.0/zz_spider/__init__.py
__init__.py
# -*- coding: utf-8 -*- # @Time : 10/14/21 5:21 PM # @Author : ZZK # @File : RabbitMq.py # @describe :处理rabbitmq内容 import pika import requests import json from retrying import retry from pika.exceptions import AMQPError def retry_if_rabbit_error(exception): return isinstance(exception, AMQPError) class DealRabbitMQ(object): def __init__(self,host,user, passwd,port,url_port): """ :param host: :param user: :param passwd: :param port: :param url_port: :param spider_main: """ self.host = host self.user = user self.passwd = passwd self.port = port self.url_port = url_port credentials = pika.PlainCredentials(user, passwd) connection = pika.BlockingConnection(pika.ConnectionParameters(host=host, port=port, credentials=credentials, heartbeat=0)) # heartbeat 表示7200时间没反应后就报错 self.channel = connection.channel() self.channel.basic_qos(prefetch_size=0, prefetch_count=1) @retry(retry_on_exception=retry_if_rabbit_error) def get_count_by_url(self,queue_name): """ :return: ready,unack,total """ try: url = 'http://{0}:{1}/api/queues/%2f/{2}'.format(self.host,self.url_port,queue_name) r = requests.get(url, auth=(self.user, self.passwd)) if r.status_code != 200: return -1 res = r.json() # ready,unack,total true_count = self.channel.queue_declare(queue=queue_name, durable=True).method.message_count lax_count = max(true_count,res['messages']) return res['messages_ready'], res['messages_unacknowledged'], lax_count # return dic['messages'] except Exception as e: print("rabbitmq connect url error:",e) raise ConnectionError("rabbitmq connect url error:{0}".format(e)) def callback(self,ch, method, properties, body): """ :param ch: :param method: :param properties: :param body: :return: """ res = json.loads(body) self.spider_main(res) ch.basic_ack(delivery_tag=method.delivery_tag) @retry(retry_on_exception=retry_if_rabbit_error) def consumer_mq(self,spider_main,queue_name): self.spider_main = spider_main self.channel.basic_consume(queue_name, self.callback, False) while self.channel._consumer_infos: ready_count, unack_count, total_count = self.get_count_by_url(queue_name) print("ready中的消息量:{0}",total_count) if total_count == 0: #当真实消息量以及ready中全为0才代表消耗完 self.channel.stop_consuming() # 退出监听 self.channel.connection.process_data_events(time_limit=1) try: self.channel.queue_delete(queue_name) print("消费完成:成功清除队列") except TypeError: print("消费完成:成功清除队列") @retry(retry_on_exception=retry_if_rabbit_error) def send_mq(self,queue_name,msg): """ 往错误队列中写入数据 :return: """ if not queue_name or not msg: raise ValueError("queue_name or msg is None") if 'error' not in queue_name: raise ValueError("queue_name is not error queue") self.channel.queue_declare(queue=queue_name, durable=True) self.channel.basic_publish(exchange='', routing_key=queue_name, body=str(msg), properties=pika.BasicProperties(delivery_mode=2) ) print('成功写入消息')
zz-spider
/zz_spider-1.0.0.tar.gz/zz_spider-1.0.0/zz_spider/RabbitMq.py
RabbitMq.py
import sys import subprocess class Utils(object): def install(self, package): subprocess.call([sys.executable, "-m", "pip", "install", package])
zz-spider
/zz_spider-1.0.0.tar.gz/zz_spider-1.0.0/module/misc.py
misc.py
from .log import LogFormatter logging = LogFormatter() # from misc import Utils # misc = Utils() __all__ = [logging]
zz-spider
/zz_spider-1.0.0.tar.gz/zz_spider-1.0.0/module/__init__.py
__init__.py
from __future__ import absolute_import, unicode_literals import sys import socket from os.path import dirname, abspath, join # from misc import Utils try: from environs import Env except: # Utils().install('environs') from environs import Env try: from loguru import logger except: # Utils().install("loguru") from loguru import logger def set_log_config(formatter, logfile=None): return { "default": { "handlers": [ { "sink": sys.stdout, "format": formatter, "level": "TRACE" }, { "sink": "info.log" if not logfile else logfile, "format": formatter, "level": "INFO", "rotation": '1 week', "retention": '30 days', 'encoding': 'utf-8' }, ], "extra": { "host": socket.gethostbyname(socket.gethostname()), 'log_name': 'default', 'type': 'None' }, "levels": [ dict(name="TRACE", icon="✏️", color="<cyan><bold>"), dict(name="DEBUG", icon="❄️", color="<blue><bold>"), dict(name="INFO", icon="♻️", color="<bold>"), dict(name="SUCCESS", icon="✔️", color="<green><bold>"), dict(name="WARNING", icon="⚠️", color="<yellow><bold>"), dict(name="ERROR", icon="❌️", color="<red><bold>"), dict(name="CRITICAL", icon="☠️", color="<RED><bold>"), ] }, 'kafka': True } class LogFormatter(object): default_formatter = '<green>{time:YYYY-MM-DD HH:mm:ss,SSS}</green> | ' \ '[<cyan>{extra[log_name]}</cyan>] <cyan>{module}</cyan>:<cyan>{name}</cyan>:<cyan>{function}</cyan>:<cyan>{line}</cyan> | ' \ '<red>{extra[host]}</red> | ' \ '<level>{level.icon}{level: <5}</level> | ' \ '<level>{level.no}</level> | ' \ '<level>{extra[type]}</level> | ' \ '<level>{message}</level> ' kafka_formatter = '{time:YYYY-MM-DD HH:mm:ss,SSS}| ' \ '[{extra[log_name]}] {module}:{name}:{function}:{line} | ' \ '{extra[host]} | ' \ '{process} | ' \ '{thread} | ' \ '{level: <5} | ' \ '{level.no} | ' \ '{extra[type]}| ' \ '{message} ' def __init__(self): self.logger = logger def setter_log_handler(self, callback=None): assert callable(callback), 'callback must be a callable object' self.logger.add(callback, format=self.kafka_formatter) def get_logger(self, name=None): log_config = set_log_config(self.default_formatter, f'{name}.log') config = log_config.pop('default', {}) if name: config['extra']['log_name'] = name self.logger.configure(**config) return self.logger @staticmethod def format(spider, meta): if hasattr(spider, 'logging_keys'): logging_txt = [] for key in spider.logging_keys: if meta.get(key, None) is not None: logging_txt.append(u'{0}:{1} '.format(key, meta[key])) logging_txt.append('successfully') return ' '.join(logging_txt)
zz-spider
/zz_spider-1.0.0.tar.gz/zz_spider-1.0.0/module/log.py
log.py
# zz-test 简单IP代理池 simple_pp 是个 异步并发IP代理验证工具,速度很快,一千个代理半分钟左右可完成。 ### 安装 ```pip install -U simple-proxy-pool``` 或下载 repo (e.g., ```git clone https://github.com/ffreemt/simple-proxy-pool.git``` 换到 simple-proxy-pool目录执行 ``` python install -r requirements.txt python setup.py develop ``` ### 代理验证原理 通过IP代理访问 www.baidu.com, 能成功获取百度返回的头则代理有效。再检查头里面是否含'via', 不含'via'即为匿名代理。参考 aio_headers.py。 ### 用法 #### 命令行 ##### 简单用法 ```python -m simple_pp``` simple_pp 会试着以各种方式搜集到不少于 200 个代理,验证后将有效代理输出到屏幕上。 ##### 普通用法 用户可以提供自己的代理:直接将自由格式的代理贴在命令行后面,或提供含自由格式代理的文件名贴在命令行后面,或在运行 `python -m simple_pp` 前将代理拷入系统剪贴板。 ```python -m simple_pp``` 贴入需验证的IP代理(格式 ip:端口, 以空格、回车非数字字母或中文隔开均可)。或: ```python -m simple_pp file1 file2 ...``` 文件内含以上格式的IP代理 也可以用pipe,例如 ``` curl "https://www.freeip.top/?page=1" | python -m simple_pp ``` #### 高级用法 显示详细用法 ```python -m simple_pp -h``` 给定代理数目 ```python -m simple_pp -p 500``` 只显示有效匿名代理 ```python -m simple_pp -a``` 给定代理数目、只显示有效匿名代理 ```python -m simple_pp -p 800 -a``` #### python 程序内调用 ``` from simple_pp import simple_pp from pprint import pprint ip_list = [ip1, ip2, ...] res = simple_pp(ip_list) pprint(res) ``` 输出 res 里格式为: res[0] = ip_list[0] +(是否有效,是否匿名,响应时间秒) 可参看__main__.py 或 tests 里面的文件。有疑问或反馈可发 Issues。 例如 ``` import asyncio import httpx from simple_pp import simple_pp simple_pp(['113.53.230.167:80', '36.25.243.51:80']) ``` 输出: [('113.53.230.167:80', True, False, 0.31), ('36.25.243.51:80', True, True, 0.51)] -> 第一个代理为透明代理,第二个代理为匿名代理 也可以直接将网页结果送给 simple_pp, 例如 ``` import re import asyncio import httpx from pprint import pprint from simple_pp import simple_pp arun = lambda x: asyncio.get_event_loop().run_until_complete(x) _ = [elm for elm in simple_pp([':'.join(elm) if elm[1] else elm[0] for elm in re.findall(r'(?:https?://)?(\d{1,3}(?:\.\d{1,3}){3})(?:[\s\t:\'",]+(\d{1,4}))?', arun(httpx.get('https://www.freeip.top/?page=1')).text)]) if elm[-3] is True] pprint(_) # 可能拿到将近 10 个代理 # 或 _ = [elm for elm in simple_pp(arun(httpx.get('https://www.freeip.top/?page=1')).text) if elm[-3] is True] pprint(_) # ditto ``` ### 鸣谢 * 用了 jhao 的 proxypool 项目里几个文件。感谢jhao开源。
zz-test
/zz-test-0.0.6.tar.gz/zz-test-0.0.6/README.md
README.md
r''' simple proxy pool + proxy validation ''' # pylint: disable=invalid-name from pathlib import Path import os import re from setuptools import setup, find_packages # https://stackoverflow.com/questions/49689880/proper-way-to-parse-requirements-file-after-pip-upgrade-to-pip-10-x-x # try: # for pip >= 10 # from pip._internal.req import parse_requirements # from pip._internal.download import PipSession # except ImportError: # for pip <= 9.0.3 # from pip.req import parse_requirements # from pip.download import PipSession name = """zz-test""" description = ' '.join(name.split('-')) + ' playground' # dir_name, *_ = find_packages() dir_name = '_'.join(name.split('-')) curr_dir = Path(__file__).absolute().parent.__str__() # curr_dir = Path(__file__).parent.__str__() def read_requirements_file(*args): ''' paths, filename''' # filepath = Path(*args) print(*args) filepath = os.path.join(*args) try: # lines = filepath.read_text('utf-8').split('\n') # lines = open(filepath.__str__(), encoding='utf-8', errors='ignore') lines = open(filepath, encoding='utf-8', errors='ignore') except Exception as exc: print(exc) return None # strip '#' lines = [elm.split('#', 1)[0].strip() for elm in lines] # remove empty lines return filter(None, lines) def parse_requirements(filename): """ load requirements from a pip requirements file """ lineiter = (line.strip() for line in open(filename)) return [line for line in lineiter if line and not line.startswith("#")] # _ = open(f'{dir_name}/__init__.py').read() _ = Path(f'{dir_name}/__init__.py').read_text(encoding='utf-8') version, *_ = re.findall(r"__version__\W*=\W*'([^']+)'", _) targz = 'v_' + version.replace('.', '') + '.tar.gz' # install_requires = [*read_requirements_file(curr_dir, 'requirements.txt')] # noqa # install_requires = [] # requriements = # does not work # parse_requirements(os.path.join(os.path.dirname(__file__), 'requirements.txt'), session=PipSession()) # install_requires = [str(requirement.req) for requirement in requriements] # install_requires = [ # 'requests', # 'aiohttp', # 'httpx', # 'multidict', # 'async_timeout', # 'html2text', # 'loguru', # 'tqdm', # 'pyperclip', # ] install_reqs = parse_requirements('requirements.txt') # reqs is a list of requirement # e.g. ['django==1.5.1', 'mezzanine==1.4.6'] # reqs = [str(ir.req) for ir in install_reqs] README_rst = f'{curr_dir}/README.md' long_description = open(README_rst, encoding='utf-8').read() if Path(README_rst).exists() else '' setup( name=name, packages=find_packages(), # packages=['simple_pp'], version=version, description=description, long_description=long_description, long_description_content_type='text/markdown', keywords=['machine translation', 'free', 'scraping', ], author="mikeee", url=f'http://github.com/ffreemt/{name}', download_url='https://github.com/ffreemt/yeekit-tr-free/archive/' + targz, # install_requires=install_requires, install_requires=install_reqs, classifiers=[ 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.6', 'License :: OSI Approved :: MIT License', ], license='MIT License', )
zz-test
/zz-test-0.0.6.tar.gz/zz-test-0.0.6/setup.py
setup.py
from zz_test import zz_test def main(): zz_test() if __name__ == '__main__': main()
zz-test
/zz-test-0.0.6.tar.gz/zz-test-0.0.6/zz_test/__main__.py
__main__.py
from loguru import logger def zz_test(): logger.debug('d msg') logger.info('i msg') logger.error('e msg')
zz-test
/zz-test-0.0.6.tar.gz/zz-test-0.0.6/zz_test/zz_test.py
zz_test.py
from .zz_test import zz_test __version__ = '0.0.6' __date__ = '2020.1.3' VERSION = tuple(__version__.split('.'))
zz-test
/zz-test-0.0.6.tar.gz/zz-test-0.0.6/zz_test/__init__.py
__init__.py
def print_lol(the_list,indent = False, level = 0): for each_item in the_list: if isinstance(each_item, list): print_lol(each_item,indent, level + 1) else: if indent: for tab_stop in range(level): print("\t",end="") print(each_item)
zz_nester
/zz_nester-1.3.0.tar.gz/zz_nester-1.3.0/zz_nester.py
zz_nester.py
from distutils.core import setup setup ( name = "zz_nester", version = "1.3.0", py_modules = ["zz_nester"], author = "adai041", author_url = "[email protected]", url = "", description = "My first Python File", )
zz_nester
/zz_nester-1.3.0.tar.gz/zz_nester-1.3.0/setup.py
setup.py
# dg_pip #### 介绍 {**以下是 Gitee 平台说明,您可以替换此简介** Gitee 是 OSCHINA 推出的基于 Git 的代码托管平台(同时支持 SVN)。专为开发者提供稳定、高效、安全的云端软件开发协作平台 无论是个人、团队、或是企业,都能够用 Gitee 实现代码托管、项目管理、协作开发。企业项目请看 [https://gitee.com/enterprises](https://gitee.com/enterprises)} #### 软件架构 软件架构说明 #### 安装教程 1. xxxx 2. xxxx 3. xxxx #### 使用说明 1. xxxx 2. xxxx 3. xxxx #### 参与贡献 1. Fork 本仓库 2. 新建 Feat_xxx 分支 3. 提交代码 4. 新建 Pull Request #### 特技 1. 使用 Readme\_XXX.md 来支持不同的语言,例如 Readme\_en.md, Readme\_zh.md 2. Gitee 官方博客 [blog.gitee.com](https://blog.gitee.com) 3. 你可以 [https://gitee.com/explore](https://gitee.com/explore) 这个地址来了解 Gitee 上的优秀开源项目 4. [GVP](https://gitee.com/gvp) 全称是 Gitee 最有价值开源项目,是综合评定出的优秀开源项目 5. Gitee 官方提供的使用手册 [https://gitee.com/help](https://gitee.com/help) 6. Gitee 封面人物是一档用来展示 Gitee 会员风采的栏目 [https://gitee.com/gitee-stars/](https://gitee.com/gitee-stars/)
zzaTest
/zzaTest-0.0.1.tar.gz/zzaTest-0.0.1/README.md
README.md
#!/usr/bin/python # encoding: utf-8 from setuptools import setup, find_packages setup( name="zzaTest", version="0.0.1", license="MIT Licence", packages=find_packages(), include_package_data=True, platforms="any", install_requires=[] )
zzaTest
/zzaTest-0.0.1.tar.gz/zzaTest-0.0.1/setup.py
setup.py
from zzam.temperature import fahrenheit2celsius, celsius2fahrenheit def test_fahrenheit2celsius(): assert fahrenheit2celsius(32) == 0.0 def test_celsius2fahrenheit(): assert celsius2fahrenheit(0) == 32
zzam
/zzam-0.0.4-py3-none-any.whl/tests/test_temperature.py
test_temperature.py
from zzam.datatype import has_alphabetic_characters, has_numeric_characters def test_has_alphabetic_characters(): assert has_alphabetic_characters('1234F') == True def test_not_has_alphabetic_characters(): assert has_alphabetic_characters('12345') == False def test_has_numeric_characters(): assert has_numeric_characters('Hell0') == True def test_not_has_numeric_characters(): assert has_numeric_characters('Hello') == False
zzam
/zzam-0.0.4-py3-none-any.whl/tests/test_datatype.py
test_datatype.py
This is the homepage of our project.
zzarpdf
/zzarpdf-1.0.tar.gz/zzarpdf-1.0/README.md
README.md
import setuptools from pathlib import Path setuptools.setup( name="zzarpdf", version=1.0, long_description=Path("README.md").read_text(), packages=setuptools.find_packages(exclude=["data"]) )
zzarpdf
/zzarpdf-1.0.tar.gz/zzarpdf-1.0/setup.py
setup.py
import setuptools setuptools.setup()
zzarrs
/zzarrs-0.1.0.tar.gz/zzarrs-0.1.0/setup.py
setup.py
# install pip install zzd $$E = MC^2$$
zzd
/zzd-1.0.5.tar.gz/zzd-1.0.5/README.md
README.md
import setuptools with open("README.md", "r") as fh: long_description = fh.read() setuptools.setup( name="zzd", version="1.0.5", author="ChenPing L", author_email="[email protected]", description="some tools", long_description=long_description, long_description_content_type="text/markdown", url="https://github.com/miderxi/zzd_lib", packages=setuptools.find_packages(), classifiers=[ "Programming Language :: Python :: 3", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", ], )
zzd
/zzd-1.0.5.tar.gz/zzd-1.0.5/setup.py
setup.py
[![Python application](https://github.com/AndreiPuchko/zzdb/actions/workflows/main.yml/badge.svg)](https://github.com/AndreiPuchko/zzdb/actions/workflows/main.yml) # The light Python DB API wrapper with some ORM functions (MySQL, PostgreSQL, SQLite) ## Quick start (run demo files) ## - in docker: ```bash git clone https://github.com/AndreiPuchko/zzdb && cd zzdb/database.docker ./up.sh ./down.sh ``` ## - on your system: ```bash pip install zzdb git clone https://github.com/AndreiPuchko/zzdb && cd zzdb # sqlite: python3 ./demo/demo.py # mysql and postgresql: pip install mysql-connector-python psycopg2-binary pushd database.docker && docker-compose up -d && popd python3 ./demo/demo_mysql.py python3 ./demo/demo_postgresql.py pushd database.docker && docker-compose down -v && popd ``` # Features: --- ## Connect ```python from zzdb.db import ZzDb database_sqlite = ZzDb("sqlite3", database_name=":memory:") # or just database_sqlite = ZzDb() database_mysql = ZzDb( "mysql", user="root", password="zztest" host="0.0.0.0", port="3308", database_name="zztest", ) # or just database_mysql = ZzDb(url="mysql://root:[email protected]:3308/zztest") database_postgresql = ZzDb( "postgresql", user="zzuser", password="zztest" host="0.0.0.0", port=5432, database_name="zztest1", ) ``` --- ## Define & migrate database schema (ADD COLUMN only). ```python zzdb.schema import ZzDbSchema schema = ZzDbSchema() schema.add(table="topic_table", column="uid", datatype="int", datalen=9, pk=True) schema.add(table="topic_table", column="name", datatype="varchar", datalen=100) schema.add(table="message_table", column="uid", datatype="int", datalen=9, pk=True) schema.add(table="message_table", column="message", datatype="varchar", datalen=100) schema.add( table="message_table", column="parent_uid", to_table="topic_table", to_column="uid", related="name" ) database.set_schema(schema) ``` --- ## INSERT, UPDATE, DELETE ```python database.insert("topic_table", {"name": "topic 0"}) database.insert("topic_table", {"name": "topic 1"}) database.insert("topic_table", {"name": "topic 2"}) database.insert("topic_table", {"name": "topic 3"}) database.insert("message_table", {"message": "Message 0 in 0", "parent_uid": 0}) database.insert("message_table", {"message": "Message 1 in 0", "parent_uid": 0}) database.insert("message_table", {"message": "Message 0 in 1", "parent_uid": 1}) database.insert("message_table", {"message": "Message 1 in 1", "parent_uid": 1}) # this returns False because there is no value 2 in topic_table.id - schema works! database.insert("message_table", {"message": "Message 1 in 1", "parent_uid": 2}) database.delete("message_table", {"uid": 2}) database.update("message_table", {"uid": 0, "message": "updated message"}) ``` --- ## Cursor ```python cursor = database.cursor(table_name="topic_table") cursor = database.cursor( table_name="topic_table", where=" name like '%2%'", order="name desc" ) cursor.insert({"name": "insert record via cursor"}) cursor.delete({"uid": 2}) cursor.update({"uid": 0, "message": "updated message"}) cursor = database.cursor(sql="select name from topic_table") for x in cursor.records(): print(x) print(cursor.r.name) cursor.record(0)['name'] cursor.row_count() cursor.first() cursor.last() cursor.next() cursor.prev() cursor.bof() cursor.eof() ```
zzdb
/zzdb-0.1.11.tar.gz/zzdb-0.1.11/README.md
README.md
# -*- coding: utf-8 -*- from setuptools import setup packages = \ ['zzdb'] package_data = \ {'': ['*'], 'zzdb': ['UNKNOWN.egg-info/*']} setup_kwargs = { 'name': 'zzdb', 'version': '0.1.11', 'description': 'python DB API wrapper (MySQL, PostgreSQL, SQLite)', 'long_description': '[![Python application](https://github.com/AndreiPuchko/zzdb/actions/workflows/main.yml/badge.svg)](https://github.com/AndreiPuchko/zzdb/actions/workflows/main.yml)\n# The light Python DB API wrapper with some ORM functions (MySQL, PostgreSQL, SQLite)\n## Quick start (run demo files)\n## - in docker:\n```bash\ngit clone https://github.com/AndreiPuchko/zzdb && cd zzdb/database.docker\n./up.sh\n./down.sh\n``` \n## - on your system:\n```bash\npip install zzdb\ngit clone https://github.com/AndreiPuchko/zzdb && cd zzdb\n# sqlite:\npython3 ./demo/demo.py\n# mysql and postgresql:\npip install mysql-connector-python psycopg2-binary\npushd database.docker && docker-compose up -d && popd\npython3 ./demo/demo_mysql.py\npython3 ./demo/demo_postgresql.py\npushd database.docker && docker-compose down -v && popd\n```\n# Features:\n ---\n## Connect\n```python\nfrom zzdb.db import ZzDb\n\ndatabase_sqlite = ZzDb("sqlite3", database_name=":memory:")\n# or just\ndatabase_sqlite = ZzDb()\n\n\ndatabase_mysql = ZzDb(\n "mysql",\n user="root",\n password="zztest"\n host="0.0.0.0",\n port="3308",\n database_name="zztest",\n)\n# or just\ndatabase_mysql = ZzDb(url="mysql://root:[email protected]:3308/zztest")\n\ndatabase_postgresql = ZzDb(\n "postgresql",\n user="zzuser",\n password="zztest"\n host="0.0.0.0",\n port=5432,\n database_name="zztest1",\n)\n```\n---\n## Define & migrate database schema (ADD COLUMN only).\n```python\nzzdb.schema import ZzDbSchema\n\nschema = ZzDbSchema()\n\nschema.add(table="topic_table", column="uid", datatype="int", datalen=9, pk=True)\nschema.add(table="topic_table", column="name", datatype="varchar", datalen=100)\n\nschema.add(table="message_table", column="uid", datatype="int", datalen=9, pk=True)\nschema.add(table="message_table", column="message", datatype="varchar", datalen=100)\nschema.add(\n table="message_table",\n column="parent_uid",\n to_table="topic_table",\n to_column="uid",\n related="name"\n)\n\ndatabase.set_schema(schema)\n```\n---\n## INSERT, UPDATE, DELETE\n```python\ndatabase.insert("topic_table", {"name": "topic 0"})\ndatabase.insert("topic_table", {"name": "topic 1"})\ndatabase.insert("topic_table", {"name": "topic 2"})\ndatabase.insert("topic_table", {"name": "topic 3"})\n\ndatabase.insert("message_table", {"message": "Message 0 in 0", "parent_uid": 0})\ndatabase.insert("message_table", {"message": "Message 1 in 0", "parent_uid": 0})\ndatabase.insert("message_table", {"message": "Message 0 in 1", "parent_uid": 1})\ndatabase.insert("message_table", {"message": "Message 1 in 1", "parent_uid": 1})\n\n# this returns False because there is no value 2 in topic_table.id - schema works!\ndatabase.insert("message_table", {"message": "Message 1 in 1", "parent_uid": 2})\n\n\ndatabase.delete("message_table", {"uid": 2})\n\ndatabase.update("message_table", {"uid": 0, "message": "updated message"})\n```\n---\n## Cursor\n```python\ncursor = database.cursor(table_name="topic_table")\ncursor = database.cursor(\n table_name="topic_table",\n where=" name like \'%2%\'",\n order="name desc"\n)\ncursor.insert({"name": "insert record via cursor"})\ncursor.delete({"uid": 2})\ncursor.update({"uid": 0, "message": "updated message"})\n\ncursor = database.cursor(sql="select name from topic_table")\n\nfor x in cursor.records():\n print(x)\n print(cursor.r.name)\n\ncursor.record(0)[\'name\']\ncursor.row_count()\ncursor.first()\ncursor.last()\ncursor.next()\ncursor.prev()\ncursor.bof()\ncursor.eof()\n```', 'author': 'Andrei Puchko', 'author_email': '[email protected]', 'maintainer': None, 'maintainer_email': None, 'url': None, 'packages': packages, 'package_data': package_data, 'python_requires': '>=3.7,<4.0', } setup(**setup_kwargs)
zzdb
/zzdb-0.1.11.tar.gz/zzdb-0.1.11/setup.py
setup.py
<H1 CLASS="western" style="text-align:center;">ZZDeepRollover</H1> This code enables the detection of rollovers performed by zebrafish larvae tracked by the open-source software <a href="https://github.com/oliviermirat/ZebraZoom" target="_blank">ZebraZoom</a>. This code is still in "beta mode". For more information visit <a href="https://zebrazoom.org/" target="_blank">zebrazoom.org</a> or email us at [email protected]<br/> <H2 CLASS="western">Road Map:</H2> [Preparing the rollovers detection model](#preparing)<br/> [Testing the rollovers detection model](#testing)<br/> [Training the rollovers detection model](#training)<br/> [Using the rollovers detection model](#using)<br/> <a name="preparing"/> <H2 CLASS="western">Preparing the rollovers detection model:</H2> The detection of rollovers is based on deep learning. You must first install pytorch on your machine. It may be better to first create an anaconda environment for this purpose.<br/><br/> You then need to place the output result folders of <a href="https://github.com/oliviermirat/ZebraZoom" target="_blank">ZebraZoom</a> inside the folder "ZZoutput" of this repository.<br/><br/> In order to train the rollovers detection model, you must also manually classify the frames of some of the tracked videos in order to be able to create a training set. Look inside the folder "manualClassificationExamples" for examples of how to create such manual classifications. You then need to place those manual classifications inside the corresponding output result folders of ZebraZoom.<br/><br/> <a name="testing"/> <H2 CLASS="western">Testing the rollovers detection model:</H2> In order to test the accuracy of the rollovers detection model, you can use the script leaveOneOutVideoTest.py, you will need to adjust some variables at the beginning of that script. The variable "videos" is an array that must contain the name of videos for which a manual classification of frames exist and has been placed inside the corresponding output result folder (inside the folder ZZoutput of this repository).<br/><br/> The script leaveOneOutVideoTest.py will loop through all the videos learning the model on all but one video and testing on the video left out.<br/><br/> <a name="training"/> <H2 CLASS="western">Training the rollovers detection model:</H2> Once the model has been tested using the steps described in the previous section, you can now learn the final model on all the videos for which a manual classification of frames exist using the script trainModel.py (you will need to adjust a few variables in that script).<br/><br/> <a name="using"/> <H2 CLASS="western">Using the rollovers detection model:</H2> As mentionned above, you can then use the script useModel.py to apply the rollovers detection model on a video.<br/><br/>
zzdeeprollover
/zzdeeprollover-0.0.4.tar.gz/zzdeeprollover-0.0.4/README.md
README.md
import os import setuptools from setuptools import setup def read_file(file): with open(file) as f: return f.read() setup( name = 'zzdeeprollover', version = read_file(os.path.join(os.path.dirname(os.path.realpath(__file__)), 'zzdeeprollover', 'version.txt')).strip(), license='AGPL-3.0', description = 'Detect rollovers in zebrafish larvae', long_description=read_file(os.path.join(os.path.dirname(os.path.realpath(__file__)), "README.md")), long_description_content_type='text/markdown', author = 'Olivier Mirat', author_email = '[email protected]', url = 'https://github.com/oliviermirat/ZZDeepRollover', download_url = 'https://github.com/oliviermirat/ZZDeepRollover/releases/latest', keywords = ['Animal', 'Behavior', 'Tracking', 'Zebrafish', 'Deep Learning', 'Rolling'], install_requires=[ "scikit-learn", "torch", "numpy", "matplotlib", "torchvision ", "pandas", "pillow", "opencv-python-headless", ], packages=setuptools.find_packages(), data_files=[ ( "zzdeeprollover", [ "zzdeeprollover/version.txt" ], ) ], include_package_data=True, classifiers=[ 'Programming Language :: Python :: 3' ], )
zzdeeprollover
/zzdeeprollover-0.0.4.tar.gz/zzdeeprollover-0.0.4/setup.py
setup.py
# The light Python GUI builder (currently based on PyQt5) # How to start ## With docker && x11: ```bash git clone https://github.com/AndreiPuchko/zzgui.git # sudo if necessary cd zzgui/docker-x11 && ./build_and_run_menu.sh ``` ## With PyPI package: ```bash poetry new project_01 && cd project_01 && poetry shell poetry add zzgui cd project_01 python -m zzgui > example_app.py && python example_app.py ``` ## Explore sources: ```bash git clone https://github.com/AndreiPuchko/zzgui.git cd zzgui pip3 install poetry poetry shell poetry install python3 demo/demo_00.py # All demo launcher python3 demo/demo_01.py # basic: main menu, form & widgets python3 demo/demo_02.py # forms and forms in form python3 demo/demo_03.py # grid form (CSV data), automatic creation of forms based on data python3 demo/demo_04.py # progressbar, data loading, sorting and filtering python3 demo/demo_05.py # nonmodal form python3 demo/demo_06.py # code editor python3 demo/demo_07.py # database app (4 tables, mock data loading) - requires a zzdb package python3 demo/demo_08.py # database app, requires a zzdb package, autoschema ``` ## demo/demo_03.py screenshot ![Alt text](https://andreipuchko.github.io/zzgui/screenshot.png) # Build standalone executable (The resulting executable file will appear in the folder dist/) ## One file ```bash pyinstaller -F demo/demo.py ``` ## One directory ```bash pyinstaller -D demo/demo.py ```
zzgui
/zzgui-0.1.15.tar.gz/zzgui-0.1.15/README.md
README.md
# -*- coding: utf-8 -*- from setuptools import setup packages = \ ['zzgui', 'zzgui.qt5', 'zzgui.qt5.widgets'] package_data = \ {'': ['*']} install_requires = \ ['PyQt5>=5.15.6,<6.0.0', 'QScintilla>=2.13.1,<3.0.0'] setup_kwargs = { 'name': 'zzgui', 'version': '0.1.15', 'description': 'Python GUI toolkit', 'long_description': '# The light Python GUI builder (currently based on PyQt5)\n\n# How to start \n## With docker && x11:\n```bash\ngit clone https://github.com/AndreiPuchko/zzgui.git\n# sudo if necessary \ncd zzgui/docker-x11 && ./build_and_run_menu.sh\n```\n## With PyPI package:\n```bash\npoetry new project_01 && cd project_01 && poetry shell\npoetry add zzgui\ncd project_01\npython -m zzgui > example_app.py && python example_app.py\n```\n## Explore sources:\n```bash\ngit clone https://github.com/AndreiPuchko/zzgui.git\ncd zzgui\npip3 install poetry\npoetry shell\npoetry install\npython3 demo/demo_00.py # All demo launcher\npython3 demo/demo_01.py # basic: main menu, form & widgets\npython3 demo/demo_02.py # forms and forms in form\npython3 demo/demo_03.py # grid form (CSV data), automatic creation of forms based on data\npython3 demo/demo_04.py # progressbar, data loading, sorting and filtering\npython3 demo/demo_05.py # nonmodal form\npython3 demo/demo_06.py # code editor\npython3 demo/demo_07.py # database app (4 tables, mock data loading) - requires a zzdb package\npython3 demo/demo_08.py # database app, requires a zzdb package, autoschema\n```\n\n## demo/demo_03.py screenshot\n![Alt text](https://andreipuchko.github.io/zzgui/screenshot.png)\n# Build standalone executable \n(The resulting executable file will appear in the folder dist/)\n## One file\n```bash\npyinstaller -F demo/demo.py\n```\n\n## One directory\n```bash\npyinstaller -D demo/demo.py\n```\n', 'author': 'Andrei Puchko', 'author_email': '[email protected]', 'maintainer': None, 'maintainer_email': None, 'url': None, 'packages': packages, 'package_data': package_data, 'install_requires': install_requires, 'python_requires': '>=3.7,<4.0', } setup(**setup_kwargs)
zzgui
/zzgui-0.1.15.tar.gz/zzgui-0.1.15/setup.py
setup.py
from distutils.core import setup setup( name = "zzh", version = "1.0.0", description = "yeye", author = "zzh", author_email = "[email protected]", url = "https://github.com/zzhwln/zzh", requires=["aiohttp","lxml"], long_description = """very log""" )
zzh
/zzh-1.0.0.zip/zzh-1.0.0/setup.py
setup.py
import setuptools setuptools.setup( name="zzha529_test", version="1.16", author="zzha529", description="personal redis queue consumer", long_description="personal redis queue consumer", packages=setuptools.find_packages(), install_requires=["redis==4.1.0"], python_requires=">3", )
zzha529-test
/zzha529_test-1.16.tar.gz/zzha529_test-1.16/setup.py
setup.py
import json import redis import random import configparser filename = 'config.ini' def singleton(cls, *args, **kw): instances = {} def _singleton(): if cls not in instances: instances[cls] = cls(*args, **kw) return instances[cls] return _singleton @singleton class RedisPool(object): def __init__(self): con = configparser.ConfigParser() con.read(filename, encoding='utf8') sections = con.sections() self.host = "localhost" self.password = None self.port = 6379 self.db = 0 if 'redis' in sections: redis_section = con['redis'] if 'port' in redis_section: self.port = redis_section['port'] if 'host' in redis_section: self.host = redis_section['host'] if 'db' in redis_section: self.db = redis_section['db'] if 'password' in redis_section: self.password = redis_section['password'] self.random = random.random() self.pool = redis.ConnectionPool(host=self.host, port=self.port, db=self.db, password=self.password, decode_responses=True) def connector(self): return redis.Redis(connection_pool=self.pool, decode_responses=True)
zzha529-test
/zzha529_test-1.16.tar.gz/zzha529_test-1.16/RedisQueue/redis_connector.py
redis_connector.py