code
stringlengths
1
5.19M
package
stringlengths
1
81
path
stringlengths
9
304
filename
stringlengths
4
145
''' 51Degrees Mobile Detector (V3 Trie Wrapper) ================================================== 51Degrees Mobile Detector is a Python wrapper of the C trie-based mobile detection solution by 51Degrees.com. Check out http://51degrees.com for a detailed description, extra documentation and other useful information. :copyright: (c) 2015 by 51Degrees.com, see README.md for more details. :license: MPL2, see LICENSE.txt for more details. ''' from __future__ import absolute_import import os import sys import subprocess import shutil import tempfile import io from setuptools import setup, find_packages, Extension from distutils.command.build_ext import build_ext as _build_ext from distutils import ccompiler from os import path def has_snprintf(): '''Checks C function snprintf() is available in the platform. ''' cc = ccompiler.new_compiler() tmpdir = tempfile.mkdtemp(prefix='51degrees-mobile-detector-v3-trie-wrapper-install-') try: try: source = os.path.join(tmpdir, 'snprintf.c') with open(source, 'w') as f: f.write( '#include <stdio.h>\n' 'int main() {\n' ' char buffer[8];\n' ' snprintf(buffer, 8, "Hey!");\n' ' return 0;\n' '}') objects = cc.compile([source], output_dir=tmpdir) cc.link_executable(objects, os.path.join(tmpdir, 'a.out')) except: return False return True finally: shutil.rmtree(tmpdir) class build_ext(_build_ext): def run(self, *args, **kwargs): return _build_ext.run(self, *args, **kwargs) define_macros = [] if has_snprintf(): define_macros.append(('HAVE_SNPRINTF', None)) '''Gets the path to the README file and populates the long description to display a summary in PyPI. ''' this_directory = path.abspath(path.dirname(__file__)) with io.open(path.join(this_directory, 'README.rst'), encoding='utf-8') as f: long_description = f.read() setup( name='51degrees-mobile-detector-v3-trie-wrapper', version='3.2.18.4', author='51Degrees.com', author_email='info@51degrees.com', cmdclass={'build_ext': build_ext}, packages=find_packages(), include_package_data=True, data_files=[(os.path.expanduser('~/51Degrees'), ['data/51Degrees-LiteV3.4.trie'])], ext_modules=[ Extension('_fiftyone_degrees_mobile_detector_v3_trie_wrapper', sources=[ 'src/trie/51Degrees.c', 'src/cityhash/city.c', 'src/threading.c', 'src/trie/51Degrees_python.cxx', 'src/trie/Provider.cpp', 'src/trie/Match.cpp', ], define_macros=define_macros, extra_compile_args=[ '-w', # Let the linker strip duplicated symbols (required in OSX). '-fcommon', ], ), ], url='http://51degrees.com', description='51Degrees Mobile Detector (Lite C Trie Wrapper).', long_description=long_description, long_description_content_type='text/x-rst', license='MPL2', classifiers=[ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'Topic :: Software Development :: Libraries', 'License :: OSI Approved :: Mozilla Public License 2.0 (MPL 2.0)', 'Programming Language :: C', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.2', 'Programming Language :: Python :: 3.3', 'Operating System :: POSIX', 'Operating System :: MacOS :: MacOS X', ], install_requires=[ 'setuptools', '51degrees-mobile-detector', ], )
51degrees-mobile-detector-v3-trie-wrapper
/51degrees-mobile-detector-v3-trie-wrapper-3.2.18.4.tar.gz/51degrees-mobile-detector-v3-trie-wrapper-3.2.18.4/setup.py
setup.py
# This file was automatically generated by SWIG (http://www.swig.org). # Version 3.0.12 # # Do not make changes to this file unless you know what you are doing--modify # the SWIG interface file instead. from sys import version_info as _swig_python_version_info if _swig_python_version_info >= (2, 7, 0): def swig_import_helper(): import importlib pkg = __name__.rpartition('.')[0] mname = '.'.join((pkg, '_FiftyOneDegreesTrieV3')).lstrip('.') try: return importlib.import_module(mname) except ImportError: return importlib.import_module('_FiftyOneDegreesTrieV3') _FiftyOneDegreesTrieV3 = swig_import_helper() del swig_import_helper elif _swig_python_version_info >= (2, 6, 0): def swig_import_helper(): from os.path import dirname import imp fp = None try: fp, pathname, description = imp.find_module('_FiftyOneDegreesTrieV3', [dirname(__file__)]) except ImportError: import _FiftyOneDegreesTrieV3 return _FiftyOneDegreesTrieV3 try: _mod = imp.load_module('_FiftyOneDegreesTrieV3', fp, pathname, description) finally: if fp is not None: fp.close() return _mod _FiftyOneDegreesTrieV3 = swig_import_helper() del swig_import_helper else: import _FiftyOneDegreesTrieV3 del _swig_python_version_info try: _swig_property = property except NameError: pass # Python < 2.2 doesn't have 'property'. try: import builtins as __builtin__ except ImportError: import __builtin__ def _swig_setattr_nondynamic(self, class_type, name, value, static=1): if (name == "thisown"): return self.this.own(value) if (name == "this"): if type(value).__name__ == 'SwigPyObject': self.__dict__[name] = value return method = class_type.__swig_setmethods__.get(name, None) if method: return method(self, value) if (not static): if _newclass: object.__setattr__(self, name, value) else: self.__dict__[name] = value else: raise AttributeError("You cannot add attributes to %s" % self) def _swig_setattr(self, class_type, name, value): return _swig_setattr_nondynamic(self, class_type, name, value, 0) def _swig_getattr(self, class_type, name): if (name == "thisown"): return self.this.own() method = class_type.__swig_getmethods__.get(name, None) if method: return method(self) raise AttributeError("'%s' object has no attribute '%s'" % (class_type.__name__, name)) def _swig_repr(self): try: strthis = "proxy of " + self.this.__repr__() except __builtin__.Exception: strthis = "" return "<%s.%s; %s >" % (self.__class__.__module__, self.__class__.__name__, strthis,) try: _object = object _newclass = 1 except __builtin__.Exception: class _object: pass _newclass = 0 class SwigPyIterator(_object): __swig_setmethods__ = {} __setattr__ = lambda self, name, value: _swig_setattr(self, SwigPyIterator, name, value) __swig_getmethods__ = {} __getattr__ = lambda self, name: _swig_getattr(self, SwigPyIterator, name) def __init__(self, *args, **kwargs): raise AttributeError("No constructor defined - class is abstract") __repr__ = _swig_repr __swig_destroy__ = _FiftyOneDegreesTrieV3.delete_SwigPyIterator __del__ = lambda self: None def value(self): return _FiftyOneDegreesTrieV3.SwigPyIterator_value(self) def incr(self, n=1): return _FiftyOneDegreesTrieV3.SwigPyIterator_incr(self, n) def decr(self, n=1): return _FiftyOneDegreesTrieV3.SwigPyIterator_decr(self, n) def distance(self, x): return _FiftyOneDegreesTrieV3.SwigPyIterator_distance(self, x) def equal(self, x): return _FiftyOneDegreesTrieV3.SwigPyIterator_equal(self, x) def copy(self): return _FiftyOneDegreesTrieV3.SwigPyIterator_copy(self) def next(self): return _FiftyOneDegreesTrieV3.SwigPyIterator_next(self) def __next__(self): return _FiftyOneDegreesTrieV3.SwigPyIterator___next__(self) def previous(self): return _FiftyOneDegreesTrieV3.SwigPyIterator_previous(self) def advance(self, n): return _FiftyOneDegreesTrieV3.SwigPyIterator_advance(self, n) def __eq__(self, x): return _FiftyOneDegreesTrieV3.SwigPyIterator___eq__(self, x) def __ne__(self, x): return _FiftyOneDegreesTrieV3.SwigPyIterator___ne__(self, x) def __iadd__(self, n): return _FiftyOneDegreesTrieV3.SwigPyIterator___iadd__(self, n) def __isub__(self, n): return _FiftyOneDegreesTrieV3.SwigPyIterator___isub__(self, n) def __add__(self, n): return _FiftyOneDegreesTrieV3.SwigPyIterator___add__(self, n) def __sub__(self, *args): return _FiftyOneDegreesTrieV3.SwigPyIterator___sub__(self, *args) def __iter__(self): return self SwigPyIterator_swigregister = _FiftyOneDegreesTrieV3.SwigPyIterator_swigregister SwigPyIterator_swigregister(SwigPyIterator) class MapStringString(_object): __swig_setmethods__ = {} __setattr__ = lambda self, name, value: _swig_setattr(self, MapStringString, name, value) __swig_getmethods__ = {} __getattr__ = lambda self, name: _swig_getattr(self, MapStringString, name) __repr__ = _swig_repr def iterator(self): return _FiftyOneDegreesTrieV3.MapStringString_iterator(self) def __iter__(self): return self.iterator() def __nonzero__(self): return _FiftyOneDegreesTrieV3.MapStringString___nonzero__(self) def __bool__(self): return _FiftyOneDegreesTrieV3.MapStringString___bool__(self) def __len__(self): return _FiftyOneDegreesTrieV3.MapStringString___len__(self) def __iter__(self): return self.key_iterator() def iterkeys(self): return self.key_iterator() def itervalues(self): return self.value_iterator() def iteritems(self): return self.iterator() def __getitem__(self, key): return _FiftyOneDegreesTrieV3.MapStringString___getitem__(self, key) def __delitem__(self, key): return _FiftyOneDegreesTrieV3.MapStringString___delitem__(self, key) def has_key(self, key): return _FiftyOneDegreesTrieV3.MapStringString_has_key(self, key) def keys(self): return _FiftyOneDegreesTrieV3.MapStringString_keys(self) def values(self): return _FiftyOneDegreesTrieV3.MapStringString_values(self) def items(self): return _FiftyOneDegreesTrieV3.MapStringString_items(self) def __contains__(self, key): return _FiftyOneDegreesTrieV3.MapStringString___contains__(self, key) def key_iterator(self): return _FiftyOneDegreesTrieV3.MapStringString_key_iterator(self) def value_iterator(self): return _FiftyOneDegreesTrieV3.MapStringString_value_iterator(self) def __setitem__(self, *args): return _FiftyOneDegreesTrieV3.MapStringString___setitem__(self, *args) def asdict(self): return _FiftyOneDegreesTrieV3.MapStringString_asdict(self) def __init__(self, *args): this = _FiftyOneDegreesTrieV3.new_MapStringString(*args) try: self.this.append(this) except __builtin__.Exception: self.this = this def empty(self): return _FiftyOneDegreesTrieV3.MapStringString_empty(self) def size(self): return _FiftyOneDegreesTrieV3.MapStringString_size(self) def swap(self, v): return _FiftyOneDegreesTrieV3.MapStringString_swap(self, v) def begin(self): return _FiftyOneDegreesTrieV3.MapStringString_begin(self) def end(self): return _FiftyOneDegreesTrieV3.MapStringString_end(self) def rbegin(self): return _FiftyOneDegreesTrieV3.MapStringString_rbegin(self) def rend(self): return _FiftyOneDegreesTrieV3.MapStringString_rend(self) def clear(self): return _FiftyOneDegreesTrieV3.MapStringString_clear(self) def get_allocator(self): return _FiftyOneDegreesTrieV3.MapStringString_get_allocator(self) def count(self, x): return _FiftyOneDegreesTrieV3.MapStringString_count(self, x) def erase(self, *args): return _FiftyOneDegreesTrieV3.MapStringString_erase(self, *args) def find(self, x): return _FiftyOneDegreesTrieV3.MapStringString_find(self, x) def lower_bound(self, x): return _FiftyOneDegreesTrieV3.MapStringString_lower_bound(self, x) def upper_bound(self, x): return _FiftyOneDegreesTrieV3.MapStringString_upper_bound(self, x) __swig_destroy__ = _FiftyOneDegreesTrieV3.delete_MapStringString __del__ = lambda self: None MapStringString_swigregister = _FiftyOneDegreesTrieV3.MapStringString_swigregister MapStringString_swigregister(MapStringString) class VectorString(_object): __swig_setmethods__ = {} __setattr__ = lambda self, name, value: _swig_setattr(self, VectorString, name, value) __swig_getmethods__ = {} __getattr__ = lambda self, name: _swig_getattr(self, VectorString, name) __repr__ = _swig_repr def iterator(self): return _FiftyOneDegreesTrieV3.VectorString_iterator(self) def __iter__(self): return self.iterator() def __nonzero__(self): return _FiftyOneDegreesTrieV3.VectorString___nonzero__(self) def __bool__(self): return _FiftyOneDegreesTrieV3.VectorString___bool__(self) def __len__(self): return _FiftyOneDegreesTrieV3.VectorString___len__(self) def __getslice__(self, i, j): return _FiftyOneDegreesTrieV3.VectorString___getslice__(self, i, j) def __setslice__(self, *args): return _FiftyOneDegreesTrieV3.VectorString___setslice__(self, *args) def __delslice__(self, i, j): return _FiftyOneDegreesTrieV3.VectorString___delslice__(self, i, j) def __delitem__(self, *args): return _FiftyOneDegreesTrieV3.VectorString___delitem__(self, *args) def __getitem__(self, *args): return _FiftyOneDegreesTrieV3.VectorString___getitem__(self, *args) def __setitem__(self, *args): return _FiftyOneDegreesTrieV3.VectorString___setitem__(self, *args) def pop(self): return _FiftyOneDegreesTrieV3.VectorString_pop(self) def append(self, x): return _FiftyOneDegreesTrieV3.VectorString_append(self, x) def empty(self): return _FiftyOneDegreesTrieV3.VectorString_empty(self) def size(self): return _FiftyOneDegreesTrieV3.VectorString_size(self) def swap(self, v): return _FiftyOneDegreesTrieV3.VectorString_swap(self, v) def begin(self): return _FiftyOneDegreesTrieV3.VectorString_begin(self) def end(self): return _FiftyOneDegreesTrieV3.VectorString_end(self) def rbegin(self): return _FiftyOneDegreesTrieV3.VectorString_rbegin(self) def rend(self): return _FiftyOneDegreesTrieV3.VectorString_rend(self) def clear(self): return _FiftyOneDegreesTrieV3.VectorString_clear(self) def get_allocator(self): return _FiftyOneDegreesTrieV3.VectorString_get_allocator(self) def pop_back(self): return _FiftyOneDegreesTrieV3.VectorString_pop_back(self) def erase(self, *args): return _FiftyOneDegreesTrieV3.VectorString_erase(self, *args) def __init__(self, *args): this = _FiftyOneDegreesTrieV3.new_VectorString(*args) try: self.this.append(this) except __builtin__.Exception: self.this = this def push_back(self, x): return _FiftyOneDegreesTrieV3.VectorString_push_back(self, x) def front(self): return _FiftyOneDegreesTrieV3.VectorString_front(self) def back(self): return _FiftyOneDegreesTrieV3.VectorString_back(self) def assign(self, n, x): return _FiftyOneDegreesTrieV3.VectorString_assign(self, n, x) def resize(self, *args): return _FiftyOneDegreesTrieV3.VectorString_resize(self, *args) def insert(self, *args): return _FiftyOneDegreesTrieV3.VectorString_insert(self, *args) def reserve(self, n): return _FiftyOneDegreesTrieV3.VectorString_reserve(self, n) def capacity(self): return _FiftyOneDegreesTrieV3.VectorString_capacity(self) __swig_destroy__ = _FiftyOneDegreesTrieV3.delete_VectorString __del__ = lambda self: None VectorString_swigregister = _FiftyOneDegreesTrieV3.VectorString_swigregister VectorString_swigregister(VectorString) class Match(_object): __swig_setmethods__ = {} __setattr__ = lambda self, name, value: _swig_setattr(self, Match, name, value) __swig_getmethods__ = {} __getattr__ = lambda self, name: _swig_getattr(self, Match, name) def __init__(self, *args, **kwargs): raise AttributeError("No constructor defined") __repr__ = _swig_repr __swig_destroy__ = _FiftyOneDegreesTrieV3.delete_Match __del__ = lambda self: None def getValues(self, *args): return _FiftyOneDegreesTrieV3.Match_getValues(self, *args) def getValue(self, *args): return _FiftyOneDegreesTrieV3.Match_getValue(self, *args) def getDeviceId(self): return _FiftyOneDegreesTrieV3.Match_getDeviceId(self) def getRank(self): return _FiftyOneDegreesTrieV3.Match_getRank(self) def getDifference(self): return _FiftyOneDegreesTrieV3.Match_getDifference(self) def getMethod(self): return _FiftyOneDegreesTrieV3.Match_getMethod(self) def getUserAgent(self): return _FiftyOneDegreesTrieV3.Match_getUserAgent(self) Match_swigregister = _FiftyOneDegreesTrieV3.Match_swigregister Match_swigregister(Match) class Provider(_object): __swig_setmethods__ = {} __setattr__ = lambda self, name, value: _swig_setattr(self, Provider, name, value) __swig_getmethods__ = {} __getattr__ = lambda self, name: _swig_getattr(self, Provider, name) __repr__ = _swig_repr __swig_destroy__ = _FiftyOneDegreesTrieV3.delete_Provider __del__ = lambda self: None def getHttpHeaders(self): return _FiftyOneDegreesTrieV3.Provider_getHttpHeaders(self) def getAvailableProperties(self): return _FiftyOneDegreesTrieV3.Provider_getAvailableProperties(self) def getDataSetName(self): return _FiftyOneDegreesTrieV3.Provider_getDataSetName(self) def getDataSetFormat(self): return _FiftyOneDegreesTrieV3.Provider_getDataSetFormat(self) def getDataSetPublishedDate(self): return _FiftyOneDegreesTrieV3.Provider_getDataSetPublishedDate(self) def getDataSetNextUpdateDate(self): return _FiftyOneDegreesTrieV3.Provider_getDataSetNextUpdateDate(self) def getDataSetSignatureCount(self): return _FiftyOneDegreesTrieV3.Provider_getDataSetSignatureCount(self) def getDataSetDeviceCombinations(self): return _FiftyOneDegreesTrieV3.Provider_getDataSetDeviceCombinations(self) def getMatch(self, *args): return _FiftyOneDegreesTrieV3.Provider_getMatch(self, *args) def getMatchWithTolerances(self, *args): return _FiftyOneDegreesTrieV3.Provider_getMatchWithTolerances(self, *args) def getMatchJson(self, *args): return _FiftyOneDegreesTrieV3.Provider_getMatchJson(self, *args) def setDrift(self, drift): return _FiftyOneDegreesTrieV3.Provider_setDrift(self, drift) def setDifference(self, difference): return _FiftyOneDegreesTrieV3.Provider_setDifference(self, difference) def reloadFromFile(self): return _FiftyOneDegreesTrieV3.Provider_reloadFromFile(self) def reloadFromMemory(self, source, size): return _FiftyOneDegreesTrieV3.Provider_reloadFromMemory(self, source, size) def getIsThreadSafe(self): return _FiftyOneDegreesTrieV3.Provider_getIsThreadSafe(self) def __init__(self, *args): this = _FiftyOneDegreesTrieV3.new_Provider(*args) try: self.this.append(this) except __builtin__.Exception: self.this = this Provider_swigregister = _FiftyOneDegreesTrieV3.Provider_swigregister Provider_swigregister(Provider) # This file is compatible with both classic and new-style classes.
51degrees-mobile-detector-v3-trie-wrapper
/51degrees-mobile-detector-v3-trie-wrapper-3.2.18.4.tar.gz/51degrees-mobile-detector-v3-trie-wrapper-3.2.18.4/src/trie/FiftyOneDegreesTrieV3.py
FiftyOneDegreesTrieV3.py
# -*- coding: utf-8 -*- ''' :copyright: (c) 2015 by 51Degrees.com, see README.md for more details. :license: MPL2, see LICENSE.txt for more details. ''' from __future__ import absolute_import
51degrees-mobile-detector-v3-trie-wrapper
/51degrees-mobile-detector-v3-trie-wrapper-3.2.18.4.tar.gz/51degrees-mobile-detector-v3-trie-wrapper-3.2.18.4/FiftyOneDegrees/__init__.py
__init__.py
# This file was automatically generated by SWIG (http://www.swig.org). # Version 4.0.0 # # Do not make changes to this file unless you know what you are doing--modify # the SWIG interface file instead. from sys import version_info as _swig_python_version_info if _swig_python_version_info < (2, 7, 0): raise RuntimeError('Python 2.7 or later required') def swig_import_helper(): import importlib pkg = __name__.rpartition('.')[0] mname = '.'.join((pkg, '_fiftyone_degrees_mobile_detector_v3_trie_wrapper')).lstrip('.') try: return importlib.import_module(mname) except ImportError: return importlib.import_module('_fiftyone_degrees_mobile_detector_v3_trie_wrapper') _fiftyone_degrees_mobile_detector_v3_trie_wrapper = swig_import_helper() del swig_import_helper del _swig_python_version_info try: import builtins as __builtin__ except ImportError: import __builtin__ def _swig_setattr_nondynamic(self, class_type, name, value, static=1): if name == "thisown": return self.this.own(value) if name == "this": if type(value).__name__ == 'SwigPyObject': self.__dict__[name] = value return method = class_type.__swig_setmethods__.get(name, None) if method: return method(self, value) if not static: if _newclass: object.__setattr__(self, name, value) else: self.__dict__[name] = value else: raise AttributeError("You cannot add attributes to %s" % self) def _swig_setattr(self, class_type, name, value): return _swig_setattr_nondynamic(self, class_type, name, value, 0) def _swig_getattr(self, class_type, name): if name == "thisown": return self.this.own() method = class_type.__swig_getmethods__.get(name, None) if method: return method(self) raise AttributeError("'%s' object has no attribute '%s'" % (class_type.__name__, name)) def _swig_repr(self): try: strthis = "proxy of " + self.this.__repr__() except __builtin__.Exception: strthis = "" return "<%s.%s; %s >" % (self.__class__.__module__, self.__class__.__name__, strthis,) try: _object = object _newclass = 1 except __builtin__.Exception: class _object: pass _newclass = 0 class SwigPyIterator(_object): __swig_setmethods__ = {} __setattr__ = lambda self, name, value: _swig_setattr(self, SwigPyIterator, name, value) __swig_getmethods__ = {} __getattr__ = lambda self, name: _swig_getattr(self, SwigPyIterator, name) def __init__(self, *args, **kwargs): raise AttributeError("No constructor defined - class is abstract") __repr__ = _swig_repr __swig_destroy__ = _fiftyone_degrees_mobile_detector_v3_trie_wrapper.delete_SwigPyIterator def __del__(self): return None def value(self): return _fiftyone_degrees_mobile_detector_v3_trie_wrapper.SwigPyIterator_value(self) def incr(self, n=1): return _fiftyone_degrees_mobile_detector_v3_trie_wrapper.SwigPyIterator_incr(self, n) def decr(self, n=1): return _fiftyone_degrees_mobile_detector_v3_trie_wrapper.SwigPyIterator_decr(self, n) def distance(self, x): return _fiftyone_degrees_mobile_detector_v3_trie_wrapper.SwigPyIterator_distance(self, x) def equal(self, x): return _fiftyone_degrees_mobile_detector_v3_trie_wrapper.SwigPyIterator_equal(self, x) def copy(self): return _fiftyone_degrees_mobile_detector_v3_trie_wrapper.SwigPyIterator_copy(self) def next(self): return _fiftyone_degrees_mobile_detector_v3_trie_wrapper.SwigPyIterator_next(self) def __next__(self): return _fiftyone_degrees_mobile_detector_v3_trie_wrapper.SwigPyIterator___next__(self) def previous(self): return _fiftyone_degrees_mobile_detector_v3_trie_wrapper.SwigPyIterator_previous(self) def advance(self, n): return _fiftyone_degrees_mobile_detector_v3_trie_wrapper.SwigPyIterator_advance(self, n) def __eq__(self, x): return _fiftyone_degrees_mobile_detector_v3_trie_wrapper.SwigPyIterator___eq__(self, x) def __ne__(self, x): return _fiftyone_degrees_mobile_detector_v3_trie_wrapper.SwigPyIterator___ne__(self, x) def __iadd__(self, n): return _fiftyone_degrees_mobile_detector_v3_trie_wrapper.SwigPyIterator___iadd__(self, n) def __isub__(self, n): return _fiftyone_degrees_mobile_detector_v3_trie_wrapper.SwigPyIterator___isub__(self, n) def __add__(self, n): return _fiftyone_degrees_mobile_detector_v3_trie_wrapper.SwigPyIterator___add__(self, n) def __sub__(self, *args): return _fiftyone_degrees_mobile_detector_v3_trie_wrapper.SwigPyIterator___sub__(self, *args) def __iter__(self): return self # Register SwigPyIterator in _fiftyone_degrees_mobile_detector_v3_trie_wrapper: _fiftyone_degrees_mobile_detector_v3_trie_wrapper.SwigPyIterator_swigregister(SwigPyIterator) class MapStringString(_object): __swig_setmethods__ = {} __setattr__ = lambda self, name, value: _swig_setattr(self, MapStringString, name, value) __swig_getmethods__ = {} __getattr__ = lambda self, name: _swig_getattr(self, MapStringString, name) __repr__ = _swig_repr def iterator(self): return _fiftyone_degrees_mobile_detector_v3_trie_wrapper.MapStringString_iterator(self) def __iter__(self): return self.iterator() def __nonzero__(self): return _fiftyone_degrees_mobile_detector_v3_trie_wrapper.MapStringString___nonzero__(self) def __bool__(self): return _fiftyone_degrees_mobile_detector_v3_trie_wrapper.MapStringString___bool__(self) def __len__(self): return _fiftyone_degrees_mobile_detector_v3_trie_wrapper.MapStringString___len__(self) def __iter__(self): return self.key_iterator() def iterkeys(self): return self.key_iterator() def itervalues(self): return self.value_iterator() def iteritems(self): return self.iterator() def __getitem__(self, key): return _fiftyone_degrees_mobile_detector_v3_trie_wrapper.MapStringString___getitem__(self, key) def __delitem__(self, key): return _fiftyone_degrees_mobile_detector_v3_trie_wrapper.MapStringString___delitem__(self, key) def has_key(self, key): return _fiftyone_degrees_mobile_detector_v3_trie_wrapper.MapStringString_has_key(self, key) def keys(self): return _fiftyone_degrees_mobile_detector_v3_trie_wrapper.MapStringString_keys(self) def values(self): return _fiftyone_degrees_mobile_detector_v3_trie_wrapper.MapStringString_values(self) def items(self): return _fiftyone_degrees_mobile_detector_v3_trie_wrapper.MapStringString_items(self) def __contains__(self, key): return _fiftyone_degrees_mobile_detector_v3_trie_wrapper.MapStringString___contains__(self, key) def key_iterator(self): return _fiftyone_degrees_mobile_detector_v3_trie_wrapper.MapStringString_key_iterator(self) def value_iterator(self): return _fiftyone_degrees_mobile_detector_v3_trie_wrapper.MapStringString_value_iterator(self) def __setitem__(self, *args): return _fiftyone_degrees_mobile_detector_v3_trie_wrapper.MapStringString___setitem__(self, *args) def asdict(self): return _fiftyone_degrees_mobile_detector_v3_trie_wrapper.MapStringString_asdict(self) def __init__(self, *args): this = _fiftyone_degrees_mobile_detector_v3_trie_wrapper.new_MapStringString(*args) try: self.this.append(this) except __builtin__.Exception: self.this = this def empty(self): return _fiftyone_degrees_mobile_detector_v3_trie_wrapper.MapStringString_empty(self) def size(self): return _fiftyone_degrees_mobile_detector_v3_trie_wrapper.MapStringString_size(self) def swap(self, v): return _fiftyone_degrees_mobile_detector_v3_trie_wrapper.MapStringString_swap(self, v) def begin(self): return _fiftyone_degrees_mobile_detector_v3_trie_wrapper.MapStringString_begin(self) def end(self): return _fiftyone_degrees_mobile_detector_v3_trie_wrapper.MapStringString_end(self) def rbegin(self): return _fiftyone_degrees_mobile_detector_v3_trie_wrapper.MapStringString_rbegin(self) def rend(self): return _fiftyone_degrees_mobile_detector_v3_trie_wrapper.MapStringString_rend(self) def clear(self): return _fiftyone_degrees_mobile_detector_v3_trie_wrapper.MapStringString_clear(self) def get_allocator(self): return _fiftyone_degrees_mobile_detector_v3_trie_wrapper.MapStringString_get_allocator(self) def count(self, x): return _fiftyone_degrees_mobile_detector_v3_trie_wrapper.MapStringString_count(self, x) def erase(self, *args): return _fiftyone_degrees_mobile_detector_v3_trie_wrapper.MapStringString_erase(self, *args) def find(self, x): return _fiftyone_degrees_mobile_detector_v3_trie_wrapper.MapStringString_find(self, x) def lower_bound(self, x): return _fiftyone_degrees_mobile_detector_v3_trie_wrapper.MapStringString_lower_bound(self, x) def upper_bound(self, x): return _fiftyone_degrees_mobile_detector_v3_trie_wrapper.MapStringString_upper_bound(self, x) __swig_destroy__ = _fiftyone_degrees_mobile_detector_v3_trie_wrapper.delete_MapStringString def __del__(self): return None # Register MapStringString in _fiftyone_degrees_mobile_detector_v3_trie_wrapper: _fiftyone_degrees_mobile_detector_v3_trie_wrapper.MapStringString_swigregister(MapStringString) class VectorString(_object): __swig_setmethods__ = {} __setattr__ = lambda self, name, value: _swig_setattr(self, VectorString, name, value) __swig_getmethods__ = {} __getattr__ = lambda self, name: _swig_getattr(self, VectorString, name) __repr__ = _swig_repr def iterator(self): return _fiftyone_degrees_mobile_detector_v3_trie_wrapper.VectorString_iterator(self) def __iter__(self): return self.iterator() def __nonzero__(self): return _fiftyone_degrees_mobile_detector_v3_trie_wrapper.VectorString___nonzero__(self) def __bool__(self): return _fiftyone_degrees_mobile_detector_v3_trie_wrapper.VectorString___bool__(self) def __len__(self): return _fiftyone_degrees_mobile_detector_v3_trie_wrapper.VectorString___len__(self) def __getslice__(self, i, j): return _fiftyone_degrees_mobile_detector_v3_trie_wrapper.VectorString___getslice__(self, i, j) def __setslice__(self, *args): return _fiftyone_degrees_mobile_detector_v3_trie_wrapper.VectorString___setslice__(self, *args) def __delslice__(self, i, j): return _fiftyone_degrees_mobile_detector_v3_trie_wrapper.VectorString___delslice__(self, i, j) def __delitem__(self, *args): return _fiftyone_degrees_mobile_detector_v3_trie_wrapper.VectorString___delitem__(self, *args) def __getitem__(self, *args): return _fiftyone_degrees_mobile_detector_v3_trie_wrapper.VectorString___getitem__(self, *args) def __setitem__(self, *args): return _fiftyone_degrees_mobile_detector_v3_trie_wrapper.VectorString___setitem__(self, *args) def pop(self): return _fiftyone_degrees_mobile_detector_v3_trie_wrapper.VectorString_pop(self) def append(self, x): return _fiftyone_degrees_mobile_detector_v3_trie_wrapper.VectorString_append(self, x) def empty(self): return _fiftyone_degrees_mobile_detector_v3_trie_wrapper.VectorString_empty(self) def size(self): return _fiftyone_degrees_mobile_detector_v3_trie_wrapper.VectorString_size(self) def swap(self, v): return _fiftyone_degrees_mobile_detector_v3_trie_wrapper.VectorString_swap(self, v) def begin(self): return _fiftyone_degrees_mobile_detector_v3_trie_wrapper.VectorString_begin(self) def end(self): return _fiftyone_degrees_mobile_detector_v3_trie_wrapper.VectorString_end(self) def rbegin(self): return _fiftyone_degrees_mobile_detector_v3_trie_wrapper.VectorString_rbegin(self) def rend(self): return _fiftyone_degrees_mobile_detector_v3_trie_wrapper.VectorString_rend(self) def clear(self): return _fiftyone_degrees_mobile_detector_v3_trie_wrapper.VectorString_clear(self) def get_allocator(self): return _fiftyone_degrees_mobile_detector_v3_trie_wrapper.VectorString_get_allocator(self) def pop_back(self): return _fiftyone_degrees_mobile_detector_v3_trie_wrapper.VectorString_pop_back(self) def erase(self, *args): return _fiftyone_degrees_mobile_detector_v3_trie_wrapper.VectorString_erase(self, *args) def __init__(self, *args): this = _fiftyone_degrees_mobile_detector_v3_trie_wrapper.new_VectorString(*args) try: self.this.append(this) except __builtin__.Exception: self.this = this def push_back(self, x): return _fiftyone_degrees_mobile_detector_v3_trie_wrapper.VectorString_push_back(self, x) def front(self): return _fiftyone_degrees_mobile_detector_v3_trie_wrapper.VectorString_front(self) def back(self): return _fiftyone_degrees_mobile_detector_v3_trie_wrapper.VectorString_back(self) def assign(self, n, x): return _fiftyone_degrees_mobile_detector_v3_trie_wrapper.VectorString_assign(self, n, x) def resize(self, *args): return _fiftyone_degrees_mobile_detector_v3_trie_wrapper.VectorString_resize(self, *args) def insert(self, *args): return _fiftyone_degrees_mobile_detector_v3_trie_wrapper.VectorString_insert(self, *args) def reserve(self, n): return _fiftyone_degrees_mobile_detector_v3_trie_wrapper.VectorString_reserve(self, n) def capacity(self): return _fiftyone_degrees_mobile_detector_v3_trie_wrapper.VectorString_capacity(self) __swig_destroy__ = _fiftyone_degrees_mobile_detector_v3_trie_wrapper.delete_VectorString def __del__(self): return None # Register VectorString in _fiftyone_degrees_mobile_detector_v3_trie_wrapper: _fiftyone_degrees_mobile_detector_v3_trie_wrapper.VectorString_swigregister(VectorString) class Match(_object): __swig_setmethods__ = {} __setattr__ = lambda self, name, value: _swig_setattr(self, Match, name, value) __swig_getmethods__ = {} __getattr__ = lambda self, name: _swig_getattr(self, Match, name) def __init__(self, *args, **kwargs): raise AttributeError("No constructor defined") __repr__ = _swig_repr __swig_destroy__ = _fiftyone_degrees_mobile_detector_v3_trie_wrapper.delete_Match def __del__(self): return None def getValues(self, *args): return _fiftyone_degrees_mobile_detector_v3_trie_wrapper.Match_getValues(self, *args) def getValue(self, *args): return _fiftyone_degrees_mobile_detector_v3_trie_wrapper.Match_getValue(self, *args) def getValueAsBool(self, *args): return _fiftyone_degrees_mobile_detector_v3_trie_wrapper.Match_getValueAsBool(self, *args) def getValueAsInteger(self, *args): return _fiftyone_degrees_mobile_detector_v3_trie_wrapper.Match_getValueAsInteger(self, *args) def getValueAsDouble(self, *args): return _fiftyone_degrees_mobile_detector_v3_trie_wrapper.Match_getValueAsDouble(self, *args) def getDeviceId(self): return _fiftyone_degrees_mobile_detector_v3_trie_wrapper.Match_getDeviceId(self) def getRank(self): return _fiftyone_degrees_mobile_detector_v3_trie_wrapper.Match_getRank(self) def getDifference(self): return _fiftyone_degrees_mobile_detector_v3_trie_wrapper.Match_getDifference(self) def getMethod(self): return _fiftyone_degrees_mobile_detector_v3_trie_wrapper.Match_getMethod(self) def getUserAgent(self): return _fiftyone_degrees_mobile_detector_v3_trie_wrapper.Match_getUserAgent(self) # Register Match in _fiftyone_degrees_mobile_detector_v3_trie_wrapper: _fiftyone_degrees_mobile_detector_v3_trie_wrapper.Match_swigregister(Match) class Provider(_object): __swig_setmethods__ = {} __setattr__ = lambda self, name, value: _swig_setattr(self, Provider, name, value) __swig_getmethods__ = {} __getattr__ = lambda self, name: _swig_getattr(self, Provider, name) __repr__ = _swig_repr __swig_destroy__ = _fiftyone_degrees_mobile_detector_v3_trie_wrapper.delete_Provider def __del__(self): return None def getHttpHeaders(self): return _fiftyone_degrees_mobile_detector_v3_trie_wrapper.Provider_getHttpHeaders(self) def getAvailableProperties(self): return _fiftyone_degrees_mobile_detector_v3_trie_wrapper.Provider_getAvailableProperties(self) def getDataSetName(self): return _fiftyone_degrees_mobile_detector_v3_trie_wrapper.Provider_getDataSetName(self) def getDataSetFormat(self): return _fiftyone_degrees_mobile_detector_v3_trie_wrapper.Provider_getDataSetFormat(self) def getDataSetPublishedDate(self): return _fiftyone_degrees_mobile_detector_v3_trie_wrapper.Provider_getDataSetPublishedDate(self) def getDataSetNextUpdateDate(self): return _fiftyone_degrees_mobile_detector_v3_trie_wrapper.Provider_getDataSetNextUpdateDate(self) def getDataSetSignatureCount(self): return _fiftyone_degrees_mobile_detector_v3_trie_wrapper.Provider_getDataSetSignatureCount(self) def getDataSetDeviceCombinations(self): return _fiftyone_degrees_mobile_detector_v3_trie_wrapper.Provider_getDataSetDeviceCombinations(self) def getMatch(self, *args): return _fiftyone_degrees_mobile_detector_v3_trie_wrapper.Provider_getMatch(self, *args) def getMatchWithTolerances(self, *args): return _fiftyone_degrees_mobile_detector_v3_trie_wrapper.Provider_getMatchWithTolerances(self, *args) def getMatchJson(self, *args): return _fiftyone_degrees_mobile_detector_v3_trie_wrapper.Provider_getMatchJson(self, *args) def setDrift(self, drift): return _fiftyone_degrees_mobile_detector_v3_trie_wrapper.Provider_setDrift(self, drift) def setDifference(self, difference): return _fiftyone_degrees_mobile_detector_v3_trie_wrapper.Provider_setDifference(self, difference) def reloadFromFile(self): return _fiftyone_degrees_mobile_detector_v3_trie_wrapper.Provider_reloadFromFile(self) def reloadFromMemory(self, source, size): return _fiftyone_degrees_mobile_detector_v3_trie_wrapper.Provider_reloadFromMemory(self, source, size) def getIsThreadSafe(self): return _fiftyone_degrees_mobile_detector_v3_trie_wrapper.Provider_getIsThreadSafe(self) def __init__(self, *args): this = _fiftyone_degrees_mobile_detector_v3_trie_wrapper.new_Provider(*args) try: self.this.append(this) except __builtin__.Exception: self.this = this # Register Provider in _fiftyone_degrees_mobile_detector_v3_trie_wrapper: _fiftyone_degrees_mobile_detector_v3_trie_wrapper.Provider_swigregister(Provider) # This file is compatible with both classic and new-style classes.
51degrees-mobile-detector-v3-trie-wrapper
/51degrees-mobile-detector-v3-trie-wrapper-3.2.18.4.tar.gz/51degrees-mobile-detector-v3-trie-wrapper-3.2.18.4/FiftyOneDegrees/fiftyone_degrees_mobile_detector_v3_trie_wrapper.py
fiftyone_degrees_mobile_detector_v3_trie_wrapper.py
|51degrees| Device Detection Python API 51Degrees Mobile Detector is a server side mobile detection solution. Changelog ==================== - Fixed a bug where an additional compile argument was causing compilation errors with clang. - Updated the v3-trie-wrapper package to include the Lite Hash Trie data file. - Updated Lite Pattern data file for November. - Updated Lite Hash Trie data file for November. General ======== Before you start matching user agents, you may wish to configure the solution to use a different datadase. You can easily generate a sample settings file running the following command $ 51degrees-mobile-detector settings > ~/51degrees-mobile-detector.settings.py The core ``51degrees-mobile-detector`` is included as a dependency when installing either the ``51degrees-mobile-detector-v3-wrapper`` or ``51degrees-mobile-detector-v3-wrapper`` packages. During install a directory which contains your data file will be created in ``~\51Degrees``. Settings ========= General Settings ---------------- - ``DETECTION_METHOD`` (defaults to 'v3-wrapper'). Sets the preferred mobile device detection method. Available options are v3-wrapper (requires 51degrees-mobile-detector-v3-wrapper package), v3-trie-wrapper - ``PROPERTIES`` (defaults to ''). List of case-sensitive property names to be fetched on every device detection. Leave empty to fetch all available properties. - ``LICENCE`` Your 51Degrees license key for enhanced device data. This is required if you want to set up the automatic 51degrees-mobile-detector-premium-pattern-wrapper package updates. Trie Detector settings ----------------------- - ``V3_TRIE_WRAPPER_DATABASE`` Location of the Hash Trie data file. Pattern Detector settings -------------------------- - ``V3_WRAPPER_DATABASE`` Location of the Pattern data file. - ``CACHE_SIZE`` (defaults to 10000). Sets the size of the workset cache. - ``POOL_SIZE`` (defaults to 20). Sets the size of the workset pool. Usage Sharer Settings ---------------------- - ``USAGE_SHARER_ENABLED`` (defaults to True). Indicates if usage data should be shared with 51Degrees.com. We recommended leaving this value unchanged to ensure we're improving the performance and accuracy of the solution. - Adavanced usage sharer settings are detailed in your settings file. Automatic Updates ------------------ If you want to set up automatic updates, add your license key to your settings and add the following command to your cron $ 51degrees-mobile-detector update-premium-pattern-wrapper NOTE: Currently auto updates are only available with our Pattern API. Usage ====== Core ----- By executing the following a useful help page will be displayed explaining basic usage. $ 51degrees-mobile-detector To check everything is set up , try fetching a match with $ 51degrees-mobile-detector match "Mozilla/5.0 (iPad; CPU OS 5_1 like Mac OS X) AppleWebKit/534.46 (KHTML, like Gecko) Mobile/9B176" Examples ========= Additional examples can be found on our GitHub_ repository. User Support ============ If you have any issues please get in touch with our Support_ or open an issue on our GitHub_ repository. .. |51degrees| image:: https://51degrees.com/DesktopModules/FiftyOne/Distributor/Logo.ashx?utm_source=github&utm_medium=repository&utm_content=readme_pattern&utm_campaign=python-open-source :target: https://51degrees.com .. _GitHub: https://github.com/51Degrees/Device-Detection/tree/master/python .. _Support: support@51degrees.com
51degrees-mobile-detector-v3-wrapper
/51degrees-mobile-detector-v3-wrapper-3.2.18.4.tar.gz/51degrees-mobile-detector-v3-wrapper-3.2.18.4/README.rst
README.rst
''' 51Degrees Mobile Detector (V3 Pattern Wrapper) ========================================== 51Degrees Mobile Detector is a Python wrapper of the C pattern-based mobile detection solution by 51Degrees.com. Check out http://51degrees.com for a detailed description, extra documentation and other useful information. :copyright: (c) 2015 by 51Degrees.com, see README.md for more details. :license: MPL2, see LICENSE.txt for more details. ''' from __future__ import absolute_import import os import sys import subprocess import shutil import tempfile import io from setuptools import setup, find_packages, Extension from distutils import ccompiler from os import path def has_snprintf(): '''Checks C function snprintf() is available in the platform. ''' cc = ccompiler.new_compiler() tmpdir = tempfile.mkdtemp(prefix='51degrees-mobile-detector-v3-wrapper-install-') try: try: source = os.path.join(tmpdir, 'snprintf.c') with open(source, 'w') as f: f.write( '#include <stdio.h>\n' 'int main() {\n' ' char buffer[8];\n' ' snprintf(buffer, 8, "Hey!");\n' ' return 0;\n' '}') objects = cc.compile([source], output_dir=tmpdir) cc.link_executable(objects, os.path.join(tmpdir, 'a.out')) except: return False return True finally: shutil.rmtree(tmpdir) define_macros = [] if has_snprintf(): define_macros.append(('HAVE_SNPRINTF', None)) '''Gets the path to the README file and populates the long description to display a summary in PyPI. ''' this_directory = path.abspath(path.dirname(__file__)) with io.open(path.join(this_directory, 'README.rst'), encoding='utf-8') as f: long_description = f.read() setup( name='51degrees-mobile-detector-v3-wrapper', version='3.2.18.4', author='51Degrees.com', author_email='support@51degrees.com', packages=find_packages(), include_package_data=True, data_files=[(os.path.expanduser('~/51Degrees'), ['data/51Degrees-LiteV3.2.dat'])], ext_modules=[ Extension('_fiftyone_degrees_mobile_detector_v3_wrapper', sources=[ 'src/pattern/51Degrees.c', 'src/cityhash/city.c', 'src/threading.c', 'src/pattern/51Degrees_python.cxx', 'src/pattern/Provider.cpp', 'src/pattern/Match.cpp', 'src/pattern/Profiles.cpp', ], define_macros=define_macros, extra_compile_args=[ '-w', ], ), ], url='http://51degrees.com', description='51Degrees Mobile Detector (C Pattern Wrapper).', long_description=long_description, long_description_content_type='text/x-rst', license='MPL2', classifiers = [ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'Topic :: Software Development :: Libraries', 'License :: OSI Approved :: Mozilla Public License 2.0 (MPL 2.0)', 'Programming Language :: C', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.2', 'Programming Language :: Python :: 3.3', 'Operating System :: POSIX', 'Operating System :: MacOS :: MacOS X', ], install_requires=[ 'setuptools', '51degrees-mobile-detector', ], )
51degrees-mobile-detector-v3-wrapper
/51degrees-mobile-detector-v3-wrapper-3.2.18.4.tar.gz/51degrees-mobile-detector-v3-wrapper-3.2.18.4/setup.py
setup.py
# This file was automatically generated by SWIG (http://www.swig.org). # Version 4.0.0 # # Do not make changes to this file unless you know what you are doing--modify # the SWIG interface file instead. from sys import version_info as _swig_python_version_info if _swig_python_version_info < (2, 7, 0): raise RuntimeError('Python 2.7 or later required') def swig_import_helper(): import importlib pkg = __name__.rpartition('.')[0] mname = '.'.join((pkg, '_fiftyone_degrees_mobile_detector_v3_wrapper')).lstrip('.') try: return importlib.import_module(mname) except ImportError: return importlib.import_module('_fiftyone_degrees_mobile_detector_v3_wrapper') _fiftyone_degrees_mobile_detector_v3_wrapper = swig_import_helper() del swig_import_helper del _swig_python_version_info try: import builtins as __builtin__ except ImportError: import __builtin__ def _swig_setattr_nondynamic(self, class_type, name, value, static=1): if name == "thisown": return self.this.own(value) if name == "this": if type(value).__name__ == 'SwigPyObject': self.__dict__[name] = value return method = class_type.__swig_setmethods__.get(name, None) if method: return method(self, value) if not static: if _newclass: object.__setattr__(self, name, value) else: self.__dict__[name] = value else: raise AttributeError("You cannot add attributes to %s" % self) def _swig_setattr(self, class_type, name, value): return _swig_setattr_nondynamic(self, class_type, name, value, 0) def _swig_getattr(self, class_type, name): if name == "thisown": return self.this.own() method = class_type.__swig_getmethods__.get(name, None) if method: return method(self) raise AttributeError("'%s' object has no attribute '%s'" % (class_type.__name__, name)) def _swig_repr(self): try: strthis = "proxy of " + self.this.__repr__() except __builtin__.Exception: strthis = "" return "<%s.%s; %s >" % (self.__class__.__module__, self.__class__.__name__, strthis,) try: _object = object _newclass = 1 except __builtin__.Exception: class _object: pass _newclass = 0 class SwigPyIterator(_object): __swig_setmethods__ = {} __setattr__ = lambda self, name, value: _swig_setattr(self, SwigPyIterator, name, value) __swig_getmethods__ = {} __getattr__ = lambda self, name: _swig_getattr(self, SwigPyIterator, name) def __init__(self, *args, **kwargs): raise AttributeError("No constructor defined - class is abstract") __repr__ = _swig_repr __swig_destroy__ = _fiftyone_degrees_mobile_detector_v3_wrapper.delete_SwigPyIterator def __del__(self): return None def value(self): return _fiftyone_degrees_mobile_detector_v3_wrapper.SwigPyIterator_value(self) def incr(self, n=1): return _fiftyone_degrees_mobile_detector_v3_wrapper.SwigPyIterator_incr(self, n) def decr(self, n=1): return _fiftyone_degrees_mobile_detector_v3_wrapper.SwigPyIterator_decr(self, n) def distance(self, x): return _fiftyone_degrees_mobile_detector_v3_wrapper.SwigPyIterator_distance(self, x) def equal(self, x): return _fiftyone_degrees_mobile_detector_v3_wrapper.SwigPyIterator_equal(self, x) def copy(self): return _fiftyone_degrees_mobile_detector_v3_wrapper.SwigPyIterator_copy(self) def next(self): return _fiftyone_degrees_mobile_detector_v3_wrapper.SwigPyIterator_next(self) def __next__(self): return _fiftyone_degrees_mobile_detector_v3_wrapper.SwigPyIterator___next__(self) def previous(self): return _fiftyone_degrees_mobile_detector_v3_wrapper.SwigPyIterator_previous(self) def advance(self, n): return _fiftyone_degrees_mobile_detector_v3_wrapper.SwigPyIterator_advance(self, n) def __eq__(self, x): return _fiftyone_degrees_mobile_detector_v3_wrapper.SwigPyIterator___eq__(self, x) def __ne__(self, x): return _fiftyone_degrees_mobile_detector_v3_wrapper.SwigPyIterator___ne__(self, x) def __iadd__(self, n): return _fiftyone_degrees_mobile_detector_v3_wrapper.SwigPyIterator___iadd__(self, n) def __isub__(self, n): return _fiftyone_degrees_mobile_detector_v3_wrapper.SwigPyIterator___isub__(self, n) def __add__(self, n): return _fiftyone_degrees_mobile_detector_v3_wrapper.SwigPyIterator___add__(self, n) def __sub__(self, *args): return _fiftyone_degrees_mobile_detector_v3_wrapper.SwigPyIterator___sub__(self, *args) def __iter__(self): return self # Register SwigPyIterator in _fiftyone_degrees_mobile_detector_v3_wrapper: _fiftyone_degrees_mobile_detector_v3_wrapper.SwigPyIterator_swigregister(SwigPyIterator) class MapStringString(_object): __swig_setmethods__ = {} __setattr__ = lambda self, name, value: _swig_setattr(self, MapStringString, name, value) __swig_getmethods__ = {} __getattr__ = lambda self, name: _swig_getattr(self, MapStringString, name) __repr__ = _swig_repr def iterator(self): return _fiftyone_degrees_mobile_detector_v3_wrapper.MapStringString_iterator(self) def __iter__(self): return self.iterator() def __nonzero__(self): return _fiftyone_degrees_mobile_detector_v3_wrapper.MapStringString___nonzero__(self) def __bool__(self): return _fiftyone_degrees_mobile_detector_v3_wrapper.MapStringString___bool__(self) def __len__(self): return _fiftyone_degrees_mobile_detector_v3_wrapper.MapStringString___len__(self) def __iter__(self): return self.key_iterator() def iterkeys(self): return self.key_iterator() def itervalues(self): return self.value_iterator() def iteritems(self): return self.iterator() def __getitem__(self, key): return _fiftyone_degrees_mobile_detector_v3_wrapper.MapStringString___getitem__(self, key) def __delitem__(self, key): return _fiftyone_degrees_mobile_detector_v3_wrapper.MapStringString___delitem__(self, key) def has_key(self, key): return _fiftyone_degrees_mobile_detector_v3_wrapper.MapStringString_has_key(self, key) def keys(self): return _fiftyone_degrees_mobile_detector_v3_wrapper.MapStringString_keys(self) def values(self): return _fiftyone_degrees_mobile_detector_v3_wrapper.MapStringString_values(self) def items(self): return _fiftyone_degrees_mobile_detector_v3_wrapper.MapStringString_items(self) def __contains__(self, key): return _fiftyone_degrees_mobile_detector_v3_wrapper.MapStringString___contains__(self, key) def key_iterator(self): return _fiftyone_degrees_mobile_detector_v3_wrapper.MapStringString_key_iterator(self) def value_iterator(self): return _fiftyone_degrees_mobile_detector_v3_wrapper.MapStringString_value_iterator(self) def __setitem__(self, *args): return _fiftyone_degrees_mobile_detector_v3_wrapper.MapStringString___setitem__(self, *args) def asdict(self): return _fiftyone_degrees_mobile_detector_v3_wrapper.MapStringString_asdict(self) def __init__(self, *args): this = _fiftyone_degrees_mobile_detector_v3_wrapper.new_MapStringString(*args) try: self.this.append(this) except __builtin__.Exception: self.this = this def empty(self): return _fiftyone_degrees_mobile_detector_v3_wrapper.MapStringString_empty(self) def size(self): return _fiftyone_degrees_mobile_detector_v3_wrapper.MapStringString_size(self) def swap(self, v): return _fiftyone_degrees_mobile_detector_v3_wrapper.MapStringString_swap(self, v) def begin(self): return _fiftyone_degrees_mobile_detector_v3_wrapper.MapStringString_begin(self) def end(self): return _fiftyone_degrees_mobile_detector_v3_wrapper.MapStringString_end(self) def rbegin(self): return _fiftyone_degrees_mobile_detector_v3_wrapper.MapStringString_rbegin(self) def rend(self): return _fiftyone_degrees_mobile_detector_v3_wrapper.MapStringString_rend(self) def clear(self): return _fiftyone_degrees_mobile_detector_v3_wrapper.MapStringString_clear(self) def get_allocator(self): return _fiftyone_degrees_mobile_detector_v3_wrapper.MapStringString_get_allocator(self) def count(self, x): return _fiftyone_degrees_mobile_detector_v3_wrapper.MapStringString_count(self, x) def erase(self, *args): return _fiftyone_degrees_mobile_detector_v3_wrapper.MapStringString_erase(self, *args) def find(self, x): return _fiftyone_degrees_mobile_detector_v3_wrapper.MapStringString_find(self, x) def lower_bound(self, x): return _fiftyone_degrees_mobile_detector_v3_wrapper.MapStringString_lower_bound(self, x) def upper_bound(self, x): return _fiftyone_degrees_mobile_detector_v3_wrapper.MapStringString_upper_bound(self, x) __swig_destroy__ = _fiftyone_degrees_mobile_detector_v3_wrapper.delete_MapStringString def __del__(self): return None # Register MapStringString in _fiftyone_degrees_mobile_detector_v3_wrapper: _fiftyone_degrees_mobile_detector_v3_wrapper.MapStringString_swigregister(MapStringString) class VectorString(_object): __swig_setmethods__ = {} __setattr__ = lambda self, name, value: _swig_setattr(self, VectorString, name, value) __swig_getmethods__ = {} __getattr__ = lambda self, name: _swig_getattr(self, VectorString, name) __repr__ = _swig_repr def iterator(self): return _fiftyone_degrees_mobile_detector_v3_wrapper.VectorString_iterator(self) def __iter__(self): return self.iterator() def __nonzero__(self): return _fiftyone_degrees_mobile_detector_v3_wrapper.VectorString___nonzero__(self) def __bool__(self): return _fiftyone_degrees_mobile_detector_v3_wrapper.VectorString___bool__(self) def __len__(self): return _fiftyone_degrees_mobile_detector_v3_wrapper.VectorString___len__(self) def __getslice__(self, i, j): return _fiftyone_degrees_mobile_detector_v3_wrapper.VectorString___getslice__(self, i, j) def __setslice__(self, *args): return _fiftyone_degrees_mobile_detector_v3_wrapper.VectorString___setslice__(self, *args) def __delslice__(self, i, j): return _fiftyone_degrees_mobile_detector_v3_wrapper.VectorString___delslice__(self, i, j) def __delitem__(self, *args): return _fiftyone_degrees_mobile_detector_v3_wrapper.VectorString___delitem__(self, *args) def __getitem__(self, *args): return _fiftyone_degrees_mobile_detector_v3_wrapper.VectorString___getitem__(self, *args) def __setitem__(self, *args): return _fiftyone_degrees_mobile_detector_v3_wrapper.VectorString___setitem__(self, *args) def pop(self): return _fiftyone_degrees_mobile_detector_v3_wrapper.VectorString_pop(self) def append(self, x): return _fiftyone_degrees_mobile_detector_v3_wrapper.VectorString_append(self, x) def empty(self): return _fiftyone_degrees_mobile_detector_v3_wrapper.VectorString_empty(self) def size(self): return _fiftyone_degrees_mobile_detector_v3_wrapper.VectorString_size(self) def swap(self, v): return _fiftyone_degrees_mobile_detector_v3_wrapper.VectorString_swap(self, v) def begin(self): return _fiftyone_degrees_mobile_detector_v3_wrapper.VectorString_begin(self) def end(self): return _fiftyone_degrees_mobile_detector_v3_wrapper.VectorString_end(self) def rbegin(self): return _fiftyone_degrees_mobile_detector_v3_wrapper.VectorString_rbegin(self) def rend(self): return _fiftyone_degrees_mobile_detector_v3_wrapper.VectorString_rend(self) def clear(self): return _fiftyone_degrees_mobile_detector_v3_wrapper.VectorString_clear(self) def get_allocator(self): return _fiftyone_degrees_mobile_detector_v3_wrapper.VectorString_get_allocator(self) def pop_back(self): return _fiftyone_degrees_mobile_detector_v3_wrapper.VectorString_pop_back(self) def erase(self, *args): return _fiftyone_degrees_mobile_detector_v3_wrapper.VectorString_erase(self, *args) def __init__(self, *args): this = _fiftyone_degrees_mobile_detector_v3_wrapper.new_VectorString(*args) try: self.this.append(this) except __builtin__.Exception: self.this = this def push_back(self, x): return _fiftyone_degrees_mobile_detector_v3_wrapper.VectorString_push_back(self, x) def front(self): return _fiftyone_degrees_mobile_detector_v3_wrapper.VectorString_front(self) def back(self): return _fiftyone_degrees_mobile_detector_v3_wrapper.VectorString_back(self) def assign(self, n, x): return _fiftyone_degrees_mobile_detector_v3_wrapper.VectorString_assign(self, n, x) def resize(self, *args): return _fiftyone_degrees_mobile_detector_v3_wrapper.VectorString_resize(self, *args) def insert(self, *args): return _fiftyone_degrees_mobile_detector_v3_wrapper.VectorString_insert(self, *args) def reserve(self, n): return _fiftyone_degrees_mobile_detector_v3_wrapper.VectorString_reserve(self, n) def capacity(self): return _fiftyone_degrees_mobile_detector_v3_wrapper.VectorString_capacity(self) __swig_destroy__ = _fiftyone_degrees_mobile_detector_v3_wrapper.delete_VectorString def __del__(self): return None # Register VectorString in _fiftyone_degrees_mobile_detector_v3_wrapper: _fiftyone_degrees_mobile_detector_v3_wrapper.VectorString_swigregister(VectorString) class Match(_object): __swig_setmethods__ = {} __setattr__ = lambda self, name, value: _swig_setattr(self, Match, name, value) __swig_getmethods__ = {} __getattr__ = lambda self, name: _swig_getattr(self, Match, name) def __init__(self, *args, **kwargs): raise AttributeError("No constructor defined") __repr__ = _swig_repr __swig_destroy__ = _fiftyone_degrees_mobile_detector_v3_wrapper.delete_Match def __del__(self): return None def getValues(self, *args): return _fiftyone_degrees_mobile_detector_v3_wrapper.Match_getValues(self, *args) def getValue(self, *args): return _fiftyone_degrees_mobile_detector_v3_wrapper.Match_getValue(self, *args) def getDeviceId(self): return _fiftyone_degrees_mobile_detector_v3_wrapper.Match_getDeviceId(self) def getRank(self): return _fiftyone_degrees_mobile_detector_v3_wrapper.Match_getRank(self) def getDifference(self): return _fiftyone_degrees_mobile_detector_v3_wrapper.Match_getDifference(self) def getMethod(self): return _fiftyone_degrees_mobile_detector_v3_wrapper.Match_getMethod(self) def getUserAgent(self): return _fiftyone_degrees_mobile_detector_v3_wrapper.Match_getUserAgent(self) # Register Match in _fiftyone_degrees_mobile_detector_v3_wrapper: _fiftyone_degrees_mobile_detector_v3_wrapper.Match_swigregister(Match) class Profiles(_object): __swig_setmethods__ = {} __setattr__ = lambda self, name, value: _swig_setattr(self, Profiles, name, value) __swig_getmethods__ = {} __getattr__ = lambda self, name: _swig_getattr(self, Profiles, name) __repr__ = _swig_repr __swig_destroy__ = _fiftyone_degrees_mobile_detector_v3_wrapper.delete_Profiles def __del__(self): return None def __init__(self): this = _fiftyone_degrees_mobile_detector_v3_wrapper.new_Profiles() try: self.this.append(this) except __builtin__.Exception: self.this = this def getCount(self): return _fiftyone_degrees_mobile_detector_v3_wrapper.Profiles_getCount(self) def getProfileIndex(self, index): return _fiftyone_degrees_mobile_detector_v3_wrapper.Profiles_getProfileIndex(self, index) def getProfileId(self, index): return _fiftyone_degrees_mobile_detector_v3_wrapper.Profiles_getProfileId(self, index) # Register Profiles in _fiftyone_degrees_mobile_detector_v3_wrapper: _fiftyone_degrees_mobile_detector_v3_wrapper.Profiles_swigregister(Profiles) class Provider(_object): __swig_setmethods__ = {} __setattr__ = lambda self, name, value: _swig_setattr(self, Provider, name, value) __swig_getmethods__ = {} __getattr__ = lambda self, name: _swig_getattr(self, Provider, name) __repr__ = _swig_repr __swig_destroy__ = _fiftyone_degrees_mobile_detector_v3_wrapper.delete_Provider def __del__(self): return None def getHttpHeaders(self): return _fiftyone_degrees_mobile_detector_v3_wrapper.Provider_getHttpHeaders(self) def getAvailableProperties(self): return _fiftyone_degrees_mobile_detector_v3_wrapper.Provider_getAvailableProperties(self) def getDataSetName(self): return _fiftyone_degrees_mobile_detector_v3_wrapper.Provider_getDataSetName(self) def getDataSetFormat(self): return _fiftyone_degrees_mobile_detector_v3_wrapper.Provider_getDataSetFormat(self) def getDataSetPublishedDate(self): return _fiftyone_degrees_mobile_detector_v3_wrapper.Provider_getDataSetPublishedDate(self) def getDataSetNextUpdateDate(self): return _fiftyone_degrees_mobile_detector_v3_wrapper.Provider_getDataSetNextUpdateDate(self) def getDataSetSignatureCount(self): return _fiftyone_degrees_mobile_detector_v3_wrapper.Provider_getDataSetSignatureCount(self) def getDataSetDeviceCombinations(self): return _fiftyone_degrees_mobile_detector_v3_wrapper.Provider_getDataSetDeviceCombinations(self) def getMatch(self, *args): return _fiftyone_degrees_mobile_detector_v3_wrapper.Provider_getMatch(self, *args) def getMatchJson(self, *args): return _fiftyone_degrees_mobile_detector_v3_wrapper.Provider_getMatchJson(self, *args) def getMatchForDeviceId(self, deviceId): return _fiftyone_degrees_mobile_detector_v3_wrapper.Provider_getMatchForDeviceId(self, deviceId) def findProfiles(self, *args): return _fiftyone_degrees_mobile_detector_v3_wrapper.Provider_findProfiles(self, *args) def reloadFromFile(self): return _fiftyone_degrees_mobile_detector_v3_wrapper.Provider_reloadFromFile(self) def reloadFromMemory(self, source, length): return _fiftyone_degrees_mobile_detector_v3_wrapper.Provider_reloadFromMemory(self, source, length) def getCacheHits(self): return _fiftyone_degrees_mobile_detector_v3_wrapper.Provider_getCacheHits(self) def getCacheMisses(self): return _fiftyone_degrees_mobile_detector_v3_wrapper.Provider_getCacheMisses(self) def getCacheMaxIterations(self): return _fiftyone_degrees_mobile_detector_v3_wrapper.Provider_getCacheMaxIterations(self) def getIsThreadSafe(self): return _fiftyone_degrees_mobile_detector_v3_wrapper.Provider_getIsThreadSafe(self) def __init__(self, *args): this = _fiftyone_degrees_mobile_detector_v3_wrapper.new_Provider(*args) try: self.this.append(this) except __builtin__.Exception: self.this = this # Register Provider in _fiftyone_degrees_mobile_detector_v3_wrapper: _fiftyone_degrees_mobile_detector_v3_wrapper.Provider_swigregister(Provider) # This file is compatible with both classic and new-style classes.
51degrees-mobile-detector-v3-wrapper
/51degrees-mobile-detector-v3-wrapper-3.2.18.4.tar.gz/51degrees-mobile-detector-v3-wrapper-3.2.18.4/FiftyOneDegrees/fiftyone_degrees_mobile_detector_v3_wrapper.py
fiftyone_degrees_mobile_detector_v3_wrapper.py
# -*- coding: utf-8 -*- ''' :copyright: (c) 2015 by 51Degrees.com, see README.md for more details. :license: MPL2, see LICENSE.txt for more details. ''' from __future__ import absolute_import
51degrees-mobile-detector-v3-wrapper
/51degrees-mobile-detector-v3-wrapper-3.2.18.4.tar.gz/51degrees-mobile-detector-v3-wrapper-3.2.18.4/FiftyOneDegrees/__init__.py
__init__.py
|51degrees| Device Detection Python API 51Degrees Mobile Detector is a server side mobile detection solution. Changelog ==================== - Fixed a bug where an additional compile argument was causing compilation errors with clang. - Updated the v3-trie-wrapper package to include the Lite Hash Trie data file. - Updated Lite Pattern data file for November. - Update Lite Hash Trie data file for November. General ======== Before you start matching user agents, you may wish to configure the solution to use a different database. You can easily generate a sample settings file running the following command $ 51degrees-mobile-detector settings > ~/51degrees-mobile-detector.settings.py The core ``51degrees-mobile-detector`` is included as a dependency when installing either the ``51degrees-mobile-detector-v3-wrapper`` or ``51degrees-mobile-detector-v3-wrapper`` packages. During install a directory which contains your data file will be created in ``~\51Degrees``. Settings ========= General Settings ---------------- - ``DETECTION_METHOD`` (defaults to 'v3-wrapper'). Sets the preferred mobile device detection method. Available options are v3-wrapper (requires 51degrees-mobile-detector-v3-wrapper package), v3-trie-wrapper - ``PROPERTIES`` (defaults to ''). List of case-sensitive property names to be fetched on every device detection. Leave empty to fetch all available properties. - ``LICENCE`` Your 51Degrees license key for enhanced device data. This is required if you want to set up the automatic 51degrees-mobile-detector-premium-pattern-wrapper package updates. Trie Detector settings ----------------------- - ``V3_TRIE_WRAPPER_DATABASE`` Location of the Hash Trie data file. Pattern Detector settings -------------------------- - ``V3_WRAPPER_DATABASE`` Location of the Pattern data file. - ``CACHE_SIZE`` (defaults to 10000). Sets the size of the workset cache. - ``POOL_SIZE`` (defaults to 20). Sets the size of the workset pool. Usage Sharer Settings ---------------------- - ``USAGE_SHARER_ENABLED`` (defaults to True). Indicates if usage data should be shared with 51Degrees.com. We recommended leaving this value unchanged to ensure we're improving the performance and accuracy of the solution. - Adavanced usage sharer settings are detailed in your settings file. Automatic Updates ------------------ If you want to set up automatic updates, add your license key to your settings and add the following command to your cron $ 51degrees-mobile-detector update-premium-pattern-wrapper NOTE: Currently auto updates are only available with our Pattern API. Usage ====== Core ----- By executing the following a useful help page will be displayed explaining basic usage. $ 51degrees-mobile-detector To check everything is set up , try fetching a match with $ 51degrees-mobile-detector match "Mozilla/5.0 (iPad; CPU OS 5_1 like Mac OS X) AppleWebKit/534.46 (KHTML, like Gecko) Mobile/9B176" Examples ========= Additional examples can be found on our GitHub_ repository. User Support ============ If you have any issues please get in touch with our Support_ or open an issue on our GitHub_ repository. .. |51degrees| image:: https://51degrees.com/DesktopModules/FiftyOne/Distributor/Logo.ashx?utm_source=github&utm_medium=repository&utm_content=readme_pattern&utm_campaign=python-open-source :target: https://51degrees.com .. _GitHub: https://github.com/51Degrees/Device-Detection/tree/master/python .. _Support: support@51degrees.com
51degrees-mobile-detector
/51degrees-mobile-detector-3.2.18.4.tar.gz/51degrees-mobile-detector-3.2.18.4/README.rst
README.rst
''' 51Degrees Mobile Detector ========================= 51Degrees Mobile Detector is a server side mobile detection solution by 51Degrees. Check out http://51degrees.com for a detailed description, extra documentation and other useful information. :copyright: (c) 2015 by 51Degrees, see README.md for more details. :license: MPL2, see LICENSE.txt for more details. ''' from __future__ import absolute_import import sys import os import io from setuptools import setup, find_packages from os import path extra = {} # Minimum Python version. if sys.version_info < (2, 6): raise Exception('51Degrees Mobile Detector requires Python 2.6 or higher.') # Python 3. if sys.version_info[0] == 3: extra.update(use_2to3=True) '''Gets the path to the README file and populates the long description to display a summary in PyPI. ''' this_directory = path.abspath(path.dirname(__file__)) with io.open(path.join(this_directory, 'README.rst'), encoding='utf-8') as f: long_description = f.read() setup( name='51degrees-mobile-detector', version='3.2.18.4', author='51Degrees', author_email='info@51degrees.com', packages=find_packages(), include_package_data=True, url='http://51degrees.com', description='51Degrees Mobile Detector.', long_description=long_description, long_description_content_type='text/x-rst', license='MPL2', entry_points={ 'console_scripts': [ '51degrees-mobile-detector = fiftyone_degrees.mobile_detector.runner:main', ], }, classifiers=[ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'Topic :: Software Development :: Libraries', 'License :: OSI Approved :: Mozilla Public License 2.0 (MPL 2.0)', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.2', 'Programming Language :: Python :: 3.3', 'Operating System :: OS Independent', 'Operating System :: POSIX', 'Operating System :: Microsoft :: Windows', 'Operating System :: MacOS :: MacOS X', ], install_requires=[ 'setuptools', ], **extra )
51degrees-mobile-detector
/51degrees-mobile-detector-3.2.18.4.tar.gz/51degrees-mobile-detector-3.2.18.4/setup.py
setup.py
# -*- coding: utf-8 -*- ''' :copyright: (c) 2015 by 51Degrees.com, see README.md for more details. :license: MPL2, see LICENSE.txt for more details. ''' from __future__ import absolute_import
51degrees-mobile-detector
/51degrees-mobile-detector-3.2.18.4.tar.gz/51degrees-mobile-detector-3.2.18.4/fiftyone_degrees/__init__.py
__init__.py
# -*- coding: utf-8 -*- ''' :copyright: (c) 2015 by 51Degrees.com, see README.md for more details. :license: MPL2, see LICENSE.txt for more details. ''' from __future__ import absolute_import import os import sys import subprocess def settings(args, help): import inspect from fiftyone_degrees.mobile_detector.conf import default sys.stdout.write(inspect.getsource(default)) def match(args, help): if len(args) == 1: from fiftyone_degrees import mobile_detector device = mobile_detector.match(args[0]) for name, value in device.properties.iteritems(): sys.stdout.write('%s: %s\n' % (name, unicode(value),)) else: sys.stderr.write(help) sys.exit(1) def update_premium_pattern_wrapper(args, help): import tempfile import urllib2 import gzip import shutil from fiftyone_degrees.mobile_detector.conf import settings sys.stdout.write('Starting Update \n') if settings.LICENSE: # Build source URL. url = 'https://distributor.51degrees.com/api/v2/download?LicenseKeys=%s&Type=BinaryV32&Download=True' % ( settings.LICENSE ) with tempfile.NamedTemporaryFile( suffix='.dat.gz', prefix='51d_temp', delete=False) as fh: delete = True try: # Fetch URL (no verification of the server's certificate here). uh = urllib2.urlopen(url, timeout=120) # Check server response. if uh.headers['Content-Disposition'] is not None: # Download the package. file_size = int(uh.headers['Content-Length']) sys.stdout.write('=> Downloading %s bytes... ' % file_size) downloaded = 0 while True: buffer = uh.read(8192) if buffer: downloaded += len(buffer) fh.write(buffer) status = r'%3.2f%%' % (downloaded * 100.0 / file_size) status = status + chr(8) * (len(status) + 1) print status, else: break #Done with temporary file. Close it. if not fh.closed: fh.close() #Open zipped file. f_name = fh.name zipped_file = gzip.open(f_name, "rb") #Open temporary file to store unzipped content. unzipped_file = open("unzipped_temp.dat", "wb") #Unarchive content to temporary file. unzipped_file.write(zipped_file.read()) #Close and remove compressed file. zipped_file.close() os.remove(f_name) #Close the unzipped file before copying. unzipped_file.close() #Copy unzipped file to the file used for detection. path = settings.V3_WRAPPER_DATABASE shutil.copy2("unzipped_temp.dat", path) #clean-up if not zipped_file.closed: zipped_file.close() if not unzipped_file.closed: unzipped_file.close() sys.stdout.write("\n Update was successfull \n") #End of try to update package. else: sys.stderr.write('Failed to download the package: is your license key expired?\n') except Exception as e: sys.stderr.write('Failed to download the package: %s.\n' % unicode(e)) finally: try: os.remove("unzipped_temp.dat") os.remove(fh) except: pass else: sys.stderr.write('Failed to download the package: you need a license key. Please, check you settings.\n') def main(): # Build help message. help = '''Usage: %(cmd)s settings: Dumps sample settings file. %(cmd)s match <user agent> Fetches device properties based on the input user agent string. %(cmd)s update-premium-pattern-wrapper Downloads and installs latest premium pattern wrapper package available at 51Degrees.com website (a valid license key is required). ''' % { 'cmd': os.path.basename(sys.argv[0]) } # Check base arguments. if len(sys.argv) > 1: command = sys.argv[1].replace('-', '_') if command in ('settings', 'match', 'update_premium_pattern_wrapper'): getattr(sys.modules[__name__], command)(sys.argv[2:], help) else: sys.stderr.write(help) sys.exit(1) else: sys.stderr.write(help) sys.exit(1) if __name__ == '__main__': main()
51degrees-mobile-detector
/51degrees-mobile-detector-3.2.18.4.tar.gz/51degrees-mobile-detector-3.2.18.4/fiftyone_degrees/mobile_detector/runner.py
runner.py
# -*- coding: utf-8 -*- ''' :copyright: (c) 2015 by 51Degrees.com, see README.md for more details. :license: MPL2, see LICENSE.txt for more details. ''' from __future__ import absolute_import from datetime import datetime import gzip import urllib2 import threading try: import xml.etree.cElementTree as ET except ImportError: import xml.etree.ElementTree as ET try: import cStringIO as StringIO except ImportError: import StringIO from fiftyone_degrees.mobile_detector.conf import settings class UsageSharer(threading.Thread): '''Class used to record usage information. Records & submits usage information which is essential to ensuring 51Degrees.mobi is optimized for performance and accuracy for current devices on the web. ''' # Singleton reference. _instance = None def __init__(self): super(UsageSharer, self).__init__() # Check singleton instance. if self._instance is not None: raise ValueError('An instance of UsageSharer class already exists.') # Init internal singleton state. self._queue = [] self._stopping = False self._event = threading.Event() @classmethod def instance(cls): '''Returns singleton UsageSharer instance. ''' if cls._instance is None: cls._instance = cls() return cls._instance def record(self, client_ip, http_headers): '''Adds request details. Adds some request details to the queue for further submission by the background thread. *client_ip* is a string with the client IP address. *http_headers* is a dictionary containing all HTTP headers. ''' # Enabled? if settings.USAGE_SHARER_ENABLED and self._stopping == False: # Launch background daemon data submission thread if not running. if not self.is_alive(): self.daemon = True self.start() # Add the request details to the queue for further submission. self._queue.append(self._get_item(client_ip, http_headers)) # Signal the background thread to check if it should send # queued data. self._event.set() def stop(self): '''Gracefully stops background data submission thread. ''' if self.is_alive(): settings.logger.info('Stopping 51Degrees UsageSharer.') self._stopping = True self._event.set() self.join() def run(self): '''Runs the background daemon data submission thread. Used to send the devices data back to 51Degrees.mobi after the minimum queue length has been reached. ''' # Log. settings.logger.info('Starting 51Degrees UsageSharer.') # Submission loop. while not self._stopping: # Wait while event's flag is set to True. while not self._event.is_set(): self._event.wait() # If there are enough items in the queue, or the thread is being # stopped, submit the queued data. length = len(self._queue) if length >= settings.USAGE_SHARER_MINIMUM_QUEUE_LENGTH or (length > 0 and self._stopping): self._submit() # Reset the internal event's flag to False. self._event.clear() # Log. settings.logger.info('Stopped 51Degrees UsageSharer.') def _is_local(self, address): return address in settings.USAGE_SHARER_LOCAL_ADDRESSES def _get_item(self, client_ip, http_headers): # Create base device element. device = ET.Element('Device') # Add the current date and time. item = ET.SubElement(device, 'DateSent') item.text = datetime.utcnow().replace(microsecond=0).isoformat() # Add product name and version. item = ET.SubElement(device, 'Version') item.text = settings.VERSION item = ET.SubElement(device, 'Product') item.text = 'Python Mobile Detector' # Add client IP address (if is not local). if not self._is_local(client_ip): item = ET.SubElement(device, 'ClientIP') item.text = client_ip # Filter & add HTTP headers. for name, value in http_headers.iteritems(): # Determine if the field should be treated as a blank. blank = name.upper() in settings.USAGE_SHARER_IGNORED_HEADER_FIELD_VALUES # Include all header values if maximum detail is enabled, or # header values related to the user agent or any header # key containing profile or information helpful to determining # mobile devices. if settings.USAGE_SHARER_MAXIMUM_DETAIL or \ name.upper() in ('USER-AGENT', 'HOST', 'PROFILE') or \ blank: item = ET.SubElement(device, 'Header') item.set('Name', name) if not blank: item.text = unicode(value) # Done! return device def _submit(self): '''Sends all the data on the queue. ''' settings.logger.info('Submitting UsageSharer queued data to %s.' % settings.USAGE_SHARER_SUBMISSION_URL) # Build output stream. stream = StringIO.StringIO() gzStream = StringIO.StringIO() devices = ET.Element('Devices') while len(self._queue) > 0: devices.append(self._queue.pop()) ET.ElementTree(devices).write( stream, encoding='utf8', xml_declaration=True) stream.seek(0,0) # Gzip the data. with gzip.GzipFile(fileobj=gzStream, mode='wb') as gzObj: gzObj.write(stream.read()) gzStream.seek(0,0) # Submit gzipped data. request = urllib2.Request( url=settings.USAGE_SHARER_SUBMISSION_URL, data=gzStream.read(), headers={ 'Content-Type': 'text/xml; charset=utf-8', 'Content-Encoding': 'gzip', }) try: response = urllib2.urlopen(request, timeout=settings.USAGE_SHARER_SUBMISSION_TIMEOUT) except: # Turn off functionality. self._stopping = True else: # Get the response and record the content if it's valid. If it's # not valid consider turning off the functionality. code = response.getcode() if code == 200: # OK. Do nothing. pass elif code == 408: # Request Timeout. Could be temporary, do nothing. pass else: # Turn off functionality. self._stopping = True
51degrees-mobile-detector
/51degrees-mobile-detector-3.2.18.4.tar.gz/51degrees-mobile-detector-3.2.18.4/fiftyone_degrees/mobile_detector/usage.py
usage.py
# -*- coding: utf-8 -*- ''' :copyright: (c) 2015 by 51Degrees.com, see README.md for more details. :license: MPL2, see LICENSE.txt for more details. ''' from __future__ import absolute_import from abc import ABCMeta from fiftyone_degrees.mobile_detector.conf import settings from fiftyone_degrees.mobile_detector import usage class Device(object): '''Simple device wrapper. ''' def __init__(self, method=None): self._method = method self._properties = {} def set_property(self, name, value): self._properties[name] = value @property def method(self): return self._method @property def properties(self): return self._properties def __getattr__(self, name): if name in self._properties: return self._properties.get(name) else: name = name.lower() for aname, value in self._properties.iteritems(): if name == aname.lower(): return value return None def __getstate__(self): return self.__dict__ def __setstate__(self, d): self.__dict__.update(d) class _Matcher(object): '''Abstract matcher class. ''' __metaclass__ = ABCMeta _METHODS = {} _INSTANCES = {} @classmethod def register(cls, method, klass): cls._METHODS[method] = klass @classmethod def instance(cls, method): if method in cls._METHODS: if method not in cls._INSTANCES: cls._INSTANCES[method] = cls._METHODS[method]() return cls._INSTANCES[method] else: raise Exception( 'Requested matching method "%s" does not exist. ' 'Available methods are: %s.' % (method, ', '.join(cls._METHODS.keys()),)) def match(self, user_agent, client_ip=None, http_headers=None): # If provided, share usage information. if client_ip and http_headers: usage.UsageSharer.instance().record(client_ip, http_headers) # Delegate on specific matcher implementation. return self._match(user_agent) def _match(self, user_agent): raise NotImplementedError('Please implement this method.') class _V3WrapperMatcher(_Matcher): ID = 'v3-wrapper' def __init__(self): if settings.V3_WRAPPER_DATABASE: try: # Does the database file exists and is it readable? with open(settings.V3_WRAPPER_DATABASE): pass except IOError: raise Exception( 'The provided detection database file (%s) does not ' 'exist or is not readable. Please, ' 'check your settings.' % settings.V3_WRAPPER_DATABASE) else: from FiftyOneDegrees import fiftyone_degrees_mobile_detector_v3_wrapper self.provider = fiftyone_degrees_mobile_detector_v3_wrapper.Provider(settings.V3_WRAPPER_DATABASE, settings.PROPERTIES, int(settings.CACHE_SIZE), int(settings.POOL_SIZE)) else: raise Exception( 'Trie-based detection method depends on an external ' 'database file. Please, check your settings.') def _match(self, user_agent): # Delegate on wrapped implementation. returnedMatch = None try: returnedMatch = self.provider.getMatch(user_agent) except Exception as e: settings.logger.error( 'Got exception while matching user agent string "%s": %s.' % (user_agent, unicode(e),)) # Pythonize result. result = Device(self.ID) if returnedMatch: result.set_property('Id', returnedMatch.getDeviceId()) result.set_property('MatchMethod', returnedMatch.getMethod()) result.set_property('Difference', returnedMatch.getDifference()) result.set_property('Rank', returnedMatch.getRank()) if settings.PROPERTIES == '': for key in self.provider.getAvailableProperties(): value = returnedMatch.getValues(key) if value: result.set_property(key, ' '.join(value)) else: result.set_property(key, 'N/A in Lite') else: for key in settings.PROPERTIES.split(','): value = returnedMatch.getValues(key) if value: result.set_property(key, ' '.join(value)) # Done! return result class _V3TrieWrapperMatcher(_Matcher): ID = 'v3-trie-wrapper' def __init__(self): if settings.V3_TRIE_WRAPPER_DATABASE: try: # Does the database file exists and is it readable? with open(settings.V3_TRIE_WRAPPER_DATABASE): pass except IOError: raise Exception( 'The provided detection database file (%s) does not ' 'exist or is not readable. Please, ' 'check your settings.' % settings.V3_TRIE_WRAPPER_DATABASE) else: from FiftyOneDegrees import fiftyone_degrees_mobile_detector_v3_trie_wrapper self.provider = fiftyone_degrees_mobile_detector_v3_trie_wrapper.Provider(settings.V3_TRIE_WRAPPER_DATABASE, settings.PROPERTIES) else: raise Exception( 'Trie-based detection method depends on an external ' 'database file. Please, check your settings.') def _match(self, user_agent): # Delegate on wrapped implementation. returnedMatch = None try: returnedMatch = self.provider.getMatch(user_agent) except Exception as e: settings.logger.error( 'Got exception while matching user agent string "%s": %s.' % (user_agent, unicode(e),)) # Pythonize result. result = Device(self.ID) print settings.PROPERTIES if returnedMatch: if settings.PROPERTIES == '': for key in self.provider.getAvailableProperties(): value = returnedMatch.getValues(key) if value: result.set_property(key, ' '.join(value)) else: result.set_property(key, 'N/A in Lite') else: for key in settings.PROPERTIES.split(','): value = returnedMatch.getValues(key) if value: result.set_property(key, ' '.join(value)) # Done! return result # Register matching methods. for klass in [_V3WrapperMatcher, _V3TrieWrapperMatcher]: _Matcher.register(klass.ID, klass) def match(user_agent, client_ip=None, http_headers=None, method=None): '''Fetches device data based on an user agent string. *user_agent* is an user agent string. *client_ip* is a string with the client IP address (optional). If provided it'll will be submitted to 51Degrees.mobi in order to improve performance and accuracy of further device detections. *http_headers* is a dictionary containing all HTTP headers (optional). If provided, it'll will be submitted (removing confidential data such as cookies) to 51Degrees.mobi in order to improve performance and accuracy of further device detections. *method* is a string with the desired device detection method. If not specified, settings.DETECTION_METHOD will be used. Returns Device instance. ''' # Fetch matcher instance. matcher = _Matcher.instance( method if method is not None else settings.DETECTION_METHOD) # Match! return matcher.match(user_agent, client_ip, http_headers)
51degrees-mobile-detector
/51degrees-mobile-detector-3.2.18.4.tar.gz/51degrees-mobile-detector-3.2.18.4/fiftyone_degrees/mobile_detector/__init__.py
__init__.py
# -*- coding: utf-8 -*- ''' :copyright: (c) 2015 by 51Degrees.com, see README.md for more details. :license: MPL2, see LICENSE.txt for more details. ''' from __future__ import absolute_import
51degrees-mobile-detector
/51degrees-mobile-detector-3.2.18.4.tar.gz/51degrees-mobile-detector-3.2.18.4/fiftyone_degrees/mobile_detector/contrib/__init__.py
__init__.py
# -*- coding: utf-8 -*- ''' :copyright: (c) 2015 by 51Degrees.com, see README.md for more details. :license: MPL2, see LICENSE.txt for more details. ''' from __future__ import absolute_import import string import logging import pickle from django.core.validators import validate_ipv46_address from django.core.exceptions import ValidationError from django.conf import settings from fiftyone_degrees import mobile_detector try: from django.utils.deprecation import MiddlewareMixin except ImportError: MiddlewareMixin = object # Settings names. SESSION_CACHE = 'FIFTYONE_DEGREES_MOBILE_DETECTOR_SESSION_CACHE' SESSION_FIELD = 'FIFTYONE_DEGREES_MOBILE_DETECTOR_SESSION_FIELD' # Default settings values. DEFAULT_SESSION_CACHE = False DEFAULT_SESSION_FIELD = '_51degrees_device' class DetectorMiddleware(MiddlewareMixin): '''Adds lazily generated 'device' attribute to the incoming request. ''' def process_request(self, request): request.device = _Device(request) return None class _Device(object): '''Proxies lazily generated 'mobile_detector.Device' instance. ''' def __init__(self, request): self._request = request self._device = None def __getattr__(self, name): if self._device is None: self._device = self._fetch() return getattr(self._device, name) def _fetch(self): # Do *not* break the request when not being able to detect device. try: if getattr(settings, SESSION_CACHE, DEFAULT_SESSION_CACHE) and \ hasattr(self._request, 'session'): field = getattr(settings, SESSION_FIELD, DEFAULT_SESSION_FIELD) if field not in self._request.session: device = self._match() self._request.session[field] = pickle.dumps(device) else: device = pickle.loads(self._request.session[field]) else: device = self._match() except Exception as e: logging.\ getLogger('fiftyone_degrees.mobile_detector').\ error('Got an exception while detecting device: %s.' % unicode(e)) device = mobile_detector.Device() # Done! return device def _match(self): # Fetch client IP address. client_ip = self._request.META.get('REMOTE_ADDR') if 'HTTP_X_FORWARDED_FOR' in self._request.META: # HTTP_X_FORWARDED_FOR can be a comma-separated list of IPs. # Take just the first valid one (proxies like squid may introduce # invalid values like 'unknown' under certain configurations, so # a validations is always required). for ip in self._request.META['HTTP_X_FORWARDED_FOR'].split(','): ip = ip.strip() try: validate_ipv46_address(ip) client_ip = ip break except ValidationError: pass # Fetch HTTP headers. # See: https://docs.djangoproject.com/en/dev/ref/request-response/#django.http.HttpRequest.META http_headers = {} for name, value in self._request.META.iteritems(): if name in ('CONTENT_LENGTH', 'CONTENT_TYPE',): http_headers[self._normalized_header_name(name)] = value elif name.startswith('HTTP_'): http_headers[self._normalized_header_name(name[5:])] = value # Match. return mobile_detector.match(http_headers) def _normalized_header_name(self, value): value = value.replace('_', ' ') value = string.capwords(value) return value.replace(' ', '-')
51degrees-mobile-detector
/51degrees-mobile-detector-3.2.18.4.tar.gz/51degrees-mobile-detector-3.2.18.4/fiftyone_degrees/mobile_detector/contrib/django/middleware.py
middleware.py
# -*- coding: utf-8 -*- ''' :copyright: (c) 2015 by 51Degrees.com, see README.md for more details. :license: MPL2, see LICENSE.txt for more details. ''' from __future__ import absolute_import def device(request): return { 'device': request.device, }
51degrees-mobile-detector
/51degrees-mobile-detector-3.2.18.4.tar.gz/51degrees-mobile-detector-3.2.18.4/fiftyone_degrees/mobile_detector/contrib/django/context_processors.py
context_processors.py
# -*- coding: utf-8 -*- ''' :copyright: (c) 2015 by 51Degrees.com, see README.md for more details. :license: MPL2, see LICENSE.txt for more details. ''' from __future__ import absolute_import
51degrees-mobile-detector
/51degrees-mobile-detector-3.2.18.4.tar.gz/51degrees-mobile-detector-3.2.18.4/fiftyone_degrees/mobile_detector/contrib/django/__init__.py
__init__.py
# -*- coding: utf-8 -*- ''' Default 51Degrees Mobile Detector settings. Override these using the FIFTYONE_DEGREES_MOBILE_DETECTOR_SETTINGS environment variable. Both file paths (e.g. '/etc/51Degrees/51degrees-mobile-detector.settings.py') and module names (e.g. 'myproject.fiftyone_degrees_mobile_settings') are allowed. If not specified, defaults to '51degrees-mobile-detector.settings.py' in the current working directory. Note that when using the mobile detector in a Django project, settings can also be specified using the FIFTYONE_DEGREES_MOBILE_DETECTOR_SETTINGS variable in the Django settings file. :copyright: (c) 2015 by 51Degrees.com, see README.md for more details. :license: MPL2, see LICENSE.txt for more details. ''' from __future__ import absolute_import import os ############################################################################### ## GENERAL SETTINGS. ############################################################################### # Sets the preferred mobile device detection method. Available options are: # # - 'v3-wrapper': Requires '51degrees-mobile-detector-v3-wrapper' package. # - 'v3-trie-wrapper': Requires '51degrees-mobile-detector-v3-trie-wrapper' package. # DETECTION_METHOD = 'v3-wrapper' # List of case-sensitive property names to be fetched on every device detection. Leave empty to # fetch all available properties. PROPERTIES = '' # Your 51Degrees license key. This is required if you want to set up the automatic # data file updates. LICENSE = '' ############################################################################### ## TRIE DETECTOR SETTINGS. ############################################################################### # Location of the database file. If not specified, the trie-based detection # method will not be available. Download the latest 51Degrees-LiteV3.4.trie # file from http://github.com/51Degrees/Device-Detection/data/. # Compare database options at https://51degrees.com/compare-data-options . V3_TRIE_WRAPPER_DATABASE = os.path.expanduser('~/51Degrees/51Degrees-LiteV3.4.trie') ############################################################################### ## PATTERN DETECTOR SETTINGS. ############################################################################### # Location of the database file. If not specified, the trie-based detection # method will not be available. Download the latest 51Degrees-LiteV3.2.dat # file from http://github.com/51Degrees/Device-Detection/data/. # Compare database options at https://51degrees.com/compare-data-options . V3_WRAPPER_DATABASE = os.path.expanduser('~/51Degrees/51Degrees-LiteV3.2.dat') # Size of cache allocated CACHE_SIZE = 10000 #Size of pool allocated POOL_SIZE = 20 ############################################################################### ## USAGE SHARER SETTINGS. ############################################################################### # Indicates if usage data should be shared with 51Degrees.com. We recommended # leaving this value unchanged to ensure we're improving the performance and # accuracy of the solution. USAGE_SHARER_ENABLED = True # The detail that should be provided relating to new devices. # Modification not required for most users. USAGE_SHARER_MAXIMUM_DETAIL = True # URL to send new device data to. # Modification not required for most users. USAGE_SHARER_SUBMISSION_URL = 'https://devices.51degrees.com/new.ashx' # Data submission timeout (seconds). USAGE_SHARER_SUBMISSION_TIMEOUT = 10 # Minimum queue length to launch data submission. USAGE_SHARER_MINIMUM_QUEUE_LENGTH = 50 # Used to detect local devices. # Modification not required for most users. USAGE_SHARER_LOCAL_ADDRESSES = ( '127.0.0.1', '0:0:0:0:0:0:0:1', ) # The content of fields in this list should not be included in the # request information sent to 51Degrees. # Modification not required for most users. USAGE_SHARER_IGNORED_HEADER_FIELD_VALUES = ( 'Referer', 'cookie', 'AspFilterSessionId', 'Akamai-Origin-Hop', 'Cache-Control', 'Cneonction', 'Connection', 'Content-Filter-Helper', 'Content-Length', 'Cookie', 'Cookie2', 'Date', 'Etag', 'If-Last-Modified', 'If-Match', 'If-Modified-Since', 'If-None-Match', 'If-Range', 'If-Unmodified-Since', 'IMof-dified-Since', 'INof-ne-Match', 'Keep-Alive', 'Max-Forwards', 'mmd5', 'nnCoection', 'Origin', 'ORIGINAL-REQUEST', 'Original-Url', 'Pragma', 'Proxy-Connection', 'Range', 'Referrer', 'Script-Url', 'Unless-Modified-Since', 'URL', 'UrlID', 'URLSCAN-ORIGINAL-URL', 'UVISS-Referer', 'X-ARR-LOG-ID', 'X-Cachebuster', 'X-Discard', 'X-dotDefender-first-line', 'X-DRUTT-REQUEST-ID', 'X-Initial-Url', 'X-Original-URL', 'X-PageView', 'X-REQUEST-URI', 'X-REWRITE-URL', 'x-tag', 'x-up-subno', 'X-Varnish', )
51degrees-mobile-detector
/51degrees-mobile-detector-3.2.18.4.tar.gz/51degrees-mobile-detector-3.2.18.4/fiftyone_degrees/mobile_detector/conf/default.py
default.py
# -*- coding: utf-8 -*- ''' Settings and configuration for 51Degrees Mobile Detector. Values will be read from the file or module specified by the FIFTYONE_DEGREES_MOBILE_DETECTOR_SETTINGS environment variable. Both file paths (e.g. '/etc/51degrees-mobile-detector.settings.py') and module names (e.g. 'myproject.fiftyone_degrees_mobile_settings') are allowed. If not specified, defaults to '51degrees-mobile-detector.settings.py' in the current working directory. Additionally, when using the mobile detector in a Django project, settings can also be specified using the FIFTYONE_DEGREES_MOBILE_DETECTOR_SETTINGS variable in the Django settings file. :copyright: (c) 2015 by 51Degrees.com, see README.md for more details. :license: MPL2, see LICENSE.txt for more details. ''' from __future__ import absolute_import import os import sys import imp import logging from fiftyone_degrees.mobile_detector.conf import default class _Settings(object): VERSION = '3.2' try: import pkg_resources VERSION = pkg_resources.get_distribution('51degrees-mobile-detector').version except: pass def __init__(self, settings_file_or_module): # Add default settings. self._add_settings(default) # Try to load settings from file/module pointed by the # environment variable. try: __import__(settings_file_or_module) self._add_settings(sys.modules[settings_file_or_module]) except: try: self._add_settings(imp.load_source( 'fiftyone_degrees.conf._file', settings_file_or_module)) except: pass # Try to load setting from the Django settings file. try: from django.conf import settings from django.core import exceptions try: for name, value in getattr(settings, 'FIFTYONE_DEGREES_MOBILE_DETECTOR_SETTINGS', {}).iteritems(): self._add_setting(name, value) except exceptions.ImproperlyConfigured: pass except ImportError: pass # Add logger instance. self.logger = logging.getLogger('fiftyone_degrees.mobile_detector') def _add_settings(self, mod): '''Updates this dict with mod settings (only ALL_CAPS). ''' for name in dir(mod): if name == name.upper(): self._add_setting(name, getattr(mod, name)) def _add_setting(self, name, value): '''Updates this dict with a specific setting. ''' if name == 'USAGE_SHARER_IGNORED_HEADER_FIELD_VALUES': value = tuple([item.upper() for item in value]) setattr(self, name, value) settings = _Settings( os.environ.get( 'FIFTYONE_DEGREES_MOBILE_DETECTOR_SETTINGS', os.path.join(os.getcwd(), '51degrees-mobile-detector.settings.py')))
51degrees-mobile-detector
/51degrees-mobile-detector-3.2.18.4.tar.gz/51degrees-mobile-detector-3.2.18.4/fiftyone_degrees/mobile_detector/conf/__init__.py
__init__.py
#!/usr/bin/python3 # -*- coding: utf-8 -*- # @Time : 2021/2/8 3:26 下午 # @Author : zhengyu # @FileName: http_sender_module.py # @Software: PyCharm import requests import logging logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s') # logging.basicConfig函数对日志的输出格式及方式做相关配置 logger = logging.getLogger('com.autotest.db.sqlalchemy_util') class HttpSender(object): get_response = "" post_response = "" hostname = "" # 公有的类属性 __cookies = {} # 私有的类属性 # def __init__(self): # print("HttpSender Default Constructor has been called.") def __init__(self, hostname, headers=None): logger.info("HttpSender Parameter Constructor has been called.") self.hostname = hostname self.headers = headers # self.headers的这个headers是实例属性,可以用实例直接方法。 logger.info("self.headers = {0}".format(self.headers)) def set_headers(self, headers): self.headers = headers logger.info("成员方法设置请求头:self.headers = {0}".format(self.headers)) logger.info("self.headers = {0}".format(self.headers)) # 类方法,用classmethod来进行修饰 # 注:类方法和实例方法同名,则类方法会覆盖实例方法。所以改个名字。 @classmethod # def set_headers(cls, headers): def set_cls_headers(cls, headers): cls.headers = headers logger.info("类方法设置请求头:cls.headers = {0}".format(cls.headers)) def send_get_request(self, full_get_url): self.get_response = requests.get(full_get_url, headers=self.headers) # logger.info("响应:", self.get_response.text) def send_get_request_by_suburi(self, sub_uri, input_params): full_url = self.hostname + sub_uri self.get_response = requests.get(full_url, params=input_params, headers=self.headers) logger.info("full_url = %s" % self.get_response.url) def send_post_request(self, full_post_url, param_data=None): self.post_response = requests.post(full_post_url, param_data, headers=self.headers) def send_json_post_request(self, full_post_url, json_data=None): self.post_response = requests.post(full_post_url, json=json_data, headers=self.headers) logger.info("响应={0}".format(self.post_response.text)) # 静态方法 @staticmethod def send_json_post_request_with_headers_cookies(self, full_post_url, json_data=None, header_data=None, cookie_data=None): # 在静态方法中引用类属性的话,必须通过类实例对象来引用 # print(self.hostname) self.post_response = requests.post(full_post_url, json=json_data, headers=header_data, cookies=cookie_data) def send_json_post_request_by_suburi(self, sub_uri, json_data=None): full_url = self.hostname + sub_uri logger.info("full_url={0}".format(full_url)) logger.info("json_data={0}".format(json_data)) self.post_response = requests.post(full_url, json=json_data, headers=self.headers) # *args 和 **kwargs 都代表 1个 或 多个 参数的意思。*args 传入tuple 类型的无名参数,而 **kwargs 传入的参数是 dict 类型. # 可变参数 (Variable Argument) 的方法:使用*args和**kwargs语法。# 其中,*args是可变的positional arguments列表,**kwargs是可变的keyword arguments列表。 # 并且,*args必须位于**kwargs之前,因为positional arguments必须位于keyword arguments之前。 # # r = requests.get("http://www.baidu.com") # print(r.text)
51job-autotest-framework
/51job_autotest_framework-0.3.1-py3-none-any.whl/rolling_king/autotest/requests/http_sender_module.py
http_sender_module.py
#!/usr/bin/python3 # -*- coding: utf-8 -*- # @Time : 2022/1/27 11:44 上午 # @Author : zhengyu.0985 # @FileName: __init__.py.py # @Software: PyCharm
51job-autotest-framework
/51job_autotest_framework-0.3.1-py3-none-any.whl/rolling_king/autotest/tests/__init__.py
__init__.py
#!/usr/bin/python3 # -*- coding: utf-8 -*- # @Time : 2021/12/13 2:41 下午 # @Author : zhengyu.0985 # @FileName: base_compare.py # @Software: PyCharm from rolling_king.autotest.db.db_models import CaseRecordModel, BamInterModel, NonCovInterModel from rolling_king.autotest.db.sqlalchemy_util import AlchemyUtil from rolling_king.autotest.tests.base.base_test import BaseTest import logging import os logger = logging.getLogger("base_compare") class CoverDiff(object): @staticmethod def _get_db_conf_path(): curr_sys_path = os.getcwd() logger.info(f"file_path={curr_sys_path}") index_of_com = curr_sys_path.find("com") if index_of_com != -1: # 下面一行是绝对路径传入获取配置文件的方法。 conf_absolute_path = curr_sys_path[0:index_of_com] + "com/conf/" db_conf_file_path = conf_absolute_path + "db.conf" else: # 下面一行的相对路径会随测试py文件位置而变化,仅在测试文件绝对路径中不包含com时,做默认三层情况使用。 db_conf_file_path = curr_sys_path + "/com/conf/db.conf" return db_conf_file_path @staticmethod def get_diff_result(psm=None, test_project_name=None, protocol="BOTH"): db_conf_dict = AlchemyUtil.get_db_param_dict("DB_BOE_Site_Reldb", CoverDiff._get_db_conf_path()) engine = AlchemyUtil.init_engine(db_conf_dict) AlchemyUtil.init_db(engine) # 创建表(存在则不创建) site_rel_db_session = AlchemyUtil.get_session(engine) # 判断已测试(分子)的查询范围。 if psm is None and test_project_name is None: project_conf_dict = BaseTest.get_project_conf_dict() psm = project_conf_dict['test_psm'] test_project_name = project_conf_dict['test_project_name'] tested_criteria_set = { # 这是<class 'set'>类型。 CaseRecordModel.test_psm == psm, # 被测PSM CaseRecordModel.test_project_name == test_project_name # 测试项目名 } elif psm is None: project_conf_dict = BaseTest.get_project_conf_dict() psm = project_conf_dict['test_psm'] tested_criteria_set = { # 这是<class 'set'>类型。 CaseRecordModel.test_psm == psm, # 被测PSM CaseRecordModel.test_project_name == test_project_name # 测试项目名 } elif test_project_name is None: # 只传入PSM,证明与被测项目无关,全局进行查询。 logger.info("test_project_name is None") tested_criteria_set = { # 这是<class 'set'>类型。 CaseRecordModel.test_psm == psm, # 被测PSM } else: tested_criteria_set = { # 这是<class 'set'>类型。 CaseRecordModel.test_psm == psm, # 被测PSM CaseRecordModel.test_project_name == test_project_name # 测试项目名 } # 获取已测试列表 tested_list = AlchemyUtil.query_obj_list(site_rel_db_session, CaseRecordModel, tested_criteria_set) # 下面查询总接口数(分母) # 查询总接口的若干字段 collum_tuple = (BamInterModel.psm, BamInterModel.name, BamInterModel.method, BamInterModel.path,\ BamInterModel.rpc_method, BamInterModel.note, BamInterModel.endpoint_id, BamInterModel.version) # 依据想要对比的接口协议类型,进行对比。 if protocol == "HTTP" or protocol == "REST": logger.info("仅对比HTTP接口") total_criteria_set = { # 这是<class 'set'>类型。 BamInterModel.psm == psm, BamInterModel.path != '', BamInterModel.method != '' } total_list = AlchemyUtil.query_field_list(site_rel_db_session, collum_tuple, criteria_set=total_criteria_set) if len(tested_list) == 0: logger.info("tested_list:为空") if len(total_list) > 0: CoverDiff._delete_non_cov_records(psm, total_list) CoverDiff._insert_non_cov_to_db(psm, total_list) elif len(total_list) == 0: logger.info("total_list:为空") else: diff_tuple_list = CoverDiff._compare_http(tested_list, total_list) CoverDiff._delete_non_cov_records(psm, diff_tuple_list) CoverDiff._insert_non_cov_to_db(psm, diff_tuple_list) return len(diff_tuple_list) elif protocol == "RPC" or protocol == "THRIFT": logger.info("仅对比RPC接口") total_criteria_set = { # 这是<class 'set'>类型。 BamInterModel.psm == psm, BamInterModel.path == '', BamInterModel.method == '' } total_list = AlchemyUtil.query_field_list(site_rel_db_session, collum_tuple, criteria_set=total_criteria_set) if len(tested_list) == 0: logger.info("tested_list:为空") if len(total_list) > 0: CoverDiff._delete_non_cov_records(psm, total_list) CoverDiff._insert_non_cov_to_db(psm, total_list) elif len(total_list) == 0: logger.info("total_list:为空") else: diff_tuple_list = CoverDiff._compare_rpc(tested_list, total_list) CoverDiff._delete_non_cov_records(psm, diff_tuple_list) CoverDiff._insert_non_cov_to_db(psm, diff_tuple_list) return len(diff_tuple_list) else: logger.info("HTTP and RPC 接口均对比") total_criteria_set = { # 这是<class 'set'>类型。 BamInterModel.psm == psm, } total_list = AlchemyUtil.query_field_list(site_rel_db_session, collum_tuple, criteria_set=total_criteria_set) if len(tested_list) == 0: logger.info("tested_list:为空") if len(total_list) > 0: CoverDiff._delete_non_cov_records(psm, total_list) CoverDiff._insert_non_cov_to_db(psm, total_list) elif len(total_list) == 0: logger.info("total_list:为空") else: diff_tuple_list = CoverDiff._compare_both(tested_list, total_list) CoverDiff._delete_non_cov_records(psm, diff_tuple_list) CoverDiff._insert_non_cov_to_db(psm, diff_tuple_list) return len(diff_tuple_list) # 返回数量 return 0 @staticmethod def _compare_rpc(tested_list, total_list): logger.info("一共 %d 个接口。" % len(total_list)) for curr_test in tested_list: curr_rpc_method = curr_test.__dict__['test_interface'].split(".")[1] for curr_db_record in total_list: if curr_rpc_method == curr_db_record[4]: logger.info("curr_db_record = %s" % curr_db_record) logger.info("[RPC] %s 已被 %s 项目的 %s 测试用例覆盖。" % (curr_rpc_method, curr_test.test_project_name, curr_test.test_method)) total_list.remove(curr_db_record) break else: pass logger.info("未覆盖 %d 个接口" % len(total_list)) return total_list @staticmethod def _compare_http(tested_list, total_list): logger.info("一共 %d 个接口。" % len(total_list)) for curr_test in tested_list: curr_http_uri = curr_test.__dict__['test_interface'].split("::")[1] for curr_db_record in total_list: if curr_http_uri == curr_db_record[3]: logger.info("curr_db_record = %s" % curr_db_record) logger.info("[REST] %s 已被 %s 项目的 %s 测试用例覆盖。" % (curr_http_uri, curr_test.test_project_name, curr_test.test_method)) total_list.remove(curr_db_record) break else: pass logger.info("未覆盖 %d 个接口" % len(total_list)) return total_list @staticmethod def _compare_both(tested_list, total_list): logger.info("一共 %d 个接口。" % len(total_list)) for curr_test in tested_list: if curr_test.test_inter_type == 'HTTP': curr_http_uri = curr_test.__dict__['test_interface'].split("::")[1] for curr_db_record in total_list: if curr_http_uri == curr_db_record[3]: logger.info("curr_db_record = %s" % curr_db_record) logger.info("[REST] %s 已被 %s 项目的 %s 测试用例覆盖。" % ( curr_http_uri, curr_test.test_project_name, curr_test.test_method)) total_list.remove(curr_db_record) break else: pass # End For elif curr_test.test_inter_type == 'THRIFT': curr_rpc_method = curr_test.__dict__['test_interface'].split(".")[1] for curr_db_record in total_list: if curr_rpc_method == curr_db_record[4]: logger.info("curr_db_record = %s" % curr_db_record) logger.info("[RPC] %s 已被 %s 项目的 %s 测试用例覆盖。" % ( curr_rpc_method, curr_test.test_project_name, curr_test.test_method)) total_list.remove(curr_db_record) break else: pass # End For else: pass logger.info("未覆盖 %d 个接口" % len(total_list)) return total_list @staticmethod def _insert_non_cov_to_db(psm, non_cov_tuple_list): if non_cov_tuple_list is not None and len(non_cov_tuple_list) > 0: logger.info("PSM=[%s],需要 插入 %d 条记录。" % (psm, len(non_cov_tuple_list))) non_cov_inter_model_list = [] for curr_non_cov_tuple in non_cov_tuple_list: curr_non_cov_inter = NonCovInterModel() curr_non_cov_inter.id = AlchemyUtil.gen_unique_key() curr_non_cov_inter.psm = curr_non_cov_tuple[0], curr_non_cov_inter.name = curr_non_cov_tuple[1], curr_non_cov_inter.method = curr_non_cov_tuple[2], curr_non_cov_inter.path = curr_non_cov_tuple[3], curr_non_cov_inter.rpc_method = curr_non_cov_tuple[4], curr_non_cov_inter.note = curr_non_cov_tuple[5], curr_non_cov_inter.endpoint_id = curr_non_cov_tuple[6], curr_non_cov_inter.version = curr_non_cov_tuple[7] non_cov_inter_model_list.append(curr_non_cov_inter) dict_val = AlchemyUtil.get_db_param_dict("DB_BOE_Site_Reldb", CoverDiff._get_db_conf_path()) engine = AlchemyUtil.init_engine(dict_val) AlchemyUtil.init_db(engine) # 创建表(存在则不创建) site_rel_db_session = AlchemyUtil.get_session(engine) AlchemyUtil.insert_list_with_flush_only(site_rel_db_session, non_cov_inter_model_list) AlchemyUtil.do_commit_only(site_rel_db_session) else: logger.info("[无需插入]:non_cov_tuple_list 为空,无需插入。") @staticmethod def _delete_non_cov_records(psm, diff_tuple_list): if psm is not None: dict_val = AlchemyUtil.get_db_param_dict("DB_BOE_Site_Reldb", CoverDiff._get_db_conf_path()) engine = AlchemyUtil.init_engine(dict_val) AlchemyUtil.init_db(engine) # 创建表(存在则不创建) site_rel_db_session = AlchemyUtil.get_session(engine) if diff_tuple_list is None: AlchemyUtil.delete_for_criteria_commit(site_rel_db_session, NonCovInterModel, {NonCovInterModel.psm == psm}) else: existing_non_cov_list_in_db = AlchemyUtil.query_field_list(site_rel_db_session,\ (NonCovInterModel.endpoint_id, NonCovInterModel.name),\ {NonCovInterModel.psm == psm}) already_cov_endpoint_list = [] for non_cov_tuple_in_db in existing_non_cov_list_in_db: found = False curr_endpoint = non_cov_tuple_in_db[0] for curr_diff_tuple in diff_tuple_list: if curr_endpoint == curr_diff_tuple[6]: diff_tuple_list.remove(curr_diff_tuple) found = True break else: pass if not found: already_cov_endpoint_list.append(curr_endpoint) # End For logger.info("PSM=[%s],需要 删除 %d 条记录。" % (psm, len(already_cov_endpoint_list))) if len(already_cov_endpoint_list) > 0: AlchemyUtil.delete_for_criteria_commit(site_rel_db_session, NonCovInterModel, {NonCovInterModel.endpoint_id in already_cov_endpoint_list}) logger.info("【Success】PSM=[%s],成功 删除 %d 条记录。" % (psm, len(already_cov_endpoint_list))) else: logger.info("psm is None.") pass
51job-autotest-framework
/51job_autotest_framework-0.3.1-py3-none-any.whl/rolling_king/autotest/tests/base/base_compare.py
base_compare.py
#!/usr/bin/python3 # -*- coding: utf-8 -*- # @Time : 2022/1/11 3:51 下午 # @Author : zhengyu # @FileName: autotest_generator.py # @Software: PyCharm import os import json from string import Template import logging logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s') # logging.basicConfig函数对日志的输出格式及方式做相关配置 logger = logging.getLogger('tests.base.autotest_generator') class TestGenerator(object): @staticmethod def rest_generate(rest_test_file_path='', test_class_name='TestXXX', domain_host_url='https://your.domain.host.url', case_info_dict_list=[]): """ :param rest_test_file_path: com.coscoshipping.tests.rest.之后的路径到.py结束。 :param test_class_name: 测试类的名称,必须以Test开头,以符合PyTest规范。 :param domain_host_url: Restful请求的域名地址。 :param case_info_dict_list: 测试用例信息列表,元素要求为dict类型。 :return: """ # 获取待生成的目标python文件 template_path = TestGenerator.__get_template_path("rest") # py_file_path = template_path + "../../coscoshipping/tests/rest/" + rest_test_file_path py_file_path = TestGenerator._get_com_path() + "coscoshipping/tests/rest/" + rest_test_file_path py_file = open(py_file_path, 'w', encoding='utf-8') # 组装测试类 setup_file_path = template_path + "restful_setup.template" setup_template_file = open(setup_file_path, encoding='utf-8') setup_template = Template(setup_template_file.read()) # setup模版替换 lines = [setup_template.substitute( rest_test_file_path=rest_test_file_path, test_class_name=test_class_name, domain_host_url=domain_host_url)] # 用例模板替换 lines.extend(TestGenerator._get_test_cases(case_info_dict_list)) # teardown模板替换 teardown_file_path = template_path + "restful_teardown.template" teardown_template_file = open(teardown_file_path, encoding='utf-8') teardown_template = Template(teardown_template_file.read()) lines.extend(teardown_template.substitute(rest_test_file_path=rest_test_file_path)) # 输出至python文件并保存。 py_file.writelines(lines) py_file.close() logger.info('[Success] Generate %s. ~ ~' % py_file_path) @staticmethod def rpc_generate(thrift_test_file_path='', test_class_name='TestXXX', thrift_file_name='thrift_file_name', idl_settings=None, case_info_dict_list=[]): """ :param thrift_test_file_path: com.coscoshipping.tests.thrift.之后的路径到.py结束。 :param test_class_name: 测试类的名称,必须以Test开头,以符合PyTest规范。 :param thrift_file_name: thrift文件名。 :param idl_settings: idl自动下载的配置。 :param case_info_dict_list: 测试用例信息列表,元素要求为dict类型。 :return: """ # 获取待生成的目标python文件 template_path = TestGenerator.__get_template_path("thrift") py_file_path = TestGenerator._get_com_path() + "coscoshipping/tests/thrift/" + thrift_test_file_path py_file = open(py_file_path, 'w', encoding='utf-8') # 组装测试类 if idl_settings is None: setup_file_path = template_path + "thrift_setup.template" setup_template_file = open(setup_file_path, encoding='utf-8') setup_template = Template(setup_template_file.read()) # setup模版替换 lines = [setup_template.substitute( thrift_test_file_path=thrift_test_file_path, test_class_name=test_class_name, thrift_file_name=thrift_file_name)] else: setup_file_path = template_path + "thrift_advanced_setup.template" setup_template_file = open(setup_file_path, encoding='utf-8') setup_template = Template(setup_template_file.read()) # setup模版替换 lines = [setup_template.substitute( thrift_test_file_path=thrift_test_file_path, test_class_name=test_class_name, idl_remote=idl_settings['idl_remote'], git_token=idl_settings['git_token'] )] # 用例模板替换 lines.extend(TestGenerator._get_test_cases(case_info_dict_list)) # teardown模板替换 teardown_file_path = template_path + "thrift_teardown.template" teardown_template_file = open(teardown_file_path, encoding='utf-8') teardown_template = Template(teardown_template_file.read()) lines.extend(teardown_template.substitute(thrift_test_file_path=thrift_test_file_path)) # 输出至python文件并保存。 py_file.writelines(lines) py_file.close() logger.info('[Success] Generate %s. ~ ~' % py_file_path) pass @staticmethod def _get_test_cases(case_info_dict_list): lines = [] if len(case_info_dict_list) == 0: pass else: for case_info_dict in case_info_dict_list: lines.append(TestGenerator._get_one_case(case_info_dict)) lines.append("\n") return lines @staticmethod def _get_one_case(curr_case_dict): if type(curr_case_dict) == dict: order = 1 test_method_name = "test_method_name" inter_name = "inter_name" protocol_type = "HTTP" method_name = "thrift_method_name" # for thrift api only inter_path = "/suburi" cookie = "" http_method = "" http_method_call = "" param_class_name = "" # for thrift api only if "order" in curr_case_dict.keys(): order = curr_case_dict['order'] if "test_method_name" in curr_case_dict.keys(): test_method_name = curr_case_dict['test_method_name'] if "inter_name" in curr_case_dict.keys(): inter_name = curr_case_dict['inter_name'] if "protocol_type" in curr_case_dict.keys(): protocol_type = curr_case_dict['protocol_type'] if "method_name" in curr_case_dict.keys(): method_name = curr_case_dict['method_name'] if "inter_path" in curr_case_dict.keys(): inter_path = curr_case_dict['inter_path'] if "cookie" in curr_case_dict.keys(): cookie = curr_case_dict['cookie'] if "http_method" in curr_case_dict.keys(): http_method = curr_case_dict['http_method'].lower() if http_method == "get": http_method_call = "send_get_request_by_suburi" elif http_method == "post": http_method_call = "send_json_post_request_by_suburi" else: http_method_call = "不支持GET或POST以外的请求" logger.info("当前用例自动生成仅支持GET和POST请求。") if "param_class_name" in curr_case_dict.keys(): param_class_name = curr_case_dict['param_class_name'] # 准备组装Template # 下面开始判断该用例是否是参数化的 if "parameters" in curr_case_dict.keys() and len(curr_case_dict['parameters']) > 0: parameters = curr_case_dict['parameters'] if "," in parameters: param_list = parameters.split(",") values_tuples = "(" for param in param_list: values_tuples = values_tuples + param.strip() + "_value0, " values_tuples = values_tuples + ")" else: values_tuples = "(" + parameters.strip() + "_value0)" # 真正开始组装Template # 判断是HTTP接口还是THRIFT接口 if protocol_type.lower() == "http" or protocol_type.lower() == "rest": template_path = TestGenerator.__get_template_path("rest") parameter_case_file_path = template_path + "restful_parameter_case.template" parameter_case_template_file = open(parameter_case_file_path, encoding='utf-8') template = Template(parameter_case_template_file.read()) result = template.substitute( order=order, test_method_name=test_method_name, inter_name=inter_name, protocol_type=protocol_type, inter_path=inter_path, cookie=cookie, http_method=http_method, http_method_call=http_method_call, parameters=parameters, values_tuples=values_tuples ) elif protocol_type.lower() == "thrift" or protocol_type.lower() == "rpc": template_path = TestGenerator.__get_template_path("thrift") parameter_case_file_path = template_path + "thrift_parameter_case.template" parameter_case_template_file = open(parameter_case_file_path, encoding='utf-8') template = Template(parameter_case_template_file.read()) result = template.substitute( order=order, test_method_name=test_method_name, inter_name=inter_name, protocol_type=protocol_type, method_name=method_name, cookie=cookie, param_class_name=param_class_name, parameters=parameters, values_tuples=values_tuples ) else: result = "" logger.warning("当前仅支持接口协议为HTTP和THRIFT。") else: # 该else代表该用例是非参数化执行。 if protocol_type.lower() == "http" or protocol_type.lower() == "rest": template_path = TestGenerator.__get_template_path("rest") restful_case_file_path = template_path + "restful_case.template" restful_case_template_file = open(restful_case_file_path, encoding='utf-8') template = Template(restful_case_template_file.read()) result = template.substitute( order=order, test_method_name=test_method_name, inter_name=inter_name, protocol_type=protocol_type, inter_path=inter_path, cookie=cookie, http_method=http_method, http_method_call=http_method_call ) elif protocol_type.lower() == "thrift" or protocol_type.lower() == "rpc": template_path = TestGenerator.__get_template_path("thrift") thrift_case_file_path = template_path + "thrift_case.template" thrift_case_template_file = open(thrift_case_file_path, encoding='utf-8') template = Template(thrift_case_template_file.read()) result = template.substitute( order=order, test_method_name=test_method_name, inter_name=inter_name, protocol_type=protocol_type, method_name=method_name, cookie=cookie, param_class_name=param_class_name, ) else: result = "" logger.warning("当前仅支持接口协议为HTTP和THRIFT。") return result else: logger.error('case_info_dict_list的元素不是dict类型。') return "" @staticmethod def __get_template_path(rest_or_thrift): return TestGenerator._get_com_path() + "templates/" + rest_or_thrift + "/" @staticmethod def _get_com_path(): curr_path = os.getcwd() index_of_com = curr_path.find("com") if index_of_com != -1: # 下面一行是绝对路径传入获取配置文件的方法。 return curr_path[0:index_of_com] + "com/" else: # 下面一行的相对路径会随测试py文件位置而变化,仅在测试文件绝对路径中不包含com时,做默认三层情况使用。 return "../../../" @staticmethod def generate(config_file_name): test_config_file_path = TestGenerator._get_com_path() + "coscoshipping/tests/case_config/" + config_file_name test_config_file = open(test_config_file_path, 'r', encoding='utf-8') str_val = test_config_file.read() dict_array = json.loads(str_val) if "rest" in config_file_name.lower() or "http" in config_file_name.lower(): for test_dict in dict_array: # 每一个dict是一个测试文件。 TestGenerator.rest_generate( rest_test_file_path=test_dict['rest_test_file_path'], test_class_name=test_dict['test_class_name'], domain_host_url=test_dict['domain_host_url'], case_info_dict_list=test_dict['case_info_dict_list'] ) elif "rpc" in config_file_name.lower() or "thrift" in config_file_name.lower(): for test_dict in dict_array: # 每一个dict是一个测试文件。 if 'idl_settings' in test_dict.keys() and len(test_dict['idl_settings']) > 0: TestGenerator.rpc_generate( thrift_test_file_path=test_dict['thrift_test_file_path'], test_class_name=test_dict['test_class_name'], thrift_file_name=test_dict['thrift_file_name'], idl_settings=test_dict['idl_settings'], case_info_dict_list=test_dict['case_info_dict_list'] ) else: TestGenerator.rpc_generate( thrift_test_file_path=test_dict['thrift_test_file_path'], test_class_name=test_dict['test_class_name'], thrift_file_name=test_dict['thrift_file_name'], case_info_dict_list=test_dict['case_info_dict_list'] ) if __name__ == "__main__": TestGenerator.generate("restful_case_config.json") # TestGenerator.generate("thrift_case_config.json") # case_info_dict_list = [ # { # "order": 1, # "test_method_name": "test_case", # "inter_name": "被测接口", # "protocol_type": "HTTP", # "inter_path": "/union_pangle", # "http_method": "GET" # }, # { # "order": 2, # "test_method_name": "test_parameter_case", # "inter_name": "被测接口1", # "protocol_type": "HTTP", # "inter_path": "/union_pangle/parameter", # "http_method": "POST", # "parameters": "var, param", # }, # ] # TestGenerator.rest_generate( # rest_test_file_path="auto_test.py", # test_class_name="TestAuto", # domain_host_url="https://boe-pangle-ssr.bytedance.net", # case_info_dict_list=case_info_dict_list # )
51job-autotest-framework
/51job_autotest_framework-0.3.1-py3-none-any.whl/rolling_king/autotest/tests/base/autotest_generator.py
autotest_generator.py
#!/usr/bin/python3 # -*- coding: utf-8 -*- import json import os import time import logging import uuid import platform from rolling_king.autotest.tests.base.base_test import BaseTest logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s') # logging.basicConfig函数对日志的输出格式及方式做相关配置 logger = logging.getLogger('requests.http_sender_module') """ 此类暂时未使用 """ class BaseConfTest(object): @staticmethod def make_report(item, call, out): # item是测试用例,call是测试步骤。 # setup、call、teardown三个阶段,每个阶段都会返回 Result 对象和 TestReport 对象以及对象属性。 logger.info('------------------------------------') call_dict = call.__dict__ logger.info("call['when'] = %s" % call_dict['when']) start = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(call_dict['start'])) logger.info("【%s】阶段 开始时间 = %s " % (call_dict['when'], start)) stop = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(call_dict['stop'])) logger.info("【%s】阶段 结束时间 = %s " % (call_dict['when'], stop)) duration_in_sec = call_dict['duration'] logger.info("【%s】阶段 耗时 = %f 秒" % (call_dict['when'], duration_in_sec)) # 获取钩子方法的调用结果 # out = yield # 这个out从函数调用中来。 # logger.info('用例执行结果 %s' % out.__dict__) # 从钩子方法的调用结果中获取测试报告 report = out.get_result() if report.when == "setup": logger.info("report.when = setup") pass # 若只获取call这一步的结果,则可以加个判断:if report.when == "call"即可。 if report.when == "call": logger.info('测试报告:%s' % report) logger.info( '步骤:%s' % report.when) # 每个测试用例执行都有三步:setup、call、teardown。(注意与setup_class方法和teardown_class方法相区分) logger.info('nodeid:%s' % report.nodeid) logger.info('description: %s' % str(item.function.__doc__)) logger.info(('运行结果: %s' % report.outcome)) # 以上是查看监听器获取的信息。下面是组装准备落库的dict。 file_class_method_list = report.nodeid.split("::") case_record_dict = { "uid": '0', # uid默认赋值'0',因为用例记录会通过此值来判断是否是新增的用例,所以不能在此就赋uuid.uuid4().hex这个值。 "test_class": file_class_method_list[0] + "::" + file_class_method_list[1], "test_method": file_class_method_list[2], "version": 1 # 用例版本默认存1 } logger.info("测试用例 = %s" % case_record_dict) project_conf_dict = BaseTest.get_project_conf_dict() case_record_dict.update(project_conf_dict) # 增加项目配置参数dict interface_dict = BaseTest.analyze_func_desc(str(item.function.__doc__)) case_record_dict.update(interface_dict) # 增加被测接口信息dict logger.info("case_record_dict = %s" % case_record_dict) # 把用例case_record_dict添加至BaseTest.case_record_dict_list中。 BaseTest.case_record_dict_list.append(case_record_dict) # 判断是否有用到断言 test_case_name = case_record_dict['test_method'].split("[")[0] if "[" in case_record_dict[ 'test_method'] else case_record_dict['test_method'] # ###### 上面是测试用例信息,下面是执行结果信息。###### execution_call_dict = { 'uid': uuid.uuid4().hex, 'test_unique_tag': str(BaseTest.unique_tag) } execution_call_dict.update(project_conf_dict) # 增加项目配置参数dict execution_call_dict['test_interface'] = interface_dict['test_interface'] execution_call_dict['test_inter_type'] = interface_dict['test_inter_type'] execution_call_dict['test_class'] = file_class_method_list[0] + "::" + file_class_method_list[1] execution_call_dict['test_method'] = file_class_method_list[2] params_dict = BaseConfTest._get_params_dict(item.__dict__, execution_call_dict['test_method']) execution_call_dict['test_params'] = json.dumps(params_dict) execution_call_dict['test_result'] = report.outcome execution_call_dict['test_assert'] = BaseConfTest.analyze_assert_by_test_method(case_record_dict['test_class'], test_case_name) # True/False if "fail" in report.outcome: execution_call_dict['test_error_msg'] = call_dict['excinfo'].value # <class '_pytest._code.code.ExceptionInfo'> else: execution_call_dict['test_error_msg'] = "" execution_call_dict['test_start_time'] = start execution_call_dict['test_finish_time'] = stop execution_call_dict['test_duration'] = int(duration_in_sec * 1000) # 打印并加入到List中。 logger.info("curr_execution_call_dict = %s" % execution_call_dict) # 打印当前用例执行记录dict。 BaseTest.execution_record_dict_list.append(execution_call_dict) # 将当前用例的执行记录添加至list中。 if report.when == "teardown": logger.info("report.when = teardown") pass # 如果在 teardown阶段添加dict到List会缺失最后一次添加的值。所以要在call阶段完成对list的添加。 logger.info('------------------------------------') @staticmethod def function_before(): logger.info("--- before_after_test func in conftest--Setup Section.---") start_time = time.time() start_time_str = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(start_time)) logger.info("当前用例-测试开始时间 = %s" % start_time_str) @staticmethod def function_after(): finish_time = time.time() finish_time_str = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(finish_time)) logger.info("当前用例-测试结束时间 = %s" % finish_time_str) logger.info("--- before_after_test func in conftest--Teardown Section.---") @staticmethod def session_before(test_project_name, test_psm): logger.info("=== setup 前置操作:开始Pytest本次整体测试 ===") BaseTest.case_record_dict_list.clear() BaseTest.execution_record_dict_list.clear() BaseTest.unique_tag = int(time.time()) BaseTest.test_project_name = test_project_name BaseTest.test_psm = test_psm @staticmethod def session_after(): logger.info("=== teardown 后置操作:结束Pytest本次整体测试 ===") logger.info( "通过BaseTest.case_record_dict_list收集到本次共执行 %d 个测试用例。" % len(BaseTest.case_record_dict_list)) BaseTest.insert_update_delete() # Case记录的DB逻辑。 logger.info("通过BaseTest.execution_record_dict_list收集到本次 %d 个测试结果。" % len( BaseTest.execution_record_dict_list)) BaseTest.insert_execution_record() # 执行记录的DB逻辑。 @staticmethod def summary(terminalreporter, exitstatus, config): logger.info("=================================") terminal_reporter_dict = terminalreporter.__dict__ logger.info(terminal_reporter_dict) # Python自省,输出terminalreporter对象的属性字典 total_case_dict = BaseConfTest._get_total_case_dict(terminal_reporter_dict['stats']) for key, record_list in total_case_dict.items(): if len(record_list) > 0: for report in record_list: logger.info("%s : %s = %s" % (key, report.nodeid, report.outcome)) logger.info("---------------------------------") # 基于PSM,获取未测试到的接口,并落入未测试覆盖的MySQL库。 # CoverDiff.get_diff_result(protocol="BOTH") logger.info("---------------------------------") duration = time.time() - terminalreporter._sessionstarttime logger.info('Total Time Cost: %.2f seconds.' % duration) logger.info(exitstatus) logger.info(config) logger.info("=================================") @staticmethod def _get_total_case_dict(terminal_reporter_stats_dict): passed_case_report_list = [] failed_case_report_list = [] skipped_case_report_list = [] for key, val in terminal_reporter_stats_dict.items(): if key == '': logger.info("当前key = %s,代表 %s" % (key, "setup_teardown")) elif key == 'passed' or key == 'xpassed': logger.info("当前key = %s, 共计 %d 个" % (key, len(val))) passed_case_report_list.extend(val) elif key == 'failed' or key == 'xfailed': logger.info("当前key = %s, 共计 %d 个" % (key, len(val))) failed_case_report_list.extend(val) elif key == 'skipped': logger.info("当前key = %s, 共计 %d 个" % (key, len(val))) skipped_case_report_list.extend(val) total_record_count = len(passed_case_report_list) + len(failed_case_report_list) + len(skipped_case_report_list) logger.info("本次测试一共执行了 %d 个用例。" % total_record_count) return { "passed": passed_case_report_list, "failed": failed_case_report_list, "skipped": skipped_case_report_list } @staticmethod def _get_params_dict(item_dict, test_method): params_dict = {} # 要返回的值 for mark in item_dict['own_markers']: if mark.name == 'parametrize': args_tuple = mark.args # ('code_id, exp_resp_code', [('py-autotest-top-baidu-2021-12-06_20:43:52', 'PG0000'), ('py-autotest-top-baidu-1', '207007')]) if isinstance(args_tuple[0], list): params_key_list = args_tuple[0] else: params_key_list = args_tuple[0].split(",") key_count = len(params_key_list) params_value_list = args_tuple[1] node_key_words = item_dict['keywords'] # .<class '_pytest.mark.structures.NodeKeywords'> function_node = node_key_words.node # .<class '_pytest.python.Function'> real_test_func_name = function_node.name logger.info( "real_test_func_name = %s" % real_test_func_name) # test_post_with_python3[py-autotest-top-baidu-2021-12-06_21:19:07-PG0000] index_left = real_test_func_name.find("[") if index_left != -1: index_left += 1 index_right = len(real_test_func_name) - 1 real_parametrize_name = real_test_func_name[ index_left: index_right] # py-autotest-top-baidu-2021-12-06_21:19:07-PG0000 else: real_parametrize_name = "" logger.info("real_parametrize_name = %s" % real_parametrize_name) if key_count > 1: for curr_param_values in params_value_list: if type(curr_param_values).__name__ == 'tuple': # 有多个参数化参数。 curr_params_join_name = "-".join(curr_param_values) # 此时curr_param_values是个tuple logger.info("curr_params_join_name = %s" % curr_params_join_name) if curr_params_join_name == real_parametrize_name: # 找到了本次执行的参数化值,相匹配 logger.info("参数化变量只有 %d 个,参数化值类型为 %s" % ( key_count, type(curr_param_values).__name__)) for index in range(0, key_count): params_dict[params_key_list[index].strip()] = curr_param_values[index] logger.info("params_dict = %s" % params_dict) break else: pass else: logger.info("参数化变量只有 %d 个,参数化值类型为 %s" % ( key_count, type(curr_param_values).__name__)) # End For elif key_count == 1: # 只有一个参数化参数 logger.info("params_key_list[0] = %s" % params_key_list[0]) # custom_param_dict logger.info("test_method = %s" % test_method) # test_post_with_python3[custom_param_dict0] if params_key_list[0] in test_method: index = test_method.find(params_key_list[0]) length = len(params_key_list[0]) exact_position = index + length count_index = int(test_method[exact_position:-1]) logger.info("当前是第 %d 次参数化执行" % count_index) curr_param_values = params_value_list[count_index] if type(curr_param_values).__name__ == 'dict': # 一个dict作为参数化参数。 logger.info("参数化变量只有 %d 个,参数化值类型为 %s" % ( key_count, type(curr_param_values).__name__)) params_dict[params_key_list[0]] = curr_param_values logger.info("params_dict = %s" % params_dict) else: logger.info("参数化变量只有 %d 个,参数化值类型为 %s" % ( key_count, type(curr_param_values).__name__)) params_dict[params_key_list[0]] = curr_param_values logger.info("params_dict = %s" % params_dict) else: logger.error("不包含 %s" % (params_key_list[0])) else: logger.info("该测试方法没有参数,非参数化执行。") break else: pass return params_dict @staticmethod def _get_parametrize_name_list(item_func_dict): if 'pytestmark' in item_func_dict.keys(): mark_list = item_func_dict['pytestmark'] parametrize_name_list = [] for curr_mark in mark_list: if curr_mark.name == 'parametrize': args_tuple = curr_mark.args print(args_tuple) if args_tuple[0].find(",") != -1: # 有多个参数 for curr_param_name in args_tuple[0].split(","): parametrize_name_list.append(curr_param_name.strip()) else: parametrize_name_list.append(args_tuple[0]) # 只有一个参数 break else: pass return parametrize_name_list else: return [] # End For Loop @staticmethod def analyze_assert_by_test_method(pytest_file_class: str, test_case_name: str) -> bool: logger.info("analyze_assert_by_test_method") assertion_flag: bool = False # if "::" in pytest_file_class: # file_path = pytest_file_class.split("::")[0] # test_class = pytest_file_class.split("::")[1] # curr_sys_path = os.getcwd() # logger.info(f"curr_sys_path={curr_sys_path}") # index_of_com = curr_sys_path.find("com") # if index_of_com != -1: # # 下面一行是绝对路径传入获取配置文件的方法。 # test_file_abs_path = curr_sys_path[0:index_of_com] + file_path # else: # logger.info("被测路径不包含com") # if str(platform.system().lower()) == 'windows': # test_file_abs_path = curr_sys_path + '\\' + file_path # else: # test_file_abs_path = curr_sys_path + '/' + file_path # logger.info(f"test_file_abs_path={test_file_abs_path}") # with open(file=test_file_abs_path, mode='r', encoding="utf8") as f: # file_content = f.read() # line_list = file_content.split("\n") # test_class_line_num: int = 0 # test_case_start_line_num: int = 0 # test_case_line_indent_count = 0 # line_num = 0 # for curr_line in line_list: # line_num += 1 # if curr_line.strip().startswith("#"): # logger.info(f"第{line_num}行是纯注释行") # elif test_class in curr_line: # logger.info(f"测试类={test_class},在第{line_num}行。") # test_class_line_num = line_num # elif "def "+test_case_name in curr_line and line_num > test_class_line_num > 0: # logger.info(f"测试类={test_class},用例={test_case_name},从第{line_num}行开始。") # test_case_start_line_num = line_num # test_case_line_indent_count = BaseConfTest.__count_space(curr_line) # elif line_num > test_case_start_line_num > test_class_line_num and test_case_line_indent_count == BaseConfTest.__count_space(curr_line): # logger.info(f"测试类={test_class},用例={test_case_name},到第{line_num-1}行结束。") # break # else: # 测试方法体中的内容 # if line_num > test_case_start_line_num and curr_line.strip().startswith("assert"): # logger.info(f"测试类={test_class},用例={test_case_name},在第{line_num}行使用了断言。") # assertion_flag = True # else: # continue # else: # logger.warning(f"pytest_file_class={pytest_file_class}, 不包含::") return assertion_flag @staticmethod def __count_space(content: str): for i, j in enumerate(content): if j != ' ': return i
51job-autotest-framework
/51job_autotest_framework-0.3.1-py3-none-any.whl/rolling_king/autotest/tests/base/base_conftest.py
base_conftest.py
#!/usr/bin/python3 # -*- coding: utf-8 -*- # @Time : 2021/12/8 3:26 下午 # @Author : zhengyu.0985 # @FileName: base_test.py # @Software: PyCharm import uuid from rolling_king.autotest.db.sqlalchemy_util import AlchemyUtil from rolling_king.autotest.db.db_models import CaseRecordDecoder, CaseRecordModel, ExecutionRecordModel, ExecutionRecordDecoder, ExecutionStatisticModel import logging import configparser import json import os import time logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s') # logging.basicConfig函数对日志的输出格式及方式做相关配置 logger = logging.getLogger('requests.http_sender_module') class BaseTest(object): conf_absolute_path = "../../../conf/" # 默认值是一个相对路径,但若测试类的python文件绝对路径包含com,则会被修改为绝对路径以适用。 case_record_dict_list = [] # 每次测试执行收集测试用例信息的列表。 # 以下属性是测试执行记录所用到 unique_tag = None # 每次测试执行的唯一标识。 execution_record_dict_list = [] # 每次测试执行收集测试执行结果的列表。 test_project_name = '' test_psm = '' @staticmethod def _get_project_param_dict(project_conf_file_path: str = ''): if project_conf_file_path == '': test_dict_val = { "test_project_name": BaseTest.test_project_name, "test_psm": BaseTest.test_psm } else: project_conf_file = open(project_conf_file_path) cf = configparser.ConfigParser() cf.read_file(project_conf_file) logger.info("从 %s 读取到 %d 个配置项。" % (project_conf_file_path, len(cf.items()))) test_dict_val = { "test_project_name": cf.get("project", "TEST_PROJECT_NAME"), "test_psm": cf.get("project", "TEST_PSM") } logger.info("项目参数 = %s" % test_dict_val) return test_dict_val @staticmethod def get_project_conf_dict(): curr_sys_path = os.getcwd() index_of_com = curr_sys_path.find("com") if index_of_com != -1: # 下面一行是绝对路径传入获取配置文件的方法。 BaseTest.conf_absolute_path = curr_sys_path[0:index_of_com] + "com/conf/" project_param_dict = BaseTest._get_project_param_dict(BaseTest.conf_absolute_path + "project.conf") else: # 下面一行的相对路径会随测试py文件位置而变化,仅在测试文件绝对路径中不包含com时,做默认三层情况使用。 project_param_dict = BaseTest._get_project_param_dict() return project_param_dict @staticmethod def analyze_func_desc(entire_desc): tested_inter_dict_val = { "test_interface": "", "test_inter_type": "", "test_description": "", } desc_list = entire_desc.split("\n") for seg in desc_list: if seg.find("desc") != -1: start_index_desc = seg.find("desc") + 5 test_description = seg[start_index_desc:].strip() tested_inter_dict_val['test_description'] = test_description if seg.find("api_info") != -1: start_index_api_info = seg.find("api_info") + 9 desc_dict_str = seg[start_index_api_info:].strip() api_dict = json.loads(desc_dict_str) protocol = str(api_dict['protocol_type']).upper().strip() if protocol == "HTTP": if api_dict['method_name'] is None or len(str(api_dict['method_name'])) == 0: tested_inter_dict_val['test_inter_type'] = protocol else: # 若是HTTP类型且method_name不为空,则用method_name的值PUT GET POST DELETE来存入DB的test_inter_type字段。 tested_inter_dict_val['test_inter_type'] = str(api_dict['method_name']).upper().strip() tested_inter_dict_val['test_interface'] = api_dict['inter_name'] + "::" + api_dict['inter_path'] elif protocol == "RPC": tested_inter_dict_val['test_inter_type'] = protocol tested_inter_dict_val['test_interface'] = api_dict['inter_name'] + "." + api_dict['method_name'] else: logger.error("传入的protocol既不是PUT GET POST DELETE 也不是RPC。") logger.info("被测接口 = %s" % tested_inter_dict_val) return tested_inter_dict_val @staticmethod def _get_db_rela_conf_path(db_conf_path=None): if db_conf_path is not None: return db_conf_path else: curr_sys_path = os.getcwd() logger.info(f"curr_sys_path={curr_sys_path}") index_of_com = curr_sys_path.find("com") if index_of_com != -1: # 下面一行是绝对路径传入获取配置文件的方法。 BaseTest.conf_absolute_path = curr_sys_path[0:index_of_com] + "com/conf/" else: logger.warning("被测路径不包含com。") BaseTest.conf_absolute_path = curr_sys_path + "/com/conf/" return BaseTest.conf_absolute_path + "db.conf" @staticmethod def insert_update_delete(): # db_dict_val = AlchemyUtil.get_db_param_dict("QA_DB", BaseTest._get_db_rela_conf_path()) # 旧用法 db_dict_val = BaseTest.get_db_param_dict("QA_DB") site_rel_db_engine = AlchemyUtil.init_engine(db_dict_val) AlchemyUtil.init_db(site_rel_db_engine) # 创建表(存在则不创建) site_rel_db_session = AlchemyUtil.get_session(site_rel_db_engine) # 先删除自身本地调试的用例记录 deleted_debug_case_records_count = AlchemyUtil.delete_for_criteria_commit( site_rel_db_session, CaseRecordModel, criteria_set={ CaseRecordModel.test_project_name == '', CaseRecordModel.test_psm == '' }) logger.info(f'Totally delete previous {deleted_debug_case_records_count} debug case records') # 下面开始对本次测试的用例做分析。 case_change_flag = False # 用来判断是否本次执行相对于DB中的已存记录有变化(新增了或者删除了用例) project_conf_dict = BaseTest.get_project_conf_dict() # 查询 criteria_set = { # 这是<class 'set'>类型。 CaseRecordModel.test_psm == project_conf_dict['test_psm'], # 被测PSM CaseRecordModel.test_project_name == project_conf_dict['test_project_name'] #测试项目名 } # 获取DB中的test_psm和test_project_name条件的用例记录。 db_case_record_model_list = AlchemyUtil.query_obj_list(site_rel_db_session, CaseRecordModel, criteria_set=criteria_set) # 获取本次TEST的用例记录。 test_case_record_model_list = [] for curr_case_dict in BaseTest.case_record_dict_list: test_case_record_model_list.append(CaseRecordDecoder.dict_to_obj(curr_case_dict)) # 将TEST与DB所存的用例记录做对比,以判断是要插入还是更新还是删除。 logger.info("DB中现有记录:%d 个。" % len(db_case_record_model_list)) logger.info("本次测试记录:%s 个。" % len(test_case_record_model_list)) if len(db_case_record_model_list) == 0: # DB中没有现存记录,全是新增,直接插入即可。 # 在插入前为uid赋实际值。 ready_insert_test_case_model_list: list[CaseRecordModel] = [] for test_case_model in test_case_record_model_list: test_case_model.uid = uuid.uuid4().hex ready_insert_test_case_model_list.append(test_case_model) # 正式插入 AlchemyUtil.insert_list_with_flush_only(site_rel_db_session, ready_insert_test_case_model_list) AlchemyUtil.do_commit_only(site_rel_db_session) elif len(test_case_record_model_list) > 0: # DB中有现有记录且本次测试用例数>0 curr_version_in_db = db_case_record_model_list[0].version # 获取当前DB中相关用例的版本号。 matched_db_record_uid_list = [] disuse_db_record_uid_list = [] for db_case_model in db_case_record_model_list: logger.info("***当前 db_case_model: test_class=%s, test_method=%s, uid=%s" % (db_case_model.test_class, db_case_model.test_method, db_case_model.uid)) for test_case_model in test_case_record_model_list: # 当前db记录跟每一个测试记录比较。 logger.info("---当前 test_case_model: test_class=%s, test_method=%s" % (test_case_model.test_class, test_case_model.test_method)) if db_case_model.test_class == test_case_model.test_class and db_case_model.test_method == test_case_model.test_method: logger.info("找到 test_class=%s, test_method=%s 的 uid=%s DB记录:%s" % (db_case_model.test_class, db_case_model.test_method, db_case_model.uid, db_case_model.to_json())) test_case_model.uid = db_case_model.uid # 原本test_case_model.uid='0',找到匹配的就存DB中的uid的值。 logger.info("当前 test_case_model: test_class=%s, test_method=%s 设为 uid=%s" % (test_case_model.test_class, test_case_model.test_method, test_case_model.uid)) matched_db_record_uid_list.append(db_case_model.uid) logger.info("当前 db_case_model uid=%s 加入匹配列表中" % db_case_model.uid) break else: pass # End Inner For Loop if db_case_model.uid not in matched_db_record_uid_list: # 跟所有测试记录比对之后还未匹配,说明该条DB记录跟所有测试记录都不匹配,已经作废。 case_change_flag = True disuse_db_record_uid_list.append(db_case_model.uid) logger.info("DB中的 uid = %s 的记录作废,并加入作废列表中。" % db_case_model.uid) del_row = AlchemyUtil.delete_for_criteria_commit(site_rel_db_session, CaseRecordModel, {CaseRecordModel.uid == db_case_model.uid}) # 从数据库中也删除。 logger.info("DB中的 uid = %s 的 %d 条记录从DB数据库中删除:" % (db_case_model.uid, del_row)) else: pass # End Outer For Loop # 因全部循环已结束,所以打印匹配列表中的uid,看一看。 logger.info("匹配列表中的uid如下:") for matched_uid in matched_db_record_uid_list: logger.info("matched_uid = %s" % matched_uid) logger.info("作废列表中的uid如下:") # 因全部循环已结束,所以打印作废列表中的uid,看一看。 for disuse_uid in disuse_db_record_uid_list: logger.info("disuse_uid = %s" % disuse_uid) logger.info("本次测试一共作废 %d 个DB中的用例记录。" % len(disuse_db_record_uid_list)) # 下面处理本次测试新增的用例情况。 # test_case_record_model_list 中剩下的(没有匹配到的,也就是uid依然=0的那部分)是DB中没有的,也就是新增的,需要插入数据库。 new_case_count = 0 for test_case_model in test_case_record_model_list: if test_case_model.uid == '0': case_change_flag = True test_case_model.uid = uuid.uuid4().hex # 在插入前为uid赋实际值。 AlchemyUtil.insert_obj_with_commit(site_rel_db_session, test_case_model) new_case_count += 1 else: pass logger.info("本次测试一共新增 %d 个测试用例。" % new_case_count) # 依据 case_change_flag 标志位判断是否有用例的新增或删除,有变化则全部相关用例version增1 if case_change_flag: logger.info("本次测试用例有变化。") new_version = curr_version_in_db + 1 logger.info("new_version = %d" % new_version) update_dict = { 'version': new_version, 'gmt_modify': time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) } affected_row = AlchemyUtil.update_for_criteria_with_commit(site_rel_db_session, CaseRecordModel, criteria_set, update_dict) logger.info("【Success】Totally, {0} Records have been updated with version = {1}.".format(affected_row, new_version)) else: logger.info("本次测试毫无变化,无用例新增、无用例删除。") # End Elif else: logger.info("本次测试不包含任何测试用例。") # End Of insert_update_delete Method @staticmethod def insert_execution_record(): # db_dict_val = AlchemyUtil.get_db_param_dict("QA_DB", BaseTest.conf_absolute_path + "db.conf") # 旧用法 db_dict_val = BaseTest.get_db_param_dict("QA_DB") site_rel_db_engine = AlchemyUtil.init_engine(db_dict_val) AlchemyUtil.init_db(site_rel_db_engine) # 创建表(存在则不创建) site_rel_db_session = AlchemyUtil.get_session(site_rel_db_engine) # 先删除DB中因自身本地调试所存入的测试执行记录 deleted_debug_exec_records_count = AlchemyUtil.delete_for_criteria_commit( site_rel_db_session, ExecutionRecordModel, criteria_set={ ExecutionRecordModel.test_project_name == '', ExecutionRecordModel.test_psm == '' }) logger.info(f'Totally delete previous {deleted_debug_exec_records_count} debug execution records') # 开始获取当前DB中最后一次执行的unique tag。 project_conf_dict = BaseTest.get_project_conf_dict() # 查询 criteria_set = { # 这是<class 'set'>类型。 ExecutionRecordModel.test_psm == project_conf_dict['test_psm'], # 被测PSM ExecutionRecordModel.test_project_name == project_conf_dict['test_project_name'] # 测试项目名 } last_exec_tag_records = AlchemyUtil.query_field_list_with_distinct_orderby_limit( site_rel_db_session, (ExecutionRecordModel.test_unique_tag,), criteria_set=criteria_set, distinct_columns=(ExecutionRecordModel.test_unique_tag,), sequence='DESC', order_by_columns=(ExecutionRecordModel.gmt_create,), limit_val=1 ) if last_exec_tag_records is not None and len(last_exec_tag_records) == 1: last_exec_unique_tag = last_exec_tag_records[0][0] else: last_exec_unique_tag = '' logger.info(f'last_exec_unique_tag={last_exec_unique_tag}') # 获取本次执行的测试用例数,只有大于0才执行相关操作。 exec_record_num: int = len(BaseTest.execution_record_dict_list) logger.info(f"本次测试执行用例数=={exec_record_num}") if exec_record_num > 0: # 将本次测试之前DB中的最后一次执行的记录DB删除 criteria_set.add(ExecutionRecordModel.test_unique_tag == last_exec_unique_tag) last_exec_count: int = AlchemyUtil.delete_for_criteria_commit(site_rel_db_session, ExecutionRecordModel, criteria_set=criteria_set ) logger.info(f"从DB删除last_exec_unique_tag={last_exec_unique_tag}的{last_exec_count}条执行记录。") # 下面开始新插入执行记录至DB和统计DB exec_statistic_model: ExecutionStatisticModel = ExecutionStatisticModel() exec_statistic_model.uid = uuid.uuid4().hex exec_statistic_model.test_psm = project_conf_dict['test_psm'] exec_statistic_model.test_project_name = project_conf_dict['test_project_name'] exec_statistic_model.test_unique_tag = '' exec_statistic_model.test_cases_num = exec_record_num exec_statistic_model.test_duration = 0 test_pass_count: float = 0.0 test_interface_list: list[str] = [] test_assert_true_count = 0.0 # 原有代码供仅留存:开始插入新执行记录至DB # for curr_execution_dict in BaseTest.execution_record_dict_list: # logger.info("curr_execution_dict = %s" % curr_execution_dict) # curr_execution_model = ExecutionRecordDecoder.dict_to_obj(curr_execution_dict) # AlchemyUtil.insert_obj_without_commit(session=site_rel_db_session, obj=curr_execution_model) for curr_execution_dict in BaseTest.execution_record_dict_list: # 开始插入新执行记录至DB logger.info("curr_execution_dict = %s" % curr_execution_dict) curr_execution_model = ExecutionRecordDecoder.dict_to_obj(curr_execution_dict) AlchemyUtil.insert_obj_without_commit(session=site_rel_db_session, obj=curr_execution_model) # 上一行插入一条执行记录(但未commit)后,开始本次执行的统计工作。 # 累加用例执行时长 exec_statistic_model.test_duration += curr_execution_model.test_duration # 获取本次通过的用例数 if curr_execution_model.test_result == 'passed': test_pass_count += 1 # 获取本次测试的被测接口列表 if curr_execution_model.test_interface not in test_interface_list: test_interface_list.append(curr_execution_model.test_interface) # 获取使用了断言的数量 logger.info(f'当前断言的类型={type(curr_execution_model.test_assert)}') # <class 'bool'> logger.info(f'当前断言的值={curr_execution_model.test_assert}') if curr_execution_model.test_assert is True: # True or False test_assert_true_count += 1 # 做本次测试所有记录具有相同值的字段的唯一一次提取 if exec_statistic_model.test_unique_tag == '': exec_statistic_model.test_unique_tag = curr_execution_model.test_unique_tag # 循环结束后,率先将已进行插入DB的执行记录,做commit。 AlchemyUtil.do_commit_only(site_rel_db_session) logger.info("本次新增 %d 条测试执行记录并插入至DB。" % len(BaseTest.execution_record_dict_list)) # 然后做剩余的本次执行统计数据 exec_statistic_model.test_pass_rate = test_pass_count/exec_record_num exec_statistic_model.test_interface_num = len(test_interface_list) exec_statistic_model.test_assert_rate = test_assert_true_count/exec_record_num # 将本次执行的统计数据对象exec_statistic_model插入DB中。 if exec_statistic_model.test_psm == '' or exec_statistic_model.test_project_name == '': logger.info(f"因[被测服务名]或[测试项目名]为空,遂本次test_unique_tag={exec_statistic_model.test_unique_tag}的执行统计信息不做落库操作。") else: logger.info(f"开始插入test_unique_tag={exec_statistic_model.test_unique_tag}的执行统计信息。") AlchemyUtil.insert_obj_with_commit(site_rel_db_session, exec_statistic_model) else: logger.warning("本次测试执行用例数为零。") @classmethod def get_db_param_dict(cls, db_key, db_conf_relative_path='', db_type: str = 'mysql'): from rolling_king.autotest.conf import db_conf if db_conf_relative_path == '': logger.info(f"os.path.dirname={os.path.abspath(os.path.dirname(__file__))}") if db_type == "postgresql": db_dict = db_conf.postgresql elif db_type == "sqlite": db_dict = db_conf.sqlite else: db_dict = db_conf.mysql db_dict_val = db_dict[db_key] else: # 旧用法 conf_file = open(db_conf_relative_path) cf = configparser.ConfigParser() cf.read_file(conf_file) if db_type == "postgresql": json_str = cf.get("postgresql", db_key) elif db_type == "sqlite": json_str = cf.get("sqlite", db_key) else: json_str = cf.get("mysql", db_key) db_dict_val = json.loads(json_str) logger.info("%s = %s" % (db_key, db_dict_val)) return db_dict_val ############################################################################### if __name__ == "__main__": # 旧的用法 # dict_val = BaseTest.get_db_param_dict("QA_DB", "../../conf/db.conf", db_type="postgresql") # engine = AlchemyUtil.init_engine(dict_val, db_type="postgresql") # 新用法 dict_val = BaseTest.get_db_param_dict("QA_DB") engine = AlchemyUtil.init_engine(dict_val) AlchemyUtil.init_db(engine) # 创建表(存在则不创建) site_rel_db_session = AlchemyUtil.get_session(engine) # 先删除自身本地调试的用例记录 # deleted_debug_case_records_count = AlchemyUtil.delete_for_criteria_commit( # site_rel_db_session, CaseRecordModel, criteria_set={ # CaseRecordModel.test_project_name == '', # CaseRecordModel.test_psm == '' # }) # logger.info(f'Totally delete previous {deleted_debug_case_records_count} debug case records') # 先删除自身本地调试的记录 # deleted_debug_exec_records_count = AlchemyUtil.delete_for_criteria_commit( # site_rel_db_session, ExecutionRecordModel, criteria_set={ # ExecutionRecordModel.test_project_name == '', # ExecutionRecordModel.test_psm == '' # }) # logger.info(f'Totally delete previous {deleted_debug_exec_records_count} debug execution records') # 根据PSM和测试项目名,倒序找到最后一次执行的unique tag。 # records = AlchemyUtil.query_field_list_with_distinct_orderby_limit( # site_rel_db_session, (ExecutionRecordModel.test_unique_tag,), # criteria_set={ # 这是<class 'set'>类型。 # ExecutionRecordModel.test_psm == '51JobService', # 被测PSM # ExecutionRecordModel.test_project_name == '51JobPytest' # 测试项目名 # }, distinct_columns=(ExecutionRecordModel.test_unique_tag,), sequence='DESC', # order_by_columns=(ExecutionRecordModel.gmt_create,), limit_val=1 # ) # print(records) # 根据PSM和测试项目名,正序找到所有符合的执行unique tag。 # records = AlchemyUtil.query_field_list_with_distinct( # site_rel_db_session, (ExecutionRecordModel.test_unique_tag,), # criteria_set={ # 这是<class 'set'>类型。 # ExecutionRecordModel.test_psm == '51JobService', # 被测PSM # ExecutionRecordModel.test_project_name == '51JobPytest' # 测试项目名 # }, distinct_columns=(ExecutionRecordModel.test_unique_tag,) # ) # print(records) # 验证criteria_set的动态增加条件。 # criteria_set = { # 这是<class 'set'>类型。 # ExecutionRecordModel.test_psm == '51JobService', # 被测PSM # ExecutionRecordModel.test_project_name == '51JobPytest' # 测试项目名 # } # criteria_set.add(ExecutionRecordModel.test_unique_tag == '1692755269') # print([x.to_json() for x in AlchemyUtil.query_obj_list(site_rel_db_session, ExecutionRecordModel, criteria_set)])
51job-autotest-framework
/51job_autotest_framework-0.3.1-py3-none-any.whl/rolling_king/autotest/tests/base/base_test.py
base_test.py
#!/usr/bin/python3 # -*- coding: utf-8 -*- # @Time : 2021/12/8 3:26 下午 # @Author : zhengyu # @FileName: sqlalchemy_util.py # @Software: PyCharm from sqlalchemy import create_engine, and_, desc # from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker, declarative_base import logging import traceback import datetime import platform import os logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s') # logging.basicConfig函数对日志的输出格式及方式做相关配置 logger = logging.getLogger('db.sqlalchemy_util') class AlchemyUtil(object): # 基类 Base = declarative_base() @classmethod def init_engine(cls, db_param_dict, db_type: str = 'mysql'): """ 根据数据库连接串创建MySQL数据库的engine。 :param db_type: DB类型 :param db_param_dict: 数据连接串的各项参数的字典。 :return: MySQL数据库的engine。 """ host = db_param_dict['db_host'] user = db_param_dict['db_user'] passwd = db_param_dict['db_passwd'] db = db_param_dict['db_db'] charset = db_param_dict['db_charset'] port = db_param_dict['db_port'] logger.info("host = {0}".format(host)) logger.info("user = {0}".format(user)) logger.info("passwd = {0}".format(passwd)) logger.info("db = {0}".format(db)) logger.info("charset = {0}".format(charset)) logger.info("port = {0}".format(port)) if db_type == "postgresql": conn_str = "postgresql://" + user + ":" + passwd + "@" + host + ":" + port + "/" + db + "?charset=" + charset elif db_type == "sqlite": conn_str = None if str(platform.system().lower()) == 'windows': path = __file__.replace(fr"\{os.path.basename(__file__)}", "").replace("\\\\", "\\") conn_str = fr'sqlite:///{path}\db\sqlite_recruit.db''?check_same_thread=False' else: path = __file__.replace(fr"/{os.path.basename(__file__)}", "").replace("//", "/") conn_str = fr'sqlite:///{path}/db/sqlite_recruit.db''?check_same_thread=False' print(f'数据库路径:{conn_str}') else: conn_str = "mysql+pymysql://" + user + ":" + passwd + "@" + host + ":" + port + "/" + db + "?charset=" + charset db_engine = create_engine( conn_str, max_overflow=0, # 超过连接池大小外最多创建的连接 pool_size=5, # 连接池大小 pool_timeout=30, # 池中没有线程最多等待的时间,否则报错 pool_recycle=-1 # 多久之后对线程池中的线程进行一次连接的回收(重置) ) logger.info("[%s] engine has been created successfully." % db_engine.name) return db_engine @classmethod def init_db(cls, mysql_engine): """ 根据类创建数据库表 :return: """ AlchemyUtil.Base.metadata.create_all(mysql_engine) @classmethod def drop_db(cls, mysql_engine): """ 根据类删除数据库表 :return: """ AlchemyUtil.Base.metadata.drop_all(mysql_engine) @classmethod def init_db_by_flask(cls, db, bind_key=None): if bind_key is None: db.create_all() else: # 下面这句不能初始化Flask中的SQLAlchemy Table,因为里面是调用 create_all() of MetaData in sqlalchemy.sql.schema。 # AlchemyUtil.init_db(db.get_engine(bind="site_reldb")) db.create_all(bind=bind_key) # 这个是create_all() of SQLAlchemy in flask_sqlalchemy @classmethod def get_session(cls, mysql_engine): db_session = sessionmaker(bind=mysql_engine) # Session是<class 'sqlalchemy.orm.session.sessionmaker'> return db_session() @classmethod def insert_list_with_flush_only(cls, session, obj_list): try: for obj in obj_list: session.add(obj) session.flush() logger.info("【Success】一共插入 %d 条记录 by [insert_list_with_flush_only] method." % len(obj_list)) finally: logger.info("[insert_list_with_flush_only] method has done, but has not been committed yet.") @classmethod def insert_obj_with_commit(cls, session, obj): try: session.add(obj) session.commit() logger.info("【Success】插入一条记录:%s" % obj.__dict__) finally: session.close() logger.info("[insert_obj_with_commit] method has done and session has been closed.") @classmethod def insert_obj_without_commit(cls, session, obj): try: session.add(obj) session.flush() logger.info("【Success】插入一条记录:%s" % obj.__dict__) finally: logger.info("[insert_obj_without_commit] method has done but not committed yet.") @classmethod def do_commit_only(cls, session): try: session.commit() logger.info("session has been committed.") finally: session.close() logger.info("do_commit_only method has done and session has been closed.") @classmethod def query_first(cls, session, clazz, criteria_set=None): try: if criteria_set is None or len(criteria_set) == 0: sql = session.query(clazz) logger.info("执行全量查询SQL = %s" % sql) else: sql = session.query(clazz).filter(*criteria_set) logger.info("执行条件查询SQL = %s" % sql) record = sql.one_or_none() # 真正执行该查询。 return record finally: session.close() logger.info("[query_first] method has done and session has been closed.") @classmethod def query_obj_list(cls, session, clazz, criteria_set=None): try: if criteria_set is None or len(criteria_set) == 0: sql = session.query(clazz) logger.info("执行全量查询SQL = %s" % sql) else: sql = session.query(clazz).filter(*criteria_set) logger.info("执行条件查询SQL = %s" % sql) record_list = sql.all() # 真正执行该查询。 logger.info("查询获取到 %d 条记录。" % len(record_list)) return record_list finally: session.close() logger.info("[query_obj_list] method has done and session has been closed.") @classmethod def query_field_list(cls, session, entities, criteria_set=None): try: if criteria_set is None or len(criteria_set) == 0: sql = session.query(*entities) logger.info("执行全量查询SQL = %s" % sql) else: sql = session.query(*entities).filter(*criteria_set) logger.info("执行条件查询SQL = %s" % sql) fields_record_list = sql.all() # 真正执行该查询。 logger.info("查询获取到 %d 条记录。" % len(fields_record_list)) return fields_record_list finally: session.close() logger.info("[query_field_list] method has done and seesion has been closed.") @classmethod def query_field_list_with_distinct(cls, session, entities, criteria_set=None, distinct_columns=None): try: if criteria_set is None or len(criteria_set) == 0: if distinct_columns is None or len(distinct_columns) == 0: sql = session.query(*entities) else: sql = session.query(*entities).distinct(*distinct_columns) logger.info("执行全量查询SQL = %s" % sql) else: if distinct_columns is None or len(distinct_columns) == 0: sql = session.query(*entities).filter(*criteria_set) else: sql = session.query(*entities).filter(*criteria_set).distinct(*distinct_columns) logger.info("执行条件查询SQL = %s" % sql) fields_record_list = sql.all() # 真正执行该查询。 logger.info("查询获取到 %d 条记录。" % len(fields_record_list)) return fields_record_list finally: session.close() logger.info("[query_field_list_with_distinct] method has done and seesion has been closed.") @classmethod def query_field_list_with_distinct_orderby_limit(cls, session, entities, criteria_set=None, distinct_columns=None, order_by_columns=None, sequence: str = 'ASC', limit_val: int = 0): try: if criteria_set is None or len(criteria_set) == 0: if distinct_columns is None or len(distinct_columns) == 0: sql = session.query(*entities) else: sql = session.query(*entities).distinct(*distinct_columns) logger.info("执行全量查询SQL = %s" % sql) else: if distinct_columns is None or len(distinct_columns) == 0: if order_by_columns is None and limit_val == 0: sql = session.query(*entities).filter(*criteria_set) elif order_by_columns is not None and sequence == 'DESC' and limit_val > 0: sql = session.query(*entities).filter(*criteria_set).order_by( and_([x.desc() for x in order_by_columns]) ).limit(limit_val) else: sql = (session.query(*entities).filter(*criteria_set). order_by(and_(*order_by_columns)).limit(limit_val)) else: if order_by_columns is None and limit_val == 0: sql = session.query(*entities).filter(*criteria_set).distinct(*distinct_columns) elif order_by_columns is not None and sequence == 'DESC' and limit_val > 0: sql = session.query(*entities).filter(*criteria_set).distinct(*distinct_columns).order_by( # 列表生成式让每一个排序字段调用.desc()方法。相当于生成了[gmt_create.desc(), gmt_modify.desc()]列表。 and_(*[x.desc() for x in order_by_columns]) ).limit(limit_val) else: sql = session.query(*entities).distinct(*distinct_columns).filter(*criteria_set).order_by( and_(*order_by_columns) ).limit(limit_val) logger.info("执行条件查询SQL = %s" % sql) fields_record_list = sql.all() # 真正执行该查询。 logger.info("查询获取到 %d 条记录。" % len(fields_record_list)) return fields_record_list finally: session.close() logger.info("[query_field_list_with_distinct] method has done and seesion has been closed.") @classmethod def update_for_criteria_with_commit(cls, session, clazz, criteria_set=None, update_dict={}): """ :param session: db_session :param clazz: db_model_name :param criteria_set: query's criteria :param update_dict: update's field-value pairs :return: row count of updated records """ if len(update_dict) > 0: try: if criteria_set is None or len(criteria_set) == 0: sql = session.query(clazz) logger.info("执行全量查询SQL = %s" % sql) else: sql = session.query(clazz).filter(*criteria_set) logger.info("执行条件查询SQL = %s" % sql) affected_row = sql.update(update_dict) # 真正执行更新,返回更新的记录条数。 session.commit() logger.info("【Success】一共更新 %d 行记录。" % affected_row) return affected_row except: session.rollback() logger.warning("出现异常") logger.error(traceback.format_exc()) finally: session.close() else: logger.warning("依据update_dict参数,传入的需要更新的字段个数为零,无法更新。") @classmethod def delete_for_criteria_commit(cls, session, clazz, criteria_set=None): """ :param session: db_session :param clazz: db_model_name :param criteria_set: query's criteria :return: row count of deleted records """ try: if criteria_set is None or len(criteria_set) == 0: logger.info("criteria_set 为空,不可删除全部记录,有风险。") return 0 else: sql = session.query(clazz).filter(*criteria_set) logger.info("执行条件查询SQL = %s" % sql) affected_row = sql.delete() # 真正执行删除,返回删除的记录条数。 session.commit() # logger.info("【Success】一共删除 %d 行记录,依据条件:%s" % (affected_row, *criteria_set)) # 类似这种pytest_execution_record.test_psm IS NULL 有NULL的条件,上一行报错。 logger.info("【Success】一共删除 %d 行记录." % affected_row) return affected_row except: session.rollback() logger.warning("出现异常") logger.error(traceback.format_exc()) finally: session.close() @classmethod def gen_unique_key(cls): dt = datetime.datetime.now() dt_str = dt.strftime('%Y%m%d%H%M%S') ts = datetime.datetime.timestamp(dt) ts_str = str(int(ts * 1000000)) unique_key = dt_str + ts_str return unique_key if __name__ == "__main__": pass
51job-autotest-framework
/51job_autotest_framework-0.3.1-py3-none-any.whl/rolling_king/autotest/db/sqlalchemy_util.py
sqlalchemy_util.py
#!/usr/bin/python3 # -*- coding: utf-8 -*- # @Time : 2021/12/8 3:26 下午 # @Author : zhengyu # @FileName: db_util.py # @Software: PyCharm import pymysql import configparser import json import sys # 定义一个db链接类 class DBConn: """ 使用cnn进行db连接 """ def __init__(self, db_key, db_conf_relative_path): self.db_key = db_key conf_file = open(db_conf_relative_path) cf = configparser.ConfigParser() cf.read_file(conf_file) json_str = cf.get("mysql", db_key) print(json_str) dict_val = json.loads(json_str) host = dict_val['db_host'] user = dict_val['db_user'] passwd = dict_val['db_passwd'] db = dict_val['db_db'] charset = dict_val['db_charset'] port = dict_val['db_port'] print("host = {0}".format(host)) print("user = {0}".format(user)) print("passwd = {0}".format(passwd)) print("db = {0}".format(db)) print("charset = {0}".format(charset)) print("port = {0}".format(port)) self.conn = pymysql.connect(host=host, user=user, passwd=passwd, db=db, charset=charset, port=int(port), ) print("成功连接{0}数据库。".format(self.db_key)) def query_db(self, sql_str): cur = self.conn.cursor() try: affected_row = cur.execute(sql_str) print("【{0}】SQL语句返回{1}条数据".format(sql_str, affected_row)) self.conn.commit() return cur.fetchall() except Exception as e: print(e.with_traceback(sys.exc_info()[2])) finally: cur.close() def update_db(self, sql_str): cur = self.conn.cursor() try: affected_row = cur.execute(sql_str) self.conn.commit() print("【{0}】SQL语句共影响{1}条数据".format(sql_str, affected_row)) return affected_row except Exception as e: print(e.with_traceback(sys.exc_info()[2])) finally: cur.close() def close_db(self): self.conn.close() print("与{0}的数据库连接已关闭。".format(self.db_key)) if __name__ == "__main__": # 建立连接 conn = DBConn("DB_BOE_Site_Reldb", "../../conf/db.conf") # 执行SELECT tuple_result = conn.query_db("select * from union_media where id in (45535, 45532, 45507, 259);") print(tuple_result) for row_result in tuple_result: print("当前行元祖为:", row_result) print("当前行共{0}个字段".format(len(row_result))) print("当前行第一个字段值=", row_result[0]) # 执行UPDATE affected_row_num = conn.update_db("update union_media_function_rel set function_id = 35 where id = '111287';") print("更新了{0}行。".format(affected_row_num)) # 关闭连接 conn.close_db()
51job-autotest-framework
/51job_autotest_framework-0.3.1-py3-none-any.whl/rolling_king/autotest/db/db_util.py
db_util.py
#!/usr/bin/python3 # -*- coding: utf-8 -*- # @Time : 2021/12/8 3:26 下午 # @Author : zhengyu # @FileName: db_models.py # @Software: PyCharm from rolling_king.autotest.db.sqlalchemy_util import AlchemyUtil from sqlalchemy import Column, Integer, String, DateTime, Float import datetime import json import re class CaseRecordModel(AlchemyUtil.Base): __tablename__ = 'pytest_case_record' # uid = Column(Integer, primary_key=True, autoincrement=True) # '测试用例唯一标识' uid = Column(String(32), primary_key=True) # uuid.uuid4().hex test_project_name = Column(String(64)) # 'QA的Python测试项目名称' test_psm = Column(String(32)) # '被测PSM' test_interface = Column(String(64)) # '被测接口: Http接口是subrui, Thrift接口是Service.Method' test_inter_type = Column(String(8)) # '接口协议类型' test_class = Column(String(64)) # 'Pytest的测试类:package.Class' test_method = Column(String(64)) # 'Pytest的测试方法名' test_description = Column(String(128)) # '测试用例描述' version = Column(Integer) # '用例版本号' gmt_create = Column(DateTime, default=datetime.datetime.now) # '记录创建时间' gmt_modify = Column(DateTime, default=datetime.datetime.now) # '记录修改时间' def to_json(self): dict = self.__dict__ if "_sa_instance_state" in dict: del dict["_sa_instance_state"] return dict # 重写JSONEncoder的default方法,object转换成dict class CaseRecordEncoder(json.JSONEncoder): # 重写default方法 def default(self, obj): """ 把【Object】转成【Dict字典】 :param obj: :return: """ if isinstance(obj, CaseRecordModel): return { 'uid': obj.uid, 'test_project_name': obj.test_project_name, 'test_psm': obj.test_psm, 'test_interface': obj.test_interface, 'test_inter_type': obj.test_inter_type, 'test_class': obj.test_class, 'test_method': obj.test_method, 'test_description': obj.test_description, 'version': obj.version, 'gmt_create': obj.gmt_create, 'gmt_modify': obj.gmt_modify } else: return json.JSONEncoder.default(self, obj) # 重写encode方法 def encode(self, obj): """ 把【Object】转成【Dict字典】再转成【String】 :param obj: :return: """ if isinstance(obj, CaseRecordModel): dict_val = { 'uid': obj.uid, 'test_project_name': obj.test_project_name, 'test_psm': obj.test_psm, 'test_interface': obj.test_interface, 'test_inter_type': obj.test_inter_type, 'test_class': obj.test_class, 'test_method': obj.test_method, 'test_description': obj.test_description, 'version': obj.version, 'gmt_create': obj.gmt_create, 'gmt_modify': obj.gmt_modify } return str(dict_val) else: return json.JSONEncoder.encode(self, obj) # 重写JSONDecoder的decode方法,dict转换成object class CaseRecordDecoder(json.JSONDecoder): def decode(self, dict_str): """ 把【字符串】转成【字典】再转成【Object】 :param dict_str: 字典的字符串 :return: """ dict_val = super().decode(dict_str) # 先把str转dict # 下面是dict转object CaseRecordDecoder.dict_to_obj(dict_val) @staticmethod def dict_to_obj(dict_val): """ 把【字典Dict】直接转成对应的【Object】 :param dict_val: :return: """ case_record_model = CaseRecordModel() if 'uid' in dict_val.keys(): case_record_model.uid = dict_val['uid'] else: case_record_model.uid = '0' case_record_model.test_project_name = dict_val['test_project_name'] case_record_model.test_psm = dict_val['test_psm'] case_record_model.test_interface = dict_val['test_interface'] case_record_model.test_inter_type = dict_val['test_inter_type'] case_record_model.test_class = dict_val['test_class'] case_record_model.test_method = dict_val['test_method'] case_record_model.test_description = dict_val['test_description'] case_record_model.version = dict_val['version'] return case_record_model ############################################################################ class ExecutionRecordModel(AlchemyUtil.Base): __tablename__ = 'pytest_execution_record' # uid = Column(Integer, primary_key=True, autoincrement=True) # '测试记录每一个TestCase执行的唯一标识' uid = Column(String(32), primary_key=True) # uuid.uuid4().hex test_unique_tag = Column(String(64)) # '一次整体测试的唯一标签' test_project_name = Column(String(64)) # 'QA的Python测试项目名称' test_psm = Column(String(32)) # '被测PSM' test_interface = Column(String(64)) # '被测接口: Http接口是subrui, Thrift接口是Service.Method' test_inter_type = Column(String(8)) # '接口协议类型' test_class = Column(String(64)) # 'Pytest的测试类:package.Class' test_method = Column(String(64)) # 'Pytest的测试方法名' test_result = Column(String(8)) # '测试用例执行结果' test_params = Column(String(64)) # 'Pytest的测试方法入参' test_duration = Column(Integer) # '测试用例执行耗时' test_start_time = Column(String(64)) # '测试用例执行起始时间' test_finish_time = Column(String(64)) # '测试用例执行完成时间' test_assert = Column(String(8)) # '测试用例是否使用Assert断言' test_error_msg = Column(String(32)) # '测试用例失败信息' gmt_create = Column(DateTime, default=datetime.datetime.now) # '记录创建时间' gmt_modify = Column(DateTime, default=datetime.datetime.now) # '记录修改时间' def to_json(self): dict = self.__dict__ if "_sa_instance_state" in dict: del dict["_sa_instance_state"] return dict # 重写JSONEncoder的default方法,object转换成dict class ExecutionRecordEncoder(json.JSONEncoder): # 重写default方法 def default(self, execution_obj): """ 把【Object】转成【Dict字典】 :param execution_obj: :return: """ if isinstance(execution_obj, ExecutionRecordModel): return { 'uid': execution_obj.uid, 'test_unique_tag': execution_obj.test_unique_tag, 'test_project_name': execution_obj.test_project_name, 'test_psm': execution_obj.test_psm, 'test_interface': execution_obj.test_interface, 'test_inter_type': execution_obj.test_inter_type, 'test_class': execution_obj.test_class, 'test_method': execution_obj.test_method, 'test_result': execution_obj.test_result, 'test_params': execution_obj.test_params, 'test_duration': execution_obj.test_duration, 'test_start_time': execution_obj.test_start_time, 'test_finish_time': execution_obj.test_finish_time, 'test_assert': execution_obj.test_assert, 'test_error_msg': execution_obj.test_error_msg, 'gmt_create': execution_obj.gmt_create, 'gmt_modify': execution_obj.gmt_modify } else: return json.JSONEncoder.default(self, execution_obj) # 重写encode方法 def encode(self, execution_obj): """ 把【Object】转成【Dict字典】再转成【String】 :param execution_obj: :return: """ if isinstance(execution_obj, CaseRecordModel): return str(ExecutionRecordEncoder.default(execution_obj)) else: return json.JSONEncoder.encode(self, execution_obj) # 重写JSONDecoder的decode方法,dict转换成object class ExecutionRecordDecoder(json.JSONDecoder): def decode(self, dict_str): """ 把【字符串】转成【字典】再转成【Object】 :param dict_str: 字典的字符串 :return: """ dict_val = super().decode(dict_str) # 先把str转dict # 下面是dict转object ExecutionRecordDecoder.dict_to_obj(dict_val) @staticmethod def dict_to_obj(dict_val): """ 把【字典Dict】直接转成对应的【Object】 :param dict_val: :return: """ execution_record_model = ExecutionRecordModel() if 'uid' in dict_val.keys(): execution_record_model.uid = dict_val['uid'] else: execution_record_model.uid = '0' execution_record_model.test_unique_tag = dict_val['test_unique_tag'] execution_record_model.test_project_name = dict_val['test_project_name'] execution_record_model.test_psm = dict_val['test_psm'] execution_record_model.test_interface = dict_val['test_interface'] execution_record_model.test_inter_type = dict_val['test_inter_type'] execution_record_model.test_class = dict_val['test_class'] execution_record_model.test_method = dict_val['test_method'] execution_record_model.test_result = dict_val['test_result'] execution_record_model.test_params = dict_val['test_params'] execution_record_model.test_duration = dict_val['test_duration'] execution_record_model.test_start_time = dict_val['test_start_time'] execution_record_model.test_finish_time = dict_val['test_finish_time'] execution_record_model.test_assert = dict_val['test_assert'] execution_record_model.test_error_msg = dict_val['test_error_msg'] return execution_record_model class ExecutionStatisticModel(AlchemyUtil.Base): __tablename__ = 'pytest_exec_statistic_record' uid = Column(String(32), primary_key=True) # uuid.uuid4().hex test_unique_tag = Column(String(16)) # '一次整体测试的唯一标签' test_project_name = Column(String(64)) # 'QA的Python测试项目名称' test_psm = Column(String(32)) # '被测PSM' test_cases_num = Column(Integer) # '本次测试的用例个数' test_pass_rate = Column(Float) # '本次测试的通过率' test_duration = Column(Integer) # '本次测试的总体执行耗时' test_assert_rate = Column(Float) # '本次测试使用Assert断言比率' test_interface_num = Column(Integer) # '本次测试的覆盖接口数' gmt_create = Column(DateTime, default=datetime.datetime.now) # '记录创建时间' gmt_modify = Column(DateTime, default=datetime.datetime.now) # '记录修改时间' def to_json(self): dict = self.__dict__ if "_sa_instance_state" in dict: del dict["_sa_instance_state"] return dict ################################################################################# ###### 下方是全部接口Model:BamInterModel 和 未覆盖接口Model:NonCovInterModel ###### FLAGS = re.VERBOSE | re.MULTILINE | re.DOTALL WHITESPACE = re.compile(r'[ \t\n\r]*', FLAGS) def gen_unique_key(): dt = datetime.datetime.now() dt_str = dt.strftime('%Y%m%d%H%M%S') ts = datetime.datetime.timestamp(dt) ts_str = str(int(ts * 1000000)) unique_key = dt_str + ts_str return unique_key class BamInterModel(AlchemyUtil.Base): __bind_key__ = "site_reldb" # 若不指定,则使用默认数据库。 __tablename__ = 'psm_inter_info' id = Column(String(32), primary_key=True) psm = Column(String(64), nullable=False) endpoint_id = Column(String(64), nullable=False) method = Column(String(8)) path = Column(String(128)) level = Column(Integer) name = Column(String(64)) note = Column(String(64)) rpc_method = Column(String(64)) creator = Column(String(16)) updater = Column(String(32)) modify_time = Column(String(32)) create_time = Column(String(32)) publish_status = Column(Integer) priority = Column(Integer) version = Column(String(8)) gmt_create = Column(DateTime, default=datetime.datetime.now) def to_json(self): dict = self.__dict__ if "_sa_instance_state" in dict: del dict["_sa_instance_state"] return dict # 重写JSONEncoder的default方法,object转换成dict class BamInterEncoder(json.JSONEncoder): # 重写default方法 def default(self, obj): """ 把【Object】转成【Dict字典】 :param obj: :return: """ if isinstance(obj, BamInterModel): return { 'id': obj.id, 'psm': obj.psm, 'endpoint_id': obj.endpoint_id, 'method': obj.method, 'path': obj.path, 'level': obj.level, 'name': obj.name, 'note': obj.note, 'rpc_method': obj.rpc_method, 'creator': obj.creator, 'updater': obj.updater, 'create_time': obj.create_time, 'modify_time': obj.modify_time, 'publish_status': obj.publish_status, 'priority': obj.priority, 'version': obj.version, 'gmt_create': obj.gmt_create } else: return json.JSONEncoder.default(self, obj) # 重写encode方法 def encode(self, obj): """ 把【Object】转成【Dict字典】再转成【String】 :param obj: :return: """ if isinstance(obj, BamInterModel): return str(self.default(obj)) else: return json.JSONEncoder.encode(self, obj) # 重写JSONDecoder的decode方法,dict转换成object class BamInterDecoder(json.JSONDecoder): def decode(self, dict_str, _w=WHITESPACE.match): """ 把【字符串】转成【字典】再转成【Object】 :param dict_str: 字典的字符串 :param _w: :return: """ dict_val = super().decode(dict_str) # 先把str转dict # 下面是dict转object self.dict_to_obj(dict_val) @staticmethod def dict_to_obj(dict_val): """ 把【字典Dict】直接转成对应的【Object】 :param dict_val: :return: """ bam_inter_model = BamInterModel() if 'uid' in dict_val.keys(): bam_inter_model.id = dict_val['id'] else: bam_inter_model.id = gen_unique_key() bam_inter_model.psm = dict_val['psm'] bam_inter_model.endpoint_id = dict_val['endpoint_id'] bam_inter_model.method = dict_val['method'] bam_inter_model.path = dict_val['path'] bam_inter_model.level = dict_val['level'] bam_inter_model.name = dict_val['name'] bam_inter_model.note = dict_val['note'] bam_inter_model.rpc_method = dict_val['rpc_method'] bam_inter_model.creator = dict_val['creator'] bam_inter_model.updater = dict_val['updater'] bam_inter_model.create_time = dict_val['create_time'] bam_inter_model.modify_time = dict_val['modify_time'] bam_inter_model.publish_status = dict_val['publish_status'] bam_inter_model.priority = dict_val['priority'] bam_inter_model.version = dict_val['version'] if 'gmt_create' in dict_val.keys(): bam_inter_model.gmt_create = dict_val['gmt_create'] return bam_inter_model class NonCovInterModel(AlchemyUtil.Base): __bind_key__ = "site_reldb" # 若不指定,则使用默认数据库。 __tablename__ = 'psm_non_cov_inter' id = Column(String(32), primary_key=True) psm = Column(String(64), nullable=False) endpoint_id = Column(String(64), nullable=False) method = Column(String(8)) path = Column(String(128)) name = Column(String(64)) note = Column(String(64)) rpc_method = Column(String(64)) version = Column(String(8)) gmt_create = Column(DateTime, default=datetime.datetime.now) def to_json(self): dict = self.__dict__ if "_sa_instance_state" in dict: del dict["_sa_instance_state"] return dict
51job-autotest-framework
/51job_autotest_framework-0.3.1-py3-none-any.whl/rolling_king/autotest/db/db_models.py
db_models.py
#!/usr/bin/python3 # -*- coding: utf-8 -*- mysql = { "QA_DB": { "db_host": "10.100.3.194", "db_port": "3306", "db_db": "quality", "db_user": "root", "db_passwd": "z85#QHbcuX", "db_charset": "utf8" } } postgresql = { "QA_DB": { "db_host": "10.100.50.246", "db_port": "5432", "db_db": "sonar", "db_user": "sonar", "db_passwd": "sonar", "db_charset": "utf8" } } sqlite = {}
51job-autotest-framework
/51job_autotest_framework-0.3.1-py3-none-any.whl/rolling_king/autotest/conf/db_conf.py
db_conf.py
#!/usr/bin/python3 # -*- coding: UTF-8 -*- from src.rolling_king.jason.requests.http_sender_module import HttpSender import json import pytest class TestCCCPlatform(object): def test_get(self): http_sender_obj = HttpSender("http://10.72.108.71:8080/") HttpSender.headers = {"header": "This is a customerized header"} input_param = {"groupName": "XY_CCC_GROUP"} http_sender_obj.send_get_request_by_suburi("meta/application.json", input_param) result_str = http_sender_obj.get_response.text print("结果:", result_str) dict_val = json.loads(result_str) print(type(dict_val)) print(json.dumps(dict_val, indent=2)) if __name__ == "__main__": pytest.main(["-s", "test_ccc.py"])
51job-autotest-framework
/51job_autotest_framework-0.3.1-py3-none-any.whl/rolling_king/jason/requests/test_ccc.py
test_ccc.py
#!/usr/bin/python3 # -*- coding: UTF-8 -*- import requests import urllib3 urllib3.disable_warnings() class HttpSender(object): get_response = "" post_response = "" hostname = "" # 公有的类属性 __cookies = {} # 私有的类属性 # def __init__(self): # print("HttpSender Default Constructor has been called.") def __init__(self, hostname, headers=None): print("HttpSender Parameter Constructor has been called.") self.hostname = hostname self.headers = headers # self.headers的这个headers是实例属性,可以用实例直接方法。 print("self.headers = {0}".format(self.headers)) def set_headers(self, headers): self.headers = headers print("成员方法设置请求头:self.headers = {0}".format(self.headers)) print("self.headers = {0}".format(self.headers)) # 类方法,用classmethod来进行修饰 # 注:类方法和实例方法同名,则类方法会覆盖实例方法。所以改个名字。 @classmethod # def set_headers(cls, headers): def set_cls_headers(cls, headers): cls.headers = headers print("类方法设置请求头:cls.headers = {0}".format(cls.headers)) def send_get_request(self, full_get_url): self.get_response = requests.get(full_get_url, headers=self.headers) print("响应:", self.get_response.text) def send_get_request_by_suburi(self, sub_uri, input_params): full_url = self.hostname + sub_uri self.get_response = requests.get(full_url, params=input_params, headers=self.headers) print("full_url = %s" % self.get_response.url) def send_post_request(self, full_post_url, param_data=None): self.post_response = requests.post(full_post_url, param_data, headers=self.headers) def send_json_post_request(self, full_post_url, json_data=None): self.post_response = requests.post(full_post_url, json=json_data, headers=self.headers) # 静态方法 @staticmethod def send_json_post_request_with_headers_cookies(self, full_post_url, json_data=None, header_data=None, cookie_data=None): # 在静态方法中引用类属性的话,必须通过类实例对象来引用 # print(self.hostname) self.post_response = requests.post(full_post_url, json=json_data, headers=header_data, cookies=cookie_data) def send_json_post_request_by_suburi(self, sub_uri, json_data=None): full_url = self.hostname + sub_uri self.post_response = requests.post(full_url, json=json_data, headers=self.headers) # *args 和 **kwargs 都代表 1个 或 多个 参数的意思。*args 传入tuple 类型的无名参数,而 **kwargs 传入的参数是 dict 类型. # 可变参数 (Variable Argument) 的方法:使用*args和**kwargs语法。# 其中,*args是可变的positional arguments列表,**kwargs是可变的keyword arguments列表。 # 并且,*args必须位于**kwargs之前,因为positional arguments必须位于keyword arguments之前。 r = requests.get("http://www.baidu.com") print(r.text)
51job-autotest-framework
/51job_autotest_framework-0.3.1-py3-none-any.whl/rolling_king/jason/requests/http_sender_module.py
http_sender_module.py
#!/usr/bin/python3 # -*- coding: UTF-8 -*- from src.rolling_king.jason.requests.http_sender_module import HttpSender import json import pytest class TestMPlatform(object): def test_get(self): http_sender_obj = HttpSender("https://boe-pangle-ssr.bytedance.net") http_sender_obj.set_headers({"Cookie": "passport_csrf_token_default=7501cdcbfc561e1dffe8452164dece87; pangle-i18n=zh; Hm_lvt_ff76cafb7653fe92a16e2025d769a918=1612672717; ttwid=1|1Pu6X3dj5YcMDj9Dtss-tGhvumhWp9QZg2s4_utiIQ4|1612672716|18b21ed88c5818720d89aee191e66bd1638187844f611b0081a6a2388c5bc354; s_v_web_id=kkunp4qt_PTwUJMKm_Uonp_4Fwh_AsWK_zHI7O7fN80d7; n_mh=9-mIeuD4wZnlYrrOvfzG3MuT6aQmCUtmr8FxV8Kl8xY; passport_auth_status=f2c05d0bf656747c3d37303dc3e18bdc,; odin_tt=5d94aaa8493d549085bf91a5061f80e0ea261173c1d7750f9dd337506eac3514c2205482622ab8b69f957ece8ea74b55e0f1d34fe50e2fd1b6ba373004f76f20; sid_guard=09c5bfc37b0ecdacd699d86ddd66b828|1612861802|21600|Tue,+09-Feb-2021+15:10:02+GMT; uid_tt=9e04001ec1a1242ca4012de5252d12eb; uid_tt_ss=9e04001ec1a1242ca4012de5252d12eb; sid_tt=09c5bfc37b0ecdacd699d86ddd66b828; sessionid=09c5bfc37b0ecdacd699d86ddd66b828; sessionid_ss=09c5bfc37b0ecdacd699d86ddd66b828; Hm_lpvt_ff76cafb7653fe92a16e2025d769a918=1612861804; mhjseduw32ewkejf_gdald_sda7=P3nG6lT2_KmKQzKGgGf44J3rRfZFlrQne5aBB8N1VvJ2hNQBr_MNqmu3q0APHwel6wcSZ_Nj7ouasdtVAXk0FFGqoVN6YtBKm-5ksaDFdMOXYTIDDWlXD8UkP6y94ma-1uP_wEDvEHK4Lycz57eFFgb06B4ceIzJWthR0NzrL2g=; session=.eJw9jr0OgjAYRV_FfDNDqZSSJi4GBofiIhprDCltUVDQ8BO0hHeXGON0bs5y7ghSV0WdFhqY6_qEOiAvpu6-wiMEzUK1TZ52j5upgY2wyIABLyMkDuImdomNw3U183W0_C3CjT3aZIgtH7a79VWU-5Lj6BWX14IPqxVMDjybh-5VBwz_dwvshM8ONOYuO6PTvjXN9wFy4BeG3CMBpp5RLkFBRnBOJdKS-IqamRQrgvAyywOYPn-VQ2Y.YCJUoA.WRNs_NowrVpiR50sSuxR3_4F7W8; gftoken=MDljNWJmYzM3YnwxNjEyODYyNjI0MjZ8fDAGBgYGBgY; MONITOR_WEB_ID=45507"}) input_param = {"AdUnitId": "1172", "ExperimentGroupType": 1, "Page": 1, "StartDate": "2021-02-09", "EndDate": "2021-02-09"} http_sender_obj.send_get_request_by_suburi("/union_pangle/api/mediation/waterfall/detail", input_param) result_str = http_sender_obj.get_response.text print("结果:", result_str) dict_val = json.loads(result_str) print(type(dict_val)) print(json.dumps(dict_val, indent=2)) if __name__ == "__main__": pytest.main(["-s", "test_m_project.py"])
51job-autotest-framework
/51job_autotest_framework-0.3.1-py3-none-any.whl/rolling_king/jason/requests/test_m_project.py
test_m_project.py
#!/usr/bin/python3 # -*- coding: UTF-8 -*- from src.rolling_king.jason.requests.http_sender_module import HttpSender import json import pytest class TestHttpPytest(object): def test_baidu(self): http_sender_obj = HttpSender('host') HttpSender.headers = {"header": "This is a customerized header"} # 下面一行用类名HttpSender调用方法,则self第一个参数需要传入相应对象。 HttpSender.send_get_request(http_sender_obj, 'http://10.72.99.200:8080/query/interfaceListByModule.do?moduleName=customer') print("结果:", http_sender_obj.get_response.text) def test_baidu_with_set_header(self): http_sender_obj = HttpSender('host') http_sender_obj.set_headers({"header":"This is a customerized header"}) # 下面一行用类HttpSender的对象http_sender_obj来调用方法,则self第一个参数不传。 http_sender_obj.send_get_request('http://10.72.99.200:8080/query/interfaceListByModule.do?moduleName=customer') print("结果:", http_sender_obj.get_response.text) print("headers:", http_sender_obj.get_response.headers) def test_get(self): http_sender_obj = HttpSender("http://10.72.99.200:8080/") input_params = {"moduleName": "customer"} # 下面一行用类HttpSender的对象http_sender_obj来调用方法,则self第一个参数不传。 http_sender_obj.send_get_request_by_suburi("query/interfaceListByModule.do", input_params) print("Text:", http_sender_obj.get_response.text) str_val = str(http_sender_obj.get_response.content) print("Content String:", str_val) left_index = str_val.index("[") right_index = str_val.index("]") content = str_val[left_index+1 : right_index] list_str = content.split(",") for curr_str in list_str: print("current value = %s" % curr_str[1:-1]) def test_send_post_request(self): http_sender_obj = HttpSender("http://10.72.99.200:8080/") http_sender_obj.set_headers({"header":"This is a New customerized header for post request"}) http_sender_obj.send_post_request("https://api.github.com/some/endpoint", json.dumps({'some': 'data'})) print("send_post_request response: %s" % http_sender_obj.post_response.text) http_sender_obj.send_post_request("https://api.github.com/some/endpoint", json.dumps({'some': 'data'})) print("Post Headers = {0}".format(http_sender_obj.post_response.headers)) def test_send_json_post_request(self): http_sender_obj = HttpSender("http://10.72.99.200:8080/") http_sender_obj.send_json_post_request("https://api.github.com/some/endpoint", {'some': 'data'}) print("send_json_post_request response: %s" % http_sender_obj.post_response.text) def test_send_json_post_request_with_headers_cookies(self): http_sender_obj = HttpSender("http://10.72.99.200:8080/") headers = {'content-type': 'application/json', 'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:22.0) Gecko/20100101 Firefox/22.0'} cookies = {'key': 'value'} http_sender_obj.send_json_post_request_with_headers_cookies("https://api.github.com/some/endpoint", {'some': 'data'}, headers, cookies) print("send_json_post_request_with_headers_cookies response: %s" % http_sender_obj.post_response.text) print("字典类型,头信息=", http_sender_obj.post_response.headers) print("发送到服务器的头信息=", http_sender_obj.post_response.request.headers) print("返回cookie=", http_sender_obj.post_response.cookies) print("重定向信息=", http_sender_obj.post_response.history) if __name__ == "__main__": pytest.main(["-s", "test_http.py"]) # 上面为pytest的调用和测试,下面为直接测试。 # result = requests.get("http://10.72.99.200:8080/query/interfaceListByModule.do?moduleName=customer") # print("结果:", result) # print("Status:", result.status_code) # print("Content:", result.content) # strVal = str(result.content) # print("Content String:", strVal) # leftIndex = strVal.index("[") # rightIndex = strVal.index("]") # content = strVal[leftIndex+1 : rightIndex] # listStr = content.split(",") # for str in listStr: # print("current value = %s" % str[1:-1]) # sender = HttpSender() # sender.send_get_request("http://10.72.99.200:8080/query/interfaceListByModule.do?moduleName=customer") # print(sender.get_response) # strVal = str(sender.get_response.content) # senderNew = HttpSender("http://10.72.99.200:8080/") # input_params = {"moduleName": "customer"} # senderNew.send_get_request_by_suburi("query/interfaceListByModule.do", input_params) # print("Text:", senderNew.get_response.text) # strVal = str(senderNew.get_response.content) # print("Content String:", strVal) # leftIndex = strVal.index("[") # rightIndex = strVal.index("]") # content = strVal[leftIndex+1 : rightIndex] # listStr = content.split(",") # for str in listStr: # print("current value = %s" % str[1:-1]) # senderNew.send_post_request("https://api.github.com/some/endpoint", json.dumps({'some': 'data'})) # print("send_post_request response: %s" % senderNew.post_response.text) # senderNew.send_json_post_request("https://api.github.com/some/endpoint", {'some': 'data'}) # print("send_json_post_request response: %s" % senderNew.post_response.text) # headers = {'content-type': 'application/json', # 'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:22.0) Gecko/20100101 Firefox/22.0'} # cookies = {'key': 'value'} # senderNew.send_json_post_request_with_headers_cookies("https://api.github.com/some/endpoint", {'some': 'data'}, headers, cookies) # print("send_json_post_request_with_headers_cookies response: %s" % senderNew.post_response.text) # r.headers #返回字典类型,头信息 # r.requests.headers #返回发送到服务器的头信息 # r.cookies #返回cookie # r.history #返回重定向信息,当然可以在请求是加上allow_redirects = false 阻止重定向 # print("字典类型,头信息=", senderNew.post_response.headers) # print("发送到服务器的头信息=", senderNew.post_response.request.headers) # print("返回cookie=", senderNew.post_response.cookies) # print("重定向信息=", senderNew.post_response.history)
51job-autotest-framework
/51job_autotest_framework-0.3.1-py3-none-any.whl/rolling_king/jason/requests/test_http.py
test_http.py
#!/usr/bin/python # -*- coding: UTF-8 -*- from src.rolling_king.jason import func1 from src.rolling_king.jason import func2 func1() func2()
51job-autotest-framework
/51job_autotest_framework-0.3.1-py3-none-any.whl/rolling_king/jason/pypac/test.py
test.py
#!/usr/bin/python # -*- coding: UTF-8 -*- def func2(): print("I'm in func2")
51job-autotest-framework
/51job_autotest_framework-0.3.1-py3-none-any.whl/rolling_king/jason/pypac/pyfile2.py
pyfile2.py
#!/usr/bin/python # -*- coding: UTF-8 -*- def func1(): print("I'm in func1")
51job-autotest-framework
/51job_autotest_framework-0.3.1-py3-none-any.whl/rolling_king/jason/pypac/pyfile1.py
pyfile1.py
# !/usr/bin/python # -*- coding: UTF-8 -*- if __name__ == '__main__': print('作为主程序运行') else: print("__init__.py的__name__变量=", __name__) print('package \'pypac\' 初始化')
51job-autotest-framework
/51job_autotest_framework-0.3.1-py3-none-any.whl/rolling_king/jason/pypac/__init__.py
__init__.py
#!/usr/bin/python3 # -*- coding: UTF-8 -*- import logging from rolling_king.autotest.requests.http_sender_module import HttpSender logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s') logger = logging.getLogger("gitlab_utils") class GitLab(object): __ACCESS_SEG_1: str = "glpat" __ACCESS_SEG_2: str = "Y4AGLX1aWBkvvsyjqEuv" __access_token: str = None __host_url: str = None __http_sender: HttpSender = None @classmethod def init(cls, gitlab_host_url: str, personal_access_token: str = None): if personal_access_token is None: cls.__access_token = cls.__ACCESS_SEG_1 + "-" + cls.__ACCESS_SEG_2 else: cls.__access_token = personal_access_token if gitlab_host_url is not None and len(gitlab_host_url) > 0: cls.__host_url = gitlab_host_url cls.__http_sender = HttpSender(hostname=cls.__host_url, headers={"PRIVATE-TOKEN": cls.__access_token}) else: logger.error("Please provide gitlab_host_url") @classmethod def get_token(cls): logger.info(f"Personal Access Token = {cls.__access_token}") @classmethod def get_host_url(cls): logger.info(f"GitLab Host URL = {cls.__host_url}") @classmethod def get_all_projects(cls) -> dict: cls.__http_sender.send_get_request_by_suburi(sub_uri="/api/v4/projects", input_params={ "private_token": cls.__access_token }) # try: json_resp = cls.__http_sender.get_response.json() if len(json_resp) > 0: logger.info(f"Total {len(json_resp)} projects") for curr in json_resp: logger.info(f"id = {curr['id']}, name = {curr['name']}, default_branch = {curr['default_branch']}") return json_resp else: return {} # except e: # logger.error("Exception happened...{e.args}") @classmethod def get_specific_project(cls, project_name: str) -> dict | None: # "private_token": cls.__access_token, # 若header中没有PRIVATE-TOKEN则需要参数里写上。 cls.__http_sender.send_get_request_by_suburi("/api/v4/projects", input_params={ "search": project_name }) # cls.__http_sender.send_get_request(full_get_url="https://gitdev.51job.com/api/v4/projects?search=maven-jave-project") json_resp = cls.__http_sender.get_response.json() if json_resp is not None and len(json_resp) == 1: logger.info(f"[成功]: 响应为{json_resp}") return json_resp[0] else: return {} @classmethod def get_project_branches(cls, project_id: str = None, project_name: str = None) -> list[dict] | None: if project_id is None or project_id == "": project_id = cls.get_specific_project(project_name)['id'] cls.__http_sender.send_get_request_by_suburi( # "private_token": cls.__access_token, # 若header中没有PRIVATE-TOKEN则需要参数里写上。 sub_uri=f"/api/v4/projects/{project_id}/repository/branches", input_params={ # "private_token": cls.__access_token } ) json_resp = cls.__http_sender.get_response.json() logger.info(json_resp) return json_resp if __name__ == '__main__': GitLab.init(gitlab_host_url="https://gitdev.51job.com") GitLab.get_token() GitLab.get_host_url() # GitLab.get_all_projects() # GitLab.get_specific_project(project_name="maven-jave-project") GitLab.get_project_branches(project_name="maven-jave-project")
51job-autotest-framework
/51job_autotest_framework-0.3.1-py3-none-any.whl/rolling_king/jason/gitlab/gitlab_utils.py
gitlab_utils.py
#!/usr/bin/python3 # -*- coding: utf-8 -*- # @Time : 2022/3/29 1:43 PM # @Author : zhengyu.0985 # @FileName: webdriver_common.py # @Software: PyCharm import logging import time from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.chrome.service import Service from selenium.webdriver.common.action_chains import ActionChains from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.support.wait import WebDriverWait from selenium.webdriver.remote.webelement import WebElement from selenium.webdriver.common.keys import Keys from typing import List logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s') logger = logging.getLogger("my_driver") class WebDriverCommon(object): driver = None action = None @classmethod def _browser_options(cls, browser_type='Chrome'): if browser_type == 'Firefox': options = webdriver.FirefoxOptions() elif browser_type == 'IE': options = webdriver.IeOptions() else: options = webdriver.ChromeOptions() # 像Options中添加实验选项。 options.add_experimental_option(name="excludeSwitches", value=["enable-automation"]) options.add_argument("--headless") return options @classmethod def init_driver(cls, driver_type='Chrome', executable_path=None): if cls.driver is None: if executable_path is None: if driver_type == 'Firefox': cls.driver = webdriver.Firefox(options=cls._browser_options(browser_type=driver_type)) elif driver_type == 'IE': cls.driver = webdriver.Ie(options=cls._browser_options(browser_type=driver_type)) else: cls.driver = webdriver.Chrome(options=cls._browser_options()) else: service_obj = Service(executable_path=executable_path) # Chrome类的初始化,executable_path已不建议使用,所以使用Service对象。 if driver_type == 'Firefox': cls.driver = webdriver.Firefox(service=service_obj, options=cls._browser_options(browser_type=driver_type)) elif driver_type == 'IE': cls.driver = webdriver.Ie(service=service_obj, options=cls._browser_options(browser_type=driver_type)) else: cls.driver = webdriver.Chrome(service=service_obj, options=cls._browser_options()) logger.info('The driver object of WebDriverCommon class was successfully initialized.') else: logger.warning('The driver object of WebDriverCommon class has been already initialized.') @classmethod def navigate(cls, url): cls.driver.get(url) @classmethod def refresh(cls): cls.driver.refresh() @classmethod def max_window(cls): cls.driver.maximize_window() @classmethod def min_window(cls): cls.driver.minimize_window() @classmethod def set_action(cls): if cls.driver is None: logger.error("Driver is None, so cannot initialize ActionChains.") else: cls.action = ActionChains(cls.driver) logger.info("Initialize ActionChains successfully by Driver.") @classmethod def is_ele_exist(cls, by_locator: str, locator_value: str) -> bool: # e.g: element = driver.find_element(By.ID, 'foo') try: web_ele = cls.driver.find_element(by_locator, locator_value) if web_ele is None: logger.warning("[失败]:{}={}, 未能定位到WebElement".format(by_locator, locator_value)) return False else: logger.info("[成功]:{}={}, 成功定位到WebElement".format(by_locator, locator_value)) return True except Exception as e: logger.warning("[异常]:{}={}, 未能定位到WebElement".format(by_locator, locator_value)) logger.warning(e.args) return False finally: logger.info("is_ele_exist class func has been executed.") @classmethod def switch_to_new_window(cls): handles_list = cls.driver.window_handles() for handle in handles_list: if handle == cls.driver.current_window_handle: pass else: cls.driver.switch_to.window(handle) @classmethod def wait_implicitly(cls, time_in_seconds): cls.driver.implicitly_wait(time_to_wait=time_in_seconds) @classmethod def wait_for_load(cls, tuple_locator: tuple, presence_or_visibility='visibility', time_out=10, frequency=0.5) -> WebElement: try: web_driver_wait = WebDriverWait(cls.driver, timeout=time_out, poll_frequency=frequency) if presence_or_visibility == 'visibility': result = web_driver_wait.until(method=EC.visibility_of_element_located(tuple_locator), message="超时未找到") elif presence_or_visibility == 'presence': result = web_driver_wait.until(method=EC.presence_of_element_located(tuple_locator), message="超时未找到") else: logger.warning("presence_or_visibility only supports visibility or presence.") result = None if isinstance(result, WebElement): logger.info("Locator={}, 元素已成功加载。".format(tuple_locator)) else: logger.warning("未等到元素加载。") logger.info("result={}".format(result)) return result except Exception as e: logger.error(e.args) logger.error(e) finally: logger.info("wait_for_load method has been executed.") @classmethod def find_element(cls, by_locator: str, locator_value: str, curr_web_ele=None) -> WebElement: try: if curr_web_ele is None: web_ele = cls.driver.find_element(by_locator, locator_value) logger.info("[成功]:{}={}, 成功定位到WebElement".format(by_locator, locator_value)) elif isinstance(curr_web_ele, WebElement): web_ele = curr_web_ele.find_element(by_locator, locator_value) logger.info("[成功]:基于当前Element[{}], 通过 {}={}, 成功定位到WebElement".format(curr_web_ele, by_locator, locator_value)) else: logger.info("所传参数curr_web_ele类型错误,必须是WebElement类型。") web_ele = None except Exception as e: logger.error(e.args) web_ele = None finally: logger.info("find_element method has been executed.") return web_ele @classmethod def find_element_list(cls, by_locator: str, locator_value: str, curr_web_ele=None) -> List[WebElement]: try: if curr_web_ele is None: web_ele_list = cls.driver.find_elements(by_locator, locator_value) logger.info("[成功]:{}={}, 成功获取到WebElement List。".format(by_locator, locator_value)) elif isinstance(curr_web_ele, WebElement): web_ele_list = curr_web_ele.find_elements(by_locator, locator_value) logger.info("[成功]:基于当前Element[{}], 通过 {}={}, 成功获取到WebElement List。".format(curr_web_ele, by_locator, locator_value)) else: logger.info("所传参数curr_web_ele类型错误,必须是WebElement类型。") web_ele_list = [] except Exception as e: logger.error(e.args) web_ele_list = [] finally: logger.info("find_element_list method has been executed.") return web_ele_list @classmethod def switch_to_iframe(cls, frame_id_name_ele): # driver.switch_to.frame('frame_name') # driver.switch_to.frame(1) # driver.switch_to.frame(driver.find_elements(By.TAG_NAME, "iframe")[0]) try: if isinstance(frame_id_name_ele, int): cls.driver.switch_to.frame(frame_id_name_ele) logger.info("通过Integer Index={}, 进入iFrame。".format(frame_id_name_ele)) elif isinstance(frame_id_name_ele, str): cls.driver.switch_to.frame(frame_id_name_ele) logger.info("通过iFrame Name={}, 进入iFrame。".format(frame_id_name_ele)) elif isinstance(frame_id_name_ele, WebElement): cls.driver.switch_to.frame(frame_id_name_ele) logger.info("通过iFrame WebElement={}, 进入iFrame。".format(frame_id_name_ele)) else: logger.warning("frame_id_name_ele参数,仅支持int、str、WebElement类型。") except Exception as e: logger.error(e.args) finally: logger.info("switch_to_iFrame method has been executed.") @classmethod def switch_to_default_content(cls): cls.driver.switch_to.default_content() @classmethod def right_click(cls, on_web_ele, int_down_times): if cls.action is None: logger.error("尚未未初始化ActionChains对象action.") else: cls.action.context_click(on_element=on_web_ele).perform() for i in range(int_down_times): # 当前点击向下键无反应。 # cls.action.send_keys(Keys.ARROW_DOWN) cls.action.key_down(Keys.ARROW_DOWN) cls.wait_implicitly(1) cls.action.key_up(Keys.ARROW_DOWN) logger.info("第{}次点击向下键。".format(i)) cls.action.send_keys(Keys.ENTER) logger.info("回车选中。") @classmethod def move_to_ele(cls, web_ele, x_off_set=None, y_off_set=None): if web_ele is None: logger.error("给定WebElement is None.") return None elif x_off_set is None or y_off_set is None: return cls.action.move_to_element(web_ele) else: return cls.action.move_to_element_with_offset(web_ele, xoffset=x_off_set, yoffset=y_off_set) @classmethod def close_driver(cls): cls.driver.close() logger.info("成功关闭WebDriver") if __name__ == '__main__': WebDriverCommon.init_driver(executable_path='./chromedriver.exe') WebDriverCommon.navigate("https://www.baidu.com") WebDriverCommon.refresh() WebDriverCommon.max_window() logger.info(WebDriverCommon.is_ele_exist(By.ID, "s-top-left")) ele = WebDriverCommon.wait_for_load((By.XPATH, "//div[@id='s-top-left']/a[1]")) logger.info(type(ele)) logger.info(ele) WebDriverCommon.set_action() # WebDriverCommon.right_click(ele, 3) # 该功能有Bug WebDriverCommon.wait_implicitly(3) # 该功能不生效 search_input = (By.ID, 'kw') search_button = (By.ID, 'su') WebDriverCommon.find_element(*search_input).send_keys("郑宇") WebDriverCommon.find_element(*search_button).click() time.sleep(3) WebDriverCommon.close_driver()
51job-autotest-framework
/51job_autotest_framework-0.3.1-py3-none-any.whl/rolling_king/jason/webdriver/webdriver_common.py
webdriver_common.py
#!/usr/bin/python3 # -*- coding: utf-8 -*- # @Time : 2022/3/29 1:42 PM # @Author : zhengyu.0985 # @FileName: __init__.py.py # @Software: PyCharm
51job-autotest-framework
/51job_autotest_framework-0.3.1-py3-none-any.whl/rolling_king/jason/webdriver/__init__.py
__init__.py
#!/usr/bin/python3 # -*- coding: UTF-8 -*- # Python SMTP发送邮件 import smtplib from email.mime.text import MIMEText from email.header import Header mail_host = "mail.meituan.com" mail_user = "zhengyu06@meituan.com" #用户名 mail_pass = "Jason1qaz!QAZ" #口令 sender = "zhengyu06@meituan.com" receivers = ["386773780@qq.com"] # 接收邮件,可设置为你的QQ邮箱或者其他邮箱 mail_msg = """ <p>Python 邮件发送测试...</p> <p><a href="http://www.runoob.com">这是一个链接</a></p> """ message = MIMEText(mail_msg, 'html', 'utf-8') message['From'] = Header("菜鸟教程", 'utf-8') message['To'] = Header("测试", 'utf-8') subject = 'Python SMTP 邮件测试' message['Subject'] = Header(subject, 'utf-8') try: print("连接邮件服务器...") smtpObj = smtplib.SMTP(mail_host, 25) print("连接邮件服务器成功。") # smtpObj = smtplib.SMTP() # smtpObj.connect(mail_host, 25) smtpObj.login(mail_user, mail_pass) smtpObj.sendmail(sender, receivers, message.as_string()) print("邮件发送成功") except smtplib.SMTPException: print("Error: 无法发送邮件")
51job-autotest-framework
/51job_autotest_framework-0.3.1-py3-none-any.whl/rolling_king/jason/python/MailTest.py
MailTest.py
# -*- coding: UTF-8 -*- import math # 自定义函数 # def functionname( parameters ): # "函数_文档字符串" # function_suite # return [expression] # 可更改(mutable)与不可更改(immutable)对象 # 在 python 中,strings, tuples, 和 numbers 是不可更改的对象,而 list,dict 等则是可以修改的对象。 # 不可变类型:变量赋值 a=5 后再赋值 a=10,这里实际是新生成一个 int 值对象 10,再让 a 指向它,而 5 被丢弃,不是改变a的值,相当于新生成了a。 # 可变类型:变量赋值 la=[1,2,3,4] 后再赋值 la[2]=5 则是将 list la 的第三个元素值更改,本身la没有动,只是其内部的一部分值被修改了。 # # python 函数的参数传递: # 不可变类型:类似 c++ 的值传递,如 整数、字符串、元组。如fun(a),传递的只是a的值,没有影响a对象本身。比如在 fun(a)内部修改 a 的值,只是修改另一个复制的对象,不会影响 a 本身。 # 可变类型:类似 c++ 的引用传递,如 列表,字典。如 fun(la),则是将 la 真正的传过去,修改后fun外部的la也会受影响 # 不可变类型 是 值传递;可变类型 是 引用传递。 def ChangeInt(a): a = 10 b = 2 ChangeInt(b) print("b = ", b) # 结果是 2,因为不可变类型 是 值传递。 # 可写函数说明 def changeme(mylist): """修改传入的列表""" mylist.append([1, 2, 3, 4]) print("函数内取值: ", mylist) return # 调用changeme函数 mylist = [10, 20, 30] changeme(mylist) print("函数外取值: ", mylist) print(len(mylist)) # 参数种类 # 正式参数类型:必选参数、默认参数、可变参数、命名关键字参数、关键字参数 共计5种。(方法定义时,也按此顺序!) # 必备参数须以正确的顺序传入函数。调用时的数量必须和声明时的一样。 # changeme() # 将会报错,缺少必要参数: changeme() missing 1 required positional argument: 'mylist' # 使用关键字参数允许函数调用时参数的顺序与声明时不一致,因为 Python 解释器能够用参数名匹配参数值。 def printinfo(name, age): "打印任何传入的字符串" print("Name: ", name) print("Age ", age) return # 调用printinfo函数 printinfo(age=50, name="miki") # 默认参数的值如果没有传入,则被认为是默认值。 def printinfo1(name, age=0): """打印任何传入的字符串""" print("Name: ", name) print("Age ", age) return printinfo1("Jason") printinfo1(name="Jason") printinfo1(age=10, name="Jason") # 加了星号(*)的变量名会存放所有未命名的变量参数。不定长参数, 声明时不会命名。 def printinfo(arg1, *vartuple): "打印任何传入的参数" print("输出: ", arg1) for var in vartuple: print(var) printinfo(10) printinfo(70, 60, 50) nums = [1,2,3] printinfo(nums) # 传入一个list,相当于传了一个参数,对应方法的arg1;没有传入后面的可变参数 printinfo(*nums) # 在入参list前添加*,变成可变参数,就是list的各个元素,相当于传入了三个参数。 # *args 和 **kwargs 主要用于函数定义。 # 你可以将不定数量的参数传递给一个函数。不定的意思是:预先并不知道, 函数使用者会传递多少个参数给你, 所以在这个场景下使用这两个关键字。其实并不是必须写成 *args 和 **kwargs。 *(星号) 才是必须的. 你也可以写成 *ar 和 **k 。而写成 *args 和**kwargs 只是一个通俗的命名约定。 # python函数传递参数的方式有两种:位置参数(positional argument)、关键词参数(keyword argument) # # *args 与 **kwargs 的区别,两者都是 python 中的可变参数: # # *args 表示任何多个无名参数(可变参数),它本质是一个 tuple # **kwargs 表示关键字参数,它本质上是一个 dict # # 如果同时使用 *args 和 **kwargs 时,必须 *args 参数列要在 **kwargs 之前。 def person(name, age, **kw): print('name:', name, 'age:', age, 'other:', kw) person("zy", 30, city='Beijing') extra = {'city': 'Beijing', 'job': 'Engineer'} person("smm", 28, **extra) # 必须通过**将dict转为关键字参数。 # 命名关键字参数 # 限制关键字参数的名字,就可以用命名关键字参数 # (1)在没有可变参数的情况下,命名关键字参数需要一个特殊分隔符*,*后面的参数被视为命名关键字参数 def person1(name, age, *, city, job): print(name, age, city, job) # (2)在存在可变参数的情况下,可变参数后面跟着的命名关键字参数就不再需要一个特殊分隔符*了。 def person2(name, age, *args, city, job): print(name, age, args, city, job) # 对于任意函数,都可以通过类似func(*args, **kw)的形式调用它,无论它的参数是如何定义的。 def f1(a, b, c=0, *args, **kw): print('a =', a, 'b =', b, 'c =', c, 'args =', args, 'kw =', kw) def f2(a, b, c=0, *, d, **kw): print('a =', a, 'b =', b, 'c =', c, 'd =', d, 'kw =', kw) args = (1, 2, 3, 4) kw = {'d': 99, 'x': '#'} f1(*args, **kw) # a = 1 b = 2 c = 3 args = (4,) kw = {'d': 99, 'x': '#'} args = (1, 2, 3) kw = {'d': 88, 'x': '#'} f2(*args, **kw) # a = 1 b = 2 c = 3 d = 88 kw = {'x': '#'} # 匿名函数:python 使用 lambda 来创建匿名函数。 # lambda [arg1 [,arg2,.....argn]]:expression # 可写函数说明 sum = lambda arg1, arg2: arg1 + arg2 # 调用sum函数 print("相加后的值为 : ", sum(10, 20)) print("相加后的值为 : ", sum(20, 20)) # 变量作用域:全局变量 和 局部变量 total = 0 # 这是一个全局变量 # 可写函数说明 def sum(arg1, arg2): # 返回2个参数的和." total = arg1 + arg2 # total在这里是局部变量, 是一个定义的新变量(局部变量且名为total) print("函数内是局部变量 : ", total) # 30 return total # 调用sum函数 sum(10, 20) print("函数外是全局变量 : ", total) # 0 total = sum(10, 20) print("函数外是全局变量 : ", total) # 30 # Python 模块 # Python 模块(Module),是一个 Python 文件,以 .py 结尾,包含了 Python 对象定义和Python语句。 # 请注意,每一个包目录下面都会有一个__init__.py的文件,这个文件是必须存在的,否则,Python就把这个目录当成普通目录,而不是一个包。 # __init__.py可以是空文件,也可以有Python代码,因为__init__.py本身就是一个模块,而它的模块名就是mycompany。 # 类似的,可以有多级目录,组成多级层次的包结构。比如如下的目录结构: # mycompany # ├─ web # │ ├─ __init__.py # │ ├─ utils.py # │ └─ www.py # ├─ __init__.py # ├─ abc.py # └─ utils.py # 模块的引入 # 模块定义好后,我们可以使用 import 语句来引入模块,语法如下: # import module1[, module2[,... moduleN]] # 当解释器遇到 import 语句,如果模块在当前的搜索路径就会被导入。 # 搜索路径是一个解释器会先进行搜索的所有目录的列表。 # 需要把import命令放在脚本的顶端. # 引入模块后,通过 模块名.函数名 方式调用模块中的函数。 # from…import 语句 # Python 的 from 语句让你从模块中导入一个指定的部分到当前命名空间中。语法如下: # from modname import name1[, name2[, ... nameN]] # from modname import * # 自己创建模块时要注意命名,不能和Python自带的模块名称冲突。 # 例如,系统自带了sys模块,自己的模块就不可命名为sys.py,否则将无法导入系统自带的sys模块。 # sys模块有一个argv变量,用list存储了命令行的所有参数。argv至少有一个元素,因为第一个参数永远是该.py文件的名称。 # 在命令行运行hello模块文件时,Python解释器把一个特殊变量__name__置为__main__, # 而如果在其他地方导入该hello模块时,if判断将失效。 # $ python hello.py Michael 的 参数Michael可以被sys.argv这个list获取到。 # 搜索路径 # 当你导入一个模块,Python 解析器对模块位置的搜索顺序是: # 1、当前目录 # 2、如果不在当前目录,Python 则搜索在 shell 变量 PYTHONPATH 下的每个目录。 # 3、如果都找不到,Python会察看默认路径。UNIX下,默认路径一般为/usr/local/lib/python/。 # 模块搜索路径存储在 system 模块的 sys.path 变量中。变量里包含当前目录,PYTHONPATH和由安装过程决定的默认目录。 # PYTHONPATH 变量 # 作为环境变量,PYTHONPATH 由装在一个列表里的许多目录组成。PYTHONPATH 的语法和 shell 变量 PATH 的一样。 # 命名空间和作用域 # 变量是拥有匹配对象的名字(标识符)。命名空间是一个包含了变量名称们(键)和它们各自相应的对象们(值)的字典。 # 一个 Python 表达式可以访问局部命名空间和全局命名空间里的变量。如果一个局部变量和一个全局变量重名,则局部变量会覆盖全局变量。 # 每个函数都有自己的命名空间。类的方法的作用域规则和通常函数的一样。 # Python 会智能地猜测一个变量是局部的还是全局的,它假设任何在函数内赋值的变量都是局部的。 # 因此,如果要给函数内的全局变量赋值,必须使用 global 语句。 # global VarName 的表达式会告诉 Python, VarName 是一个全局变量,这样 Python 就不会在局部命名空间里寻找这个变量了。 Money = 2000 def AddMoney(): # 想改正代码就取消以下注释: global Money Money = Money + 1 print(Money) AddMoney() print(Money) # dir()函数 # dir() 函数一个排好序的字符串列表,内容是一个模块里定义过的名字。 # 返回的列表容纳了在一个模块里定义的所有模块,变量和函数。获得一个对象的所有属性和方法。 content = dir(math) print(content) # 特殊字符串变量__name__指向模块的名字: print(math.__name__) # __file__指向该模块的导入文件名: print(math.__file__) # globals() 和 locals() 函数 # 根据调用地方的不同,globals() 和 locals() 函数可被用来返回全局和局部命名空间里的名字。 # 如果在函数内部调用 locals(),返回的是所有能在该函数里访问的命名。 # 如果在函数内部调用 globals(),返回的是所有在该函数里能访问的全局名字。 # 两个函数的返回类型都是字典。所以名字们能用 keys() 函数摘取。 def func(): a = 1 b = 2 print(globals()) print(globals().keys()) print(locals()) print(locals().keys()) func() # reload() 函数 # 当一个模块被导入到一个脚本,模块顶层部分的代码只会被执行一次。该函数会重新导入之前导入过的模块。 # 语法:reload(module_name), 入参不是字符串,就是module_name,譬如:reload(math) # Python中的包 # 包是一个分层次的文件目录结构,它定义了一个由模块及子包,和子包下的子包等组成的 Python 的应用环境。 # 简单来说,包就是文件夹,但该文件夹下必须存在 __init__.py 文件, 该文件的内容可以为空。__init__.py 用于标识当前文件夹是一个包。 # Python 文件I/O # 读取键盘输入 # raw_input([prompt]) 函数从标准输入读取一个行,并返回一个字符串(去掉结尾的换行符): # 但是 input 可以接收一个Python表达式作为输入,并将运算结果返回 # 打开和关闭文件 # open 函数: 你必须先用Python内置的open()函数打开一个文件,创建一个file对象,相关的方法才可以调用它进行读写 # file object = open(file_name [, access_mode][, buffering]) fileObj = open("/Users/jasonzheng/Desktop/CAT告警.txt", mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None) print("文件名: ", fileObj.name) print("是否已关闭 : ", fileObj.closed) print("访问模式 : ", fileObj.mode) # print("末尾是否强制加空格 : ", fileObj.softspace) firstLine = fileObj.readline() print(firstLine) # tell()方法告诉你文件内的当前位置, 换句话说,下一次的读写会发生在文件开头这么多字节之后。 # seek(offset [,from])方法改变当前文件的位置。 # 查找当前位置 position = fileObj.tell() print("当前文件位置 : ", position) print(fileObj.seek(35, 0)) print(fileObj.read(5)) # 重命名和删除文件 # Python的os模块提供了帮你执行文件处理操作的方法 # import os # os.renames("oldfilename.txt", "newfilename.txt") # os.remove("existfilename.txt") # os.mkdir("newdirectory") # os.chdir("newdirname") # print(os.getcwd()) # os.rmdir('newdirname') if fileObj.closed : print("File has been already closed.") else: fileObj.close() print("File is closed now.") print(fileObj.closed) # Python 异常处理 # 什么是异常? # 异常即是一个事件,该事件会在程序执行过程中发生,影响了程序的正常执行。 # 一般情况下,在Python无法正常处理程序时就会发生一个异常。 # 异常是Python对象,表示一个错误。 # 当Python脚本发生异常时我们需要捕获处理它,否则程序会终止执行。 # 以下为简单的try....except...else的语法: # try: # <语句> #运行别的代码 # except <名字>: # <语句> #如果在try部份引发了'name'异常 # except <名字>,<数据>: # <语句> #如果引发了'name'异常,获得附加的数据 # else: # <语句> #如果没有异常发生 try: fh = open("testfile", "w") fh.write("这是一个测试文件,用于测试异常!!") except IOError: print("Error: 没有找到文件或读取文件失败") else: print("内容写入文件成功") fh.close() def exp_func(): print("raise IOError exception") raise IOError("my io error") try: print("try body") exp_func() except IOError as err: print("get IOError exception") print("OS error: {0}".format(err)) # raise #抛出 else: print("else block") finally: print("finally block")
51job-autotest-framework
/51job_autotest_framework-0.3.1-py3-none-any.whl/rolling_king/jason/python/PythonTest.py
PythonTest.py
#!/usr/bin/python # -*- coding: UTF-8 -*- import math import cmath from collections.abc import Iterable from collections.abc import Iterator import argparse if True: print("真") else: print("假") strVar = input("Please input a number:") print("strVar is:"+strVar) print(type(strVar)) num = int(strVar) print(type(num)) print(num) # chr(参数是一个ASCII码),就是将ASCII转为char print("ASCII码转字符:"+chr(49)) print("字符转ASCII码:", ord("A")) print(len('ABC')) # 3 strEn = 'ABC'.encode('ascii') print(strEn) # string英文转ascii编码的byte数组 print(len(strEn)) # 3 print(len('中文')) # 2 strCn = '中文'.encode('utf-8') print(strCn) # string中文转utf-8编码的byte数组 print(len(strCn)) # 6 print("bytes转str:", b'ABC'.decode('ascii')) print("bytes转str:", b'\xe4\xb8\xad\xe6\x96\x87'.decode('utf-8')) # 当Python解释器读取源代码时,为了让它按UTF-8编码读取,我们通常在文件开头写上这两行: # !/usr/bin/env python3 # 告诉Linux/OS X系统,这是一个Python可执行程序,Windows系统会忽略这个注释; # -*- coding: utf-8 -*- # 告诉Python解释器,按照UTF-8编码读取源代码,否则,你在源代码中写的中文输出可能会有乱码。 counter = 100 # 赋值整型变量 miles = 1000.0 # 浮点型 name = "John" # 字符串 print(counter, miles, name) # ,代表不换行 counter1, miles1, name1 = 100, 1000.0, "Jason" # 为多个对象指定多个变量 print(counter1, miles1, name1) # 标准数据类型:Numbers(数字)、String(字符串)、List(列表)、Tuple(元组)、Dictionary(字典) var1 = 10 print(var1) # ----- del用于删除对象的引用 del var1 # print(var1) #del之后此行会报错:NameError: name 'var1' is not defined var1 = 20 print(var1) s = "abcdef" print(s[0:2]) # 包括起始,但不包括结尾。与java的substr函数一致。 print(s[-6:-4]) # 结果均是ab # 加号(+)是字符串连接运算符,星号(*)是重复操作。 strVal = "Hello World" print(strVal) # 输出完整字符串 print(strVal[0]) # 输出字符串中的第一个字符 print(strVal[2:5]) # 输出字符串中第三个至第六个之间的字符串 print(strVal[2:]) # 输出从第三个字符开始的字符串 print(strVal * 2) # 输出字符串两次 print(strVal + "TEST") # 输出连接的字符串 # 列表 list = ['runoob', 786, 2.23, 'john', 70.2] tinylist = [123, 'john'] print(list) # 输出完整列表 print(list[0]) # 输出列表的第一个元素 print(list[1:3]) # 输出第二个至第三个元素 print(list[2:]) # 输出从第三个开始至列表末尾的所有元素 print(tinylist * 2) # 输出列表两次 print(list + tinylist) # 打印组合的列表 list.append('Google') ## 使用 append() 添加元素 list.append('Runoob') print(list) del(list[-2]) print(list) # 元祖(元组不能二次赋值,相当于只读列表): Tuple是有序但元素指向不可变。 tuple = ('runoob', 786, 2.23, 'john', 70.2) tinytuple = (123, 'john') print(tuple) # 输出完整元组 print(tuple[0]) # 输出元组的第一个元素 print(tuple[1:3]) # 输出第二个至第四个(不包含)的元素 print(tuple[2:]) # 输出从第三个开始至列表末尾的所有元素 print(tinytuple * 2) # 输出元组两次 print(tuple + tinytuple) # 打印组合的元组 #tuple[2] = 1000 # 元组中是非法应用,此行会报错:TypeError: 'tuple' object does not support item assignment list[2] = 1000 # 列表中是合法应用 tup1 = () # 创建空元组 tup1 = (50,) # 元组中只包含一个元素时,需要在元素后面添加逗号 # 元组中的元素值是不允许修改的,但我们可以对元组进行连接组合. tup1 = (12, 34.56) tup2 = ('abc', 'xyz') tup3 = tup1 + tup2 print("tup3=", tup3) # 元组中的元素值是不允许删除的,但我们可以使用del语句来删除整个元组 del tup3 # print("After deleting tup3:", tup3) # NameError: name 'tup3' is not defined # 字典(列表是有序的对象集合,字典是无序的对象集合) dict = {} dict['one'] = "This is one" dict[2] = "This is two" tinydict = {'name': 'runoob', 'code':6734, 'dept': 'sales'} print(dict['one']) # 输出键为'one' 的值 print(dict[2]) # 输出键为 2 的值 print(tinydict) # 输出完整的字典 print(tinydict.keys()) # 输出所有键 print(tinydict.values()) # 输出所有值 dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'} dict['Age'] = 8 # 更新 dict['School'] = "RUNOOB" # 添加 del dict['Name'] # 删除键是'Name'的条目 dict.clear() # 清空字典所有条目 del dict # 删除字典 # 键必须不可变,所以可以用数字,字符串或元组充当,所以用列表就不行 # dict = {['Name']: 'Zara', 'Age': 7} # TypeError: unhashable type: 'list' # 集合Set(Set是无序的、元素唯一不可重复的对象集合) s = set([1, 2, 3]) print("Set集合:", s) s = set([1, 1, 2, 2, 3, 3]) # 重复元素在set中自动被过滤 print(s) s.add(5) print(s) s.remove(1) print(s) # Set可以看成数学意义上的无序和无重复元素的集合,因此,两个set可以做数学意义上的交集、并集等操作 s1 = set([2, 5, 6, 8]) print("交集:", s & s1) print("并集:", s | s1) # if 条件语句 num = 9 if num >= 0 and num <= 10: # 判断值是否在0~10之间 print('hello') # 输出结果: hello num = 10 if num < 0 or num > 10: # 判断值是否在小于0或大于10 print('hello') else: print('undefine') # 输出结果: undefine num = 8 # 判断值是否在0~5或者10~15之间 if (num >= 0 and num <= 5) or (10 <= num <= 15): print('hello') elif num < 0: print("负数") else: print('undefine') # 输出结果: undefine # while 循环 count = 0 while count < 9: print('The count is:', count) count = count + 1 print("Good bye!") # while..eles.. # 在 python 中,while … else 在循环条件为 false 时执行 else 语句块: count = 0 while count < 5: print(count, "is less than 5") count = count + 1 print("Count is ", count, " now.") # for 循环1 for letter in 'Python': # 第一个实例 print('当前字母 :', letter) fruits = ['banana', 'apple', 'mango'] for fruit in fruits: # 第二个实例 print('当前水果 :', fruit) print("Good bye!") # for 循环2:通过索引 fruits = ['banana', 'apple', 'mango'] for index in range(len(fruits)): print("Current is ", fruits[index]) for index in range(0, len(fruits)): print("Current is ", fruits[index]) print("Good Bye") # for..else.. 循环 (else 中的语句会在循环正常执行完的情况下执行, 也就意味着不是通过 break 跳出而中断的) fruits = ['banana', 'apple', 'mango'] for index in range(len(fruits)): if index == 3: break print("index=", index, "'s fruit is ", fruits[index]) else: print("Current index = ", index) # 凡是可作用于for循环的对象都是Iterable类型; print("是否可迭代:", isinstance('abc', Iterable)) # str是否可迭代 True print("是否可迭代:", isinstance([1,2,3], Iterable)) # list是否可迭代 True print("是否可迭代:", isinstance(123, Iterable)) # 整数是否可迭代 False for i, value in enumerate(['A', 'B', 'C']): print(i, value) # 0 A # 1 B # 2 C # 列表生成式 print("列表生成式") print([x * x for x in range(1, 11)]) print([x * x for x in range(1, 11) if x % 2 == 0]) # 跟在for后面的if是一个筛选条件,不能带else。 print([x if x % 2 == 0 else -x for x in range(1, 11)]) # 在for前面的部分是一个表达式,必须要算出一个值。 print([m + n for m in 'ABC' for n in 'XYZ']) # Python中,这种一边循环一边计算的机制,称为生成器:generator # 第一种方法很简单,只要把一个列表生成式的[]改成(),就创建了一个generator: g = (x * x for x in range(1, 11)) print(g) print("使用next函数打印generator", next(g)) for i in g: print("使用for循环打印generator:", i) # 第二种(生成器函数):一个函数定义中包含yield关键字,那么这个函数就不再是一个普通函数,而是一个generator: # 在每次调用next()的时候执行,遇到yield语句返回,再次执行时从上次返回的yield语句处继续执行。 # 定义一个generator,依次返回数字1,3,5: def odd(): print('step 1') yield 1 print('step 2') yield(3) print('step 3') yield(5) return "Done" gen_func = odd() # generator函数的“调用”实际返回一个generator对象: # print(next(gen_func)) # print("-------") # print(next(gen_func)) # print("-------") # print(next(gen_func)) # print("-------") # print(next(gen_func)) # 但是用for循环调用generator时,发现拿不到generator的return语句的返回值。 for n in gen_func: print(n) print("-------") print("for循环打印generator完成") # 如果想要拿到返回值,必须捕获StopIteration错误,返回值包含在StopIteration的value中: while True: try: x = next(gen_func) print("g: ", x) except StopIteration as e: print("Generator return value: ", e.value) break # 迭代器:可以被next()函数调用并不断返回下一个值的对象称为迭代器:Iterator。 print(isinstance((x for x in range(10)), Iterator)) # True, generator生成器是迭代器 print(isinstance([], Iterator)) # False # 生成器都是Iterator对象,但list、dict、str虽然是Iterable,却不是Iterator。 # 这是因为Python的Iterator对象表示的是一个数据流,把这个数据流看做是一个有序序列, # 但我们却不能提前知道序列的长度,只能不断通过next()函数实现按需计算下一个数据, # 所以Iterator的计算是惰性的,只有在需要返回下一个数据时它才会计算。 # Iterator甚至可以表示一个无限大的数据流 # 把list、dict、str等Iterable变成Iterator可以使用iter()函数: print(isinstance(iter([]), Iterator)) # True print(isinstance(iter("abc"), Iterator)) # True # pass语句:不做任何事情,一般用做占位语句 for letter in 'Python': if letter == 'h': pass print('这是 pass 块') print('当前字母 :', letter) print("Good bye!") # Python Number(数字) # 数据类型是不允许改变的,这就意味着如果改变 Number 数据类型的值,将重新分配内存空间。 var = 0 var1 = 1 var2 = 10 # 使用del语句删除一些 Number 对象引用 del var del var1, var2 # Python Number 类型转换 # int(x [,base ]) 将x转换为一个整数 # long(x [,base ]) 将x转换为一个长整数 # float(x ) 将x转换到一个浮点数 # complex(real [,imag ]) 创建一个复数 # str(x ) 将对象 x 转换为字符串 # repr(x ) 将对象 x 转换为表达式字符串 # eval(str ) 用来计算在字符串中的有效Python表达式,并返回一个对象 # tuple(s ) 将序列 s 转换为一个元组 # list(s ) 将序列 s 转换为一个列表 # chr(x ) 将一个整数转换为一个字符 # unichr(x ) 将一个整数转换为Unicode字符 # ord(x ) 将一个字符转换为它的整数值 # hex(x ) 将一个整数转换为一个十六进制字符串 # oct(x ) 将一个整数转换为一个八进制字符串 intVal = 0 print(type(intVal)) strVal = str(intVal) print(type(strVal)) print(hex(15)) # 数学运算 # Python 中数学运算常用的函数基本都在 math 模块、cmath 模块中。 # Python math 模块提供了许多对浮点数的数学运算函数。 # Python cmath 模块包含了一些用于复数运算的函数。 # cmath 模块的函数跟 math 模块函数基本一致,区别是 cmath 模块运算的是复数,math 模块运算的是数学运算。 # 要使用 math 或 cmath 函数必须先导入:import math、import cmath print(dir(math)) print(dir(cmath)) # 字符串 var1 = 'Hello World!' var2 = "Python Runoob" print("var1[0]: ", var1[0]) print("var2[1:5]: ", var2[1:5]) # 成员运算符 if ("ll" in "Hello"): print("Hello 包含 ll") else: print("错误") # 原始字符串 print("反转义") print(r'\n') # 反转义 # 字符串格式化使用与 C 中 sprintf 函数一样的语法 print("My name is %s and weight is %d kg!" % ('Zara', 21)) # Python 三引号允许一个字符串跨多行,字符串中可以包含换行符、制表符以及其他特殊字符。 # 三引号让程序员从引号和特殊字符串的泥潭里面解脱出来,当你需要一块HTML或者SQL时,这时当用三引号标记。 errHTML = ''' <HTML><HEAD><TITLE> Friends CGI Demo</TITLE></HEAD> <BODY><H3>ERROR</H3> <B>%s</B><P> <FORM><INPUT TYPE=button VALUE=Back ONCLICK="window.history.back()"></FORM> </BODY></HTML> ''' print(errHTML) # Unicode 字符串 # 定义一个 Unicode 字符串 uVar = u'Hello World !' print(uVar) # 如果你想加入一个特殊字符,可以使用 Python 的 Unicode-Escape 编码 uVar1 = u'Hello\u0020World !' print(uVar1) # Python 日期和时间 import time # 引入time模块 ticks = time.time() print("当前时间戳为:", ticks) # 当前时间戳为: 1603089755.566846 # 时间元祖:很多Python函数用一个元组装起来的9组数字处理时间,也就是struct_time元组。 localtime = time.localtime(time.time()) print("本地时间为:", localtime) # time.struct_time(tm_year=2020, tm_mon=10, tm_mday=19, tm_hour=14, tm_min=47, tm_sec=46, tm_wday=0, tm_yday=293, tm_isdst=0) print(time.localtime()) # 等同 asctime = time.asctime(localtime) print("asc本地时间为:", asctime) # Mon Oct 19 14:47:46 2020 # 使用 time 模块的 strftime 方法来格式化日期 # 格式化成2016-03-20 11:45:39形式 print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())) # 格式化成Sat Mar 28 22:24:24 2016形式 print(time.strftime("%a %b %d %H:%M:%S %Y", time.localtime())) # 将格式字符串转换为时间戳 a = "Sat Mar 28 22:24:24 2016" print(time.mktime(time.strptime(a, "%a %b %d %H:%M:%S %Y"))) # 处理年历和月历 import calendar cal = calendar.month(2020, 10) print("2020年10月的日历:\n", cal) # Time 模块: 内置函数,既有时间处理的,也有转换时间格式 # time.clock() # Python 3.8 已移除 clock() 方法,改用下方: print(time.process_time()) # ArgumentParser print("ArgumentParser") parser = argparse.ArgumentParser(description='Process some integers.') parser.add_argument('int_val', metavar='N', type=int, nargs='+', help='an integer for the accumulator') parser.add_argument("square", help="display a square of a given number", type=int) args = parser.parse_args() print("输入的int_val={0}".format(args.int_val)) print("输入的square={0}".format(args.square)) print(args.square**2)
51job-autotest-framework
/51job_autotest_framework-0.3.1-py3-none-any.whl/rolling_king/jason/python/MyPyTest.py
MyPyTest.py
#!/usr/bin/python3 # -*- coding: UTF-8 -*- # $ pip3 install PyMySQL # Collecting PyMySQL # Downloading PyMySQL-0.10.1-py2.py3-none-any.whl (47 kB) # |████████████████████████████████| 47 kB 1.9 kB/s # Installing collected packages: PyMySQL # Successfully installed PyMySQL-0.10.1 import pymysql # 打开数据库连接 # db = pymysql.connect("localhost","testuser","test123","TESTDB") db = pymysql.connect("10.84.234.28", "ccc_test_info", "ccc_test_info", "db_ccc_test_info", 5002) # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() # 使用 execute() 方法执行 SQL 查询 intVar = cursor.execute("SELECT VERSION()") print("返回{0}条数据".format(intVar)) # 使用 fetchone() 方法获取单条数据. dbVersion = cursor.fetchone() print("dbVersion = {0}".format(dbVersion)) print("Database version : %s " % dbVersion) # 关闭数据库连接 db.close() # 因上面已经close了数据库连接,所以若不重新建立连接就直接查询,则connection.py会报出pymysql.err.InterfaceError: (0, '')问题。 db = pymysql.connect("10.84.234.28", "ccc_test_info", "ccc_test_info", "db_ccc_test_info", 5002) cursor = db.cursor() # querySql = "SELECT * FROM test_env WHERE UID > %s" % ("3") querySql = "SELECT * FROM test_env WHERE UID > 3" intVar = cursor.execute(querySql) print("返回{0}条数据".format(intVar)) tupleResult = cursor.fetchall() for var in tupleResult: print("当前结果集元祖为:", var) print("结果集共{0}个字段".format(len(var))) print("结果集第一个字段值=", var[0])
51job-autotest-framework
/51job_autotest_framework-0.3.1-py3-none-any.whl/rolling_king/jason/python/DbTest.py
DbTest.py
#!/usr/bin/python3 # -*- coding: UTF-8 -*- from functools import reduce import functools # ################### 闭包 ################### # 闭包的定义:在函数嵌套的前提下,内部函数使用了外部函数的变量,并且外部函数返回了内部函数,这种程序结构称为闭包。 # 闭包的构成条件: # 1、在函数嵌套(函数里面再定义函数)的前提下 # 2、内部函数使用了外部函数的变量(还包括外部函数的参数) # 3、外部函数返回了内部函数 # 定义一个外部函数 def func_out(num1): # 定义一个内部函数 def func_inner(num2): # 内部函数使用了外部函数的变量(num1) result = num1 + num2 print("结果是:", result) # 外部函数返回了内部函数,这里返回的内部函数就是闭包 return func_inner # 创建闭包实例 f = func_out(1) # 执行闭包 f(2) # 3 f(3) # 4 # 若要修改外部函数的变量,则内部函数中应该: # nonlocal num1 # 告诉解释器,此处使用的是 外部变量a # 修改外部变量num1 # num1 = 10 # ################### 装饰器 ################### # 装饰器的定义:就是给已有函数增加额外功能的函数,它本质上就是一个闭包函数。 # 代码运行期间动态增加功能的方式,称之为“装饰器”(Decorator)。 # 装饰器的功能特点: # 1、不修改已有函数的源代码 # 2、不修改已有函数的调用方式 # 3、给已有函数增加额外的功能 # 添加一个登录验证的功能 def check(fn): def inner(): print("请先登录....") fn() return inner def comment(): print("发表评论") # 使用装饰器来装饰函数 comment = check(comment) comment() ''' 执行结果 请先登录.... 发表评论 ''' # 装饰器的基本雏形 # def decorator(fn): # fn:目标函数. # def inner(): # '''执行函数之前''' # fn() # 执行被装饰的函数 # '''执行函数之后''' # return inner # 代码说明: # 闭包函数有且只有一个参数,必须是函数类型,这样定义的函数才是装饰器。 # 写代码要遵循开放封闭原则,它规定已经实现的功能代码不允许被修改,但可以被扩展。 # 装饰器的语法糖写法 # Python给提供了一个装饰函数更加简单的写法,那就是语法糖,语法糖的书写格式是: @装饰器名字,通过语法糖的方式也可以完成对已有函数的装饰 # 使用语法糖方式来装饰函数 @check def comment(): print("发表评论") # @check 等价于 comment = check(comment) # 装饰器的执行时间是加载模块时立即执行。 # ###### 装饰带有参数的函数 ###### def logging(fn): def inner(num1, num2): print("--正在努力计算--") fn(num1, num2) return inner # 使用装饰器装饰函数 @logging def sum_num(a, b): result = a + b print(result) sum_num(1, 2) ''' 运行结果: --正在努力计算-- 3 ''' # ###### 装饰带有返回值的函数 ###### # 添加输出日志的功能 def logging(fn): def inner(num1, num2): print("--正在努力计算--") result = fn(num1, num2) return result return inner # 使用装饰器装饰函数 @logging def sum_num(a, b): result = a + b return result result = sum_num(1, 2) print(result) ''' 运行结果: --正在努力计算-- 3 ''' # ###### 装饰带有不定长参数的函数 ###### # 添加输出日志的功能 def logging(func): def inner(*args, **kwargs): print("--正在努力计算--") func(*args, **kwargs) return inner # 使用语法糖装饰函数 @logging def sum_num(*args, **kwargs): result = 0 for value in args: result += value for value in kwargs.values(): result += value print(result) sum_num(1, 2, a=10) ''' 运行结果: --正在努力计算-- 13 ''' # ###### 通用装饰器 ###### # 通用装饰器 - 添加输出日志的功能 def logging(func): def inner(*args, **kwargs): print("--正在努力计算--") result = func(*args, **kwargs) return result return inner # 使用语法糖装饰函数 @logging def sum_num(*args, **kwargs): result = 0 for value in args: result += value for value in kwargs.values(): result += value return result @logging def subtraction(a, b): result = a - b print(result) result = sum_num(1, 2, a=10) print(result) subtraction(4, 2) ''' 运行结果: --正在努力计算-- 13 --正在努力计算-- 2 ''' # log方法作为装饰器,返回替代func方法的wrapper方法,利用@functools.wraps表示,以便让wrapper.__name__等同于func.__name__。 def log(func): @functools.wraps(func) #import functools才行 def wrapper(*args, **kw): print('call %s():' % func.__name__) return func(*args, **kw) return wrapper # 针对带参数的decorator: def log_with_param(text): def decorator(func): @functools.wraps(func) def wrapper(*args, **kw): print('%s %s():' % (text, func.__name__)) return func(*args, **kw) return wrapper return decorator # ###### 多个装饰器的使用 ###### # 代码说明:多个装饰器的装饰过程是: 离函数最近的装饰器先装饰,然后外面的装饰器再进行装饰,由内到外的装饰过程。 def make_div(func): """对被装饰的函数的返回值 div标签""" def inner(): return "<div>" + func() + "</div>" return inner def make_p(func): """对被装饰的函数的返回值 p标签""" def inner(): return "<p>" + func() + "</p>" return inner # 装饰过程: 1 content = make_p(content) 2 content = make_div(content) # content = make_div(make_p(content)) @make_div @make_p def content(): return "人生苦短" result = content() print(result) # <div><p>人生苦短</p></div> # ################### 带有参数的装饰器 ################### # 代码说明:装饰器只能接收一个参数,并且还是函数类型。 # 正确写法:在装饰器外面再包裹上一个函数,让最外面的函数接收参数,返回的是装饰器,因为@符号后面必须是装饰器实例。 # 添加输出日志的功能 def logging(flag): def decorator(fn): def inner(num1, num2): if flag == "+": print("--正在努力加法计算--") elif flag == "-": print("--正在努力减法计算--") result = fn(num1, num2) return result return inner # 返回装饰器 return decorator # 使用装饰器装饰函数 @logging("+") def add(a, b): result = a + b return result @logging("-") def sub(a, b): result = a - b return result result = add(1, 2) print(result) result = sub(1, 2) print(result) ''' 执行结果: --正在努力加法计算-- 3 --正在努力减法计算-- -1 ''' # ################### 类装饰器 ################### # 类装饰器的介绍:装饰器还有一种特殊的用法就是类装饰器,就是通过定义一个类来装饰函数。 class Check(object): def __init__(self, fn): # 初始化操作在此完成 self.__fn = fn # 实现__call__方法,表示对象是一个可调用对象,可以像调用函数一样进行调用。 def __call__(self, *args, **kwargs): # 添加装饰功能 print("请先登陆...") self.__fn() @Check def comment(): print("发表评论") comment() ''' 执行结果: 请先登陆... 发表评论 ''' # 代码说明: # 1.1@Check 等价于 comment = Check(comment), 所以需要提供一个init方法,并多增加一个fn参数。 # 1.2要想类的实例对象能够像函数一样调用,需要在类里面使用call方法,把类的实例变成可调用对象(callable),也就是说可以像调用函数一样进行调用。 # 1.3在call方法里进行对fn函数的装饰,可以添加额外的功能。 # 函数式编程 # 其一个特点就是,允许把函数本身作为参数传入另一个函数,还允许返回一个函数! # 函数本身也可以赋值给变量,即:变量可以指向函数。 f = abs # 变量f现在已经指向了abs函数本身。 print(f(-10)) # 高阶函数 # 一个函数就可以接收另一个函数作为参数,这种函数就称之为高阶函数。 # map函数 def func(x): return x * x r = map(func, [1,2,3,4]) # map()函数接收两个参数,一个是函数,一个是Iterable # map将传入的函数依次作用到序列的每个元素,并把结果作为新的Iterator返回。 # Iterator是惰性序列,因此通过list()函数让它把整个序列都计算出来并返回一个list。 print(list(r)) # reduce函数 # reduce把一个函数作用在一个序列[x1, x2, x3, ...]上,这个函数必须接收两个参数。reduce把结果继续和序列的下一个元素做计算。 def fn(x, y): return x * 10 + y res = reduce(fn, [1, 3, 5, 7, 9]) print(res) # map、reduce函数配合使用将str转为int。 DIGITS = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9} def str2int(s): def fn1(x, y): return x * 10 + y def char2num(s): return DIGITS[s] return reduce(fn1, map(char2num, s)) # 还可以用lambda函数进一步简化成: # 无需定义fn1这个函数,直接用lambda表达式替换 def char2num(s): return DIGITS[s] def str_to_int(s): return reduce(lambda x, y: x * 10 + y, map(char2num, s)) # filter() 函数 # Python内建的filter()函数用于过滤序列。 # filter()把传入的函数依次作用于每个元素,然后根据返回值是True还是False决定保留还是丢弃该元素。 # 注意到filter()函数返回的是一个Iterator,也就是一个惰性序列。 def is_odd(n): return n % 2 == 1 res = filter(is_odd, [1, 2, 3, 4, 5, 6]) print(list(res)) def not_empty(s): return s and s.strip() print(list(filter(not_empty, ['A', '', ' B', None, 'C ', ' ']))) # 排序算法 # Python内置的sorted()函数就可以对list进行排序: print(sorted([36, 5, -12, 9, -21])) # 此外,sorted()函数也是一个高阶函数,它还可以接收一个key函数来实现自定义的排序,例如按绝对值大小排序: print(sorted([36, 5, -12, 9, -21], key=abs)) # 给sorted传入key函数,即可实现忽略大小写的排序: print(sorted(['bob', 'about', 'Zoo', 'Credit'], key=str.lower)) # 要进行反向排序,不必改动key函数,可以传入第三个参数reverse=True: print(sorted(['bob', 'about', 'Zoo', 'Credit'], key=str.lower, reverse=True)) # 按成绩从高到低排序: L = [('Bob', 75), ('Adam', 92), ('Bart', 66), ('Lisa', 88)] def by_score(t): return -t[1] L2 = sorted(L, key=by_score) print(L2) # 偏函数 # functools.partial:作用就是,把一个函数的某些参数给固定住(也就是设置默认值),返回一个新的函数,调用这个新函数会更简单。 int2 = functools.partial(int, base=2) # 接收函数对象、*args和**kw这3个参数。入参1是方法名。 # 相当于: kw = {'base': 2} int('10010', **kw) print(int2('1000000')) # int2方法就是把2进制字符串转为integer,相当于int('char', base=2) # int2函数,仅仅是把base参数重新设定默认值为2,但也可以在函数调用时传入其他值: print(int2('1000000', base=10)) # 当传入max2 = functools.partial(max, 10)时,把10作为*args的一部分自动加到左边。 max2 = functools.partial(max, 10) print(max2(5, 6, 7)) # 相当于: args = (10, 5, 6, 7) max(*args)
51job-autotest-framework
/51job_autotest_framework-0.3.1-py3-none-any.whl/rolling_king/jason/python/SeniorTest.py
SeniorTest.py
#!/usr/bin/python3 # -*- coding: UTF-8 -*- import queue import threading import time exitFlag = 0 class MyThread(threading.Thread): def __init__(self, threadID, name, q): threading.Thread.__init__(self) self.threadID = threadID self.name = name self.q = q def run(self): print("开启线程:" + self.name) self.process_data(self.name, self.q) print("退出线程:" + self.name) def process_data(self, threadName, q): while not exitFlag: queueLock.acquire() if not workQueue.empty(): data = q.get() print("data = ", data) queueLock.release() print("%s processing %s" % (threadName, data)) else: queueLock.release() time.sleep(1) threadList = ["Thread-1", "Thread-2", "Thread-3"] nameList = ["One", "Two", "Three", "Four", "Five"] queueLock = threading.Lock() workQueue = queue.Queue(10) threads = [] threadID = 1 # 创建新线程 for tName in threadList: thread = MyThread(threadID, tName, workQueue) thread.start() print("Add ", tName, "into threads") threads.append(thread) threadID += 1 # 填充队列 queueLock.acquire() for word in nameList: print("Add ", word, "into workQueue") workQueue.put(word) queueLock.release() # 等待队列清空 while not workQueue.empty(): pass # 通知线程是时候退出 exitFlag = 1 # 等待所有线程完成 for t in threads: t.join() print("退出主线程")
51job-autotest-framework
/51job_autotest_framework-0.3.1-py3-none-any.whl/rolling_king/jason/python/QueueTest.py
QueueTest.py
#!/usr/bin/python3 # -*- coding: UTF-8 -*- import builtins # Python 3 可以使用直接使用 super().xxx 代替 super(Class, self).xxx : class Employee: empCount = 0 class Member(object): def __init__(self): print("This is {0} Constructor.".format("无参")) member = Member() class Parent(object): def myfunc(self): print("This is {0}'s myfunc method.".format("Parent")) class SubA(Parent): def myfunc(self): print("This is {0}'s myfunc method.".format("SubA")) super().myfunc() super(SubA, self).myfunc() sub = SubA() sub.myfunc() class Upper(object): def myfunc(self): print("This is {0}'s myfunc method.".format("Upper")) # class Child(Parent, SubA): # 多个基类之间不能存在继承关系否则将有如下错误: # TypeError: Cannot create a consistent method resolution # order (MRO) for bases Parent, SubA class Child(Parent, Upper): def __init__(self): super(Child, self).__init__() # 首先找到 Child 的父类(就是类 Parent),然后把类 Child 的对象转换为类 Parent 的对象 def myfunc(self): print("This is {0}'s myfunc method.".format("Child")) super(Child, self).myfunc() child = Child() child.myfunc() print(issubclass(Child, Parent)) # Child类 是 Parent的子类 print(isinstance(child, Child)) # child 是 Child类的实例 print(isinstance(child, Parent)) # child 是 Parent类子类的实例 print(isinstance(child, Upper)) # child 是 Upper类子类的实例 # 类的私有属性 # __private_attrs:两个下划线开头,在类内部的方法中使用时 self.__private_attrs。 # 类的私有方法 # __private_method:两个下划线开头,在类的内部调用 self.__private_methods。 # 单下划线、双下划线、头尾双下划线说明: # __foo__: 定义的是特殊方法,一般是系统定义名字 ,类似 __init__() 之类的。 # _foo: 以单下划线开头的表示的是 protected 类型的变量,即保护类型只能允许其本身与子类进行访问,不能用于 from module import * # __foo: 双下划线的表示的是私有类型(private)的变量, 只能是允许这个类本身进行访问了。 # Python 中只有模块(module),类(class)以及函数(def、lambda)才会引入新的作用域 # 有四种作用域: # L(Local):最内层,包含局部变量,比如一个函数/方法内部。 # E(Enclosing):包含了非局部(non-local)也非全局(non-global)的变量。比如两个嵌套函数,一个函数(或类) A 里面又包含了一个函数 B ,那么对于 B 中的名称来说 A 中的作用域就为 nonlocal。 # G(Global):当前脚本的最外层,比如当前模块的全局变量。 # B(Built-in): 包含了内建的变量/关键字等。,最后被搜索 # 实例熟悉 与 类属性 # 实例属性属于各个实例所有,互不干扰; # 类属性属于类所有,所有实例共享一个属性; # 不要对实例属性和类属性使用相同的名字,否则将产生难以发现的错误。 # 可以给该实例绑定任何属性和方法,这就是动态语言的灵活性 # class Student(object): # pass # # 然后,尝试给实例绑定一个属性: # >>> s = Student() # >>> s.name = 'Michael' # >>> print(s.name) # Michael # 还可以尝试给实例绑定一个方法: # >>> def set_age(self, age): # ... self.age = age # ... # >>> from types import MethodType # >>> s.set_age = MethodType(set_age, s) # >>> s.set_age(25) # >>> s.age # 25 # 给一个实例绑定的方法,对另一个实例是不起作用的 # 为了给所有实例都绑定方法,可以给class绑定方法: # >>> def set_score(self, score): # ... self.score = score # ... # >>> Student.set_score = set_score # # 给class绑定方法后,所有实例均可调用。 # 使用__slots__ 限制某类型的实例可以添加的属性 # 想要限制实例的属性怎么办?Python允许在定义class的时候,定义一个特殊的__slots__变量,来限制该class实例能添加的属性。 # class Student(object): # __slots__ = ('name', 'age') # # 然后,我们试试: # >>> s = Student() # >>> s.name = 'Michael' # >>> s.age = 25 # >>> s.score = 99 # 试图绑定score将得到AttributeError的错误。 # 使用__slots__要注意,__slots__定义的属性仅对当前类的实例起作用,对继承的子类是不起作用的。 # @property装饰器 # 有没有既能检查参数,又可以用类似属性这样简单的方式来访问类的变量呢? # Python内置的@property装饰器就是负责把一个方法变成属性调用的。 class Student(object): @property def score(self): return self._score @score.setter def score(self, value): if not isinstance(value, int): raise ValueError('score must be an integer!') if value < 0 or value > 100: raise ValueError('score must between 0 ~ 100!') self._score = value # 把一个getter方法变成属性,只需要加上@property就可以了 # @property本身又创建了另一个装饰器@score.setter,负责把一个setter方法变成属性赋值 # >>> s = Student() # >>> s.score = 60 # >>> s.score # 60 # 还可以定义只读属性,只定义getter方法,不定义setter方法就是一个只读属性。 # 查看到底预定义了哪些变量: print(dir(builtins)) # global 关键字 num = 1 def fun1(): global num # 需要使用 global 关键字声明 print(num) num = 123 print(num) fun1() print(num) # 如果要修改嵌套作用域(enclosing 作用域,外层非全局作用域)中的变量则需要 nonlocal 关键字 def outer(): num = 10 def inner(): nonlocal num # nonlocal关键字声明 num = num + 100 print(num) inner() print(num) outer() a = 10 def test(a): # a 是 number,不可变对象属于值传递,也就是复制a的值传进来,而不是a本身。 a = a + 1 # 11 = 10 + 1 print(a) # 11 test(a) print(a) # 10 # 动态语言的“鸭子类型” # 对于静态语言(例如Java)来说,如果需要传入Animal类型,则传入的对象必须是Animal类型或者它的子类,否则,将无法调用run()方法。 # 对于Python这样的动态语言来说,则不一定需要传入Animal类型。我们只需要保证传入的对象有一个run()方法就可以了 # 获取对象信息。获得一个对象的所有属性和方法 # >>> import types # >>> def fn(): # ... pass # ... # >>> type(fn)==types.FunctionType # True # >>> type(abs)==types.BuiltinFunctionType # True # >>> type(lambda x: x)==types.LambdaType # True # >>> type((x for x in range(10)))==types.GeneratorType # True # 获得一个对象的所有属性和方法,可以使用dir()函数,它返回一个包含字符串的list # 调用len()函数试图获取一个对象的长度,实际上,在len()函数内部,它自动去调用该对象的__len__()方法: # 自己写的类,如果也想用len(myObj)的话,就自己写一个__len__()方法 # 配合getattr()、setattr()以及hasattr(),我们可以直接操作一个对象的状态 # >>> getattr(obj, 'z', 404) # 获取属性'z',如果不存在,返回默认值404 # 404 # >>> hasattr(obj, 'power') # 有属性'power'吗? # True # >>> getattr(obj, 'power') # 获取属性'power' # <bound method MyObject.power of <__main__.MyObject object at 0x10077a6a0>> # >>> fn = getattr(obj, 'power') # 获取属性'power'并赋值到变量fn # >>> fn # fn指向obj.power # <bound method MyObject.power of <__main__.MyObject object at 0x10077a6a0>> # >>> fn() # 调用fn()与调用obj.power()是一样的 # 81 # 枚举 from enum import Enum Month = Enum('Month', ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec')) print(Month.Jan) # value属性则是自动赋给成员的int常量,默认从1开始计数。 for name, member in Month.__members__.items(): print(name, '=>', member, ',', member.value) # 更精确地控制枚举类型,可以从Enum派生出自定义类: from enum import Enum, unique # @unique装饰器可以帮助我们检查保证没有重复值。 @unique class Weekday(Enum): Sun = 0 Mon = 1 Tue = 2 Wed = 3 Thu = 4 Fri = 5 Sat = 6 day1 = Weekday.Mon print(day1) print(Weekday['Tue']) print(Weekday.Sun.value) print(day1 == Weekday.Mon) print(Weekday(1)) print(day1 == Weekday(1)) for name, member in Weekday.__members__.items(): print(name, '=>', member) # 使用元类 # 动态语言和静态语言最大的不同,就是函数和类的定义,不是编译时定义的,而是运行时动态创建的。 print(type(Member)) print(type(member)) # class的定义是运行时动态创建的,而创建class的方法就是使用type()函数。 # type()函数既可以返回一个对象的类型,又可以创建出新的类型。 def fn(self, name='world'): # 先定义函数 print('Hello, %s.' % name) # 创建一个class对象,type()函数依次传入3个参数:class的名称、继承的父类集合(是一个tuple)、class的方法名称与函数绑定(是一个dict) Hello = type('Hello', (object,), dict(hello=fn)) # 创建Hello class h = Hello() h.hello() print(type(Hello)) # <class 'type'> print(type(h)) # <class '__main__.Hello'> # 除了使用type()动态创建类以外,还可以使用metaclass。 # metaclass,直译为元类。先定义metaclass,就可以创建类,最后创建实例。 # metaclass允许你创建类或者修改类。可以把类看成是metaclass创建出来的“实例”。 # 我们先看一个简单的例子,这个metaclass可以给我们自定义的MyList增加一个add方法: # 定义ListMetaclass,按照默认习惯,metaclass的类名总是以Metaclass结尾,以便清楚地表示这是一个metaclass: class ListMetaclass(type): def __new__(cls, name, bases, attrs): attrs['add'] = lambda self, value: self.append(value) print("attrs = ", attrs) # {'__module__': '__main__', '__qualname__': 'MyList', 'add': <function ListMetaclass.__new__.<locals>.<lambda> at 0x1020b79d0>} return type.__new__(cls, name, bases, attrs) # 有了ListMetaclass,我们在定义类的时候还要指示使用ListMetaclass来定制类,传入关键字参数metaclass: class MyList(list, metaclass=ListMetaclass): pass # 当我们传入关键字参数metaclass时,魔术就生效了,它指示Python解释器在创建MyList时,要通过ListMetaclass.__new__()来创建, # 在此,我们可以修改类的定义,比如,加上新的方法,然后,返回修改后的定义。 # __new__()方法接收到的参数依次是:当前准备创建的类的对象、类的名字、类继承的父类集合、类的方法集合。 L = MyList() L.add(1) # 普通的list没有add()方法,这个add方法是 L.append(2) print(L) # [1, 2] # ### 通过metaclass来实现ORM框架 ### # class User(Model): # id = IntegerField('id') # name = StringField('username') # email = StringField('email') # password = StringField('password') # u = User(id=12345, name='Michael', email='test@orm.org', password='my-pwd') class Field(object): def __init__(self, name, column_type): self.name = name self.column_type = column_type def __str__(self): return '<%s:%s>' % (self.__class__.__name__, self.name) class StringField(Field): def __init__(self, name): super().__init__(name, "varchar(100)") # Python3 方式 class IntegerField(Field): def __init__(self, name): super(IntegerField, self).__init__(name, "bigint") # 通用方式 # 下一步,就是编写最复杂的ModelMetaclass了: # 建议使用 "import os" 风格而非 "from os import *"。这样可以保证随操作系统不同而有所变化的 os.open() 不会覆盖内置函数 open()。 import os print(os.getcwd()) os.chdir("/Users/jasonzheng/PycharmProjects/pythonProject/rolling_king/jason") print(os.getcwd()) os.system("mkdir today") os.system("touch temp.txt") # 针对日常的文件和目录管理任务,:mod:shutil 模块提供了一个易于使用的高级接口: import shutil shutil.copyfile("temp.txt", "./today/new.txt") shutil.copy("temp.txt", "./today") # 文件通配符 # glob模块提供了一个函数用于从目录通配符搜索中生成文件列表: import glob list = glob.glob("*.txt") print(list) # 测试模块 def average(values): """Computes the arithmetic mean of a list of numbers. >>> print(average([20, 30, 70])) 40.0 """ return sum(values) / len(values) import doctest doctest.testmod() # 自动验证嵌入测试 a = [10, ] print(len(a)) # 1 print('%.2f' % 123.444) # unittest模块 import unittest class TestStatisticalFunctions(unittest.TestCase): def test_average(self): self.assertEqual(average([20, 30, 70]), 40.0) self.assertEqual(round(average([1, 5, 7]), 1), 4.3) self.assertRaises(ZeroDivisionError, average, []) self.assertRaises(TypeError, average, 20, 30, 70) unittest.main() # Calling from the command line invokes all tests
51job-autotest-framework
/51job_autotest_framework-0.3.1-py3-none-any.whl/rolling_king/jason/python/ClassTest.py
ClassTest.py
#!/usr/bin/python3 # -*- coding: UTF-8 -*- import socket # 导入 socket 模块 s = socket.socket() # 创建 socket 对象 host = socket.gethostname() # 获取本地主机名 port = 8888 s.connect((host, port)) sentMsg = "我是Client" bytes = bytes(sentMsg, "UTF-8") s.send(bytes) print("Client发送:", sentMsg) receivedBytes = s.recv(1024) print("Client收到:", str(receivedBytes, "UTF-8")) s.close()
51job-autotest-framework
/51job_autotest_framework-0.3.1-py3-none-any.whl/rolling_king/jason/python/socket/SocketClient.py
SocketClient.py
#!/usr/bin/python3 # -*- coding: UTF-8 -*- import socket # 导入 socket 模块 s = socket.socket() # 创建 socket 对象 host = socket.gethostname() # 获取本地主机名 port = 8888 # 设置端口 s.bind((host, port)) # 绑定主机与端口 s.listen(5) # 等待客户端连接 print("开始监听Socket...") while True: socketObj, addr = s.accept() # 接受客户端连接 print("Addr = ", addr) serverRecvBytes = socketObj.recv(1024) print("Server端收到:", str(serverRecvBytes, "UTF-8")) socketObj.send(bytes("Socket响应。", "UTF-8")) print("Server端发送: ", "Socket响应。") socketObj.close() # 关闭连接
51job-autotest-framework
/51job_autotest_framework-0.3.1-py3-none-any.whl/rolling_king/jason/python/socket/SocketServer.py
SocketServer.py
#!/usr/bin/python3 # -*- coding: utf-8 -*- # @Time : 2022/1/26 12:17 下午 # @Author : zhengyu.0985 # @FileName: __init__.py.py # @Software: PyCharm
51job-autotest-framework
/51job_autotest_framework-0.3.1-py3-none-any.whl/rolling_king/jason/python/socket/__init__.py
__init__.py
#!/usr/bin/python3 # -*- coding: UTF-8 -*- import logging from src.rolling_king.jason.openpyxl.excel_util import ExcelUtil logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s') # logging.basicConfig函数对日志的输出格式及方式做相关配置 logger = logging.getLogger("ExcelTest") def func_excel_val_change(excel_path, excel_sheet, col): excel_operator = ExcelUtil(excel_path, excel_sheet) logger.info(excel_operator.rows) total_row = excel_operator.rows day_val = 0 for curr_row in range(2, total_row+1): # 因为range不包括total_row,所以为了包括而+1 val = excel_operator.get_cell_value(curr_row, col) print(val) if val.endswith("秒"): sec_val = val.split(" ")[0] day_val = int(sec_val)/24/60/60 set_val = str(round(float(day_val), 2)) + " 天" excel_operator.set_cell_value(curr_row, col, set_val) logger.info("设置{0}行{1}列的值为{2}".format(curr_row, col, set_val)) elif val.endswith("分钟"): min_val = val.split(" ")[0] day_val = int(min_val)/24/60 set_val = str(round(float(day_val), 2)) + " 天" excel_operator.set_cell_value(curr_row, col, set_val) logger.info("设置{0}行{1}列的值为{2}".format(curr_row, col, set_val)) elif val.endswith("小时"): hour_val = val.split(" ")[0] day_val = int(hour_val)/24 set_val = str(round(float(day_val), 2))+" 天" excel_operator.set_cell_value(curr_row, col, set_val) logger.info("设置{0}行{1}列的值为{2}".format(curr_row, col, set_val)) excel_operator.save("/Users/admin/Downloads/缺陷导出.xlsx") if __name__ == "__main__": func_excel_val_change("/Users/admin/Downloads/缺陷导出-商业产品 (9).xlsx", "缺陷导出-商业产品", 12)
51job-autotest-framework
/51job_autotest_framework-0.3.1-py3-none-any.whl/rolling_king/jason/python/tools/ExcelTest.py
ExcelTest.py
#!/usr/bin/python3 # -*- coding: utf-8 -*- # @Time : 2022/1/28 4:20 下午 # @Author : zhengyu.0985 # @FileName: zy_schedule.py # @Software: PyCharm import schedule import time import threading import functools import logging logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s') # logging.basicConfig函数对日志的输出格式及方式做相关配置 logger = logging.getLogger('com.autotest.db.sqlalchemy_util') # def job(): # print("I'm working...") # # # schedule.every(10).seconds.do(job) # # while True: # schedule.run_pending() # 检测是否执行 # time.sleep(1) # logger.info("Waiting for 1 second...") def job(): print("I'm working...") # 每十分钟执行任务 schedule.every(10).minutes.do(job) # 每个小时执行任务 schedule.every().hour.do(job) # 每天的10:30执行任务 schedule.every().day.at("10:30").do(job) # 每个月执行任务 schedule.every().monday.do(job) # 每个星期三的13:15分执行任务 schedule.every().wednesday.at("13:15").do(job) # 每分钟的第17秒执行任务 schedule.every().minute.at(":17").do(job) while True: schedule.run_pending() time.sleep(1) # 只运行一次 def job_that_executes_once(): # 此处编写的任务只会执行一次... return schedule.CancelJob schedule.every().day.at('22:30').do(job_that_executes_once) while True: schedule.run_pending() time.sleep(1) # 参数传递 def greet(name): print('Hello', name) # do() 将额外的参数传递给job函数 schedule.every(2).seconds.do(greet, name='Alice') schedule.every(4).seconds.do(greet, name='Bob') # 获取所有作业 and 取消所有作业 def hello(): print('Hello world') schedule.every().second.do(hello) all_jobs = schedule.get_jobs() # 获取 schedule.clear() # 取消 # .tag 打标签 schedule.every().day.do(greet, 'Andrea').tag('daily-tasks', 'friend') schedule.every().hour.do(greet, 'John').tag('hourly-tasks', 'friend') schedule.every().hour.do(greet, 'Monica').tag('hourly-tasks', 'customer') schedule.every().day.do(greet, 'Derek').tag('daily-tasks', 'guest') # get_jobs(标签):可以获取所有该标签的任务 friends = schedule.get_jobs('friend') # 取消所有 daily-tasks 标签的任务 schedule.clear('daily-tasks') # 设定截止时间 # 每个小时运行作业,18:30后停止 schedule.every(1).hours.until("18:30").do(job) # 每个小时运行作业,2030-01-01 18:33 today schedule.every(1).hours.until("2030-01-01 18:33").do(job) # 每个小时运行作业,8个小时后停止 schedule.every(1).hours.until(timedelta(hours=8)).do(job) # 每个小时运行作业,11:32:42后停止 schedule.every(1).hours.until(time(11, 33, 42)).do(job) # 每个小时运行作业,2020-5-17 11:36:20后停止 schedule.every(1).hours.until(datetime(2020, 5, 17, 11, 36, 20)).do(job) # 立即运行所有作业,而不管其安排如何 schedule.run_all() # 立即运行所有作业,每次作业间隔10秒 schedule.run_all(delay_seconds=10) # 装饰器安排作业 # 此装饰器效果等同于 schedule.every(10).minutes.do(job) @repeat(every(10).minutes) def job(): print("I am a scheduled job") while True: run_pending() time.sleep(1) # 并行执行 # 默认情况下,Schedule 按顺序执行所有作业 # 通过多线程的形式来并行每个作业 def job1(): print("I'm running on thread %s" % threading.current_thread()) def job2(): print("I'm running on thread %s" % threading.current_thread()) def job3(): print("I'm running on thread %s" % threading.current_thread()) def run_threaded(job_func): job_thread = threading.Thread(target=job_func) job_thread.start() schedule.every(10).seconds.do(run_threaded, job1) schedule.every(10).seconds.do(run_threaded, job2) schedule.every(10).seconds.do(run_threaded, job3) while True: schedule.run_pending() time.sleep(1) # 异常处理 # Schedule 不会自动捕捉异常,它遇到异常会直接抛出 def catch_exceptions(cancel_on_failure=False): def catch_exceptions_decorator(job_func): @functools.wraps(job_func) def wrapper(*args, **kwargs): try: return job_func(*args, **kwargs) except: import traceback print(traceback.format_exc()) if cancel_on_failure: return schedule.CancelJob return wrapper return catch_exceptions_decorator @catch_exceptions(cancel_on_failure=True) def bad_task(): return 1 / 0 # 这样,bad_task 在执行时遇到的任何错误,都会被 catch_exceptions 捕获,这点在保证调度任务正常运转的时候非常关键。 schedule.every(5).minutes.do(bad_task)
51job-autotest-framework
/51job_autotest_framework-0.3.1-py3-none-any.whl/rolling_king/jason/python/tools/zy_schedule.py
zy_schedule.py
#!/usr/bin/python3 # -*- coding: utf-8 -*- # @Time : 2022/3/16 12:01 PM # @Author : zhengyu.0985 # @FileName: zy_shell.py # @Software: PyCharm import os import logging logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s') # logging.basicConfig函数对日志的输出格式及方式做相关配置 logger = logging.getLogger('zy_shell') def check_if_has_rolling(): flag = False res = os.popen("python3 -m pip list | grep rolling-in-the-deep") lines = res.readlines() if len(lines) == 1: logging.info("【已安装】{}".format("rolling-in-the-deep")) flag = True else: res = os.popen("python3 -m pip install --index-url https://pypi.org/simple/ --no-deps rolling-in-the-deep") lines = res.readlines() for val in lines: if 'Successfully installed rolling-in-the-deep' in val or 'Requirement already satisfied' in val: flag = True break else: pass return flag if __name__ == '__main__': logger.info(check_if_has_rolling())
51job-autotest-framework
/51job_autotest_framework-0.3.1-py3-none-any.whl/rolling_king/jason/python/tools/zy_shell.py
zy_shell.py
#!/usr/bin/python3 # -*- coding: utf-8 -*- # @Time : 2022/3/8 4:08 下午 # @Author : zhengyu.0985 # @FileName: zy_stamp_tool.py # @Software: PyCharm from datetime import datetime import time class TimeStampExchange(object): @staticmethod def stamp2datetime(stamp_val=None) -> str: if stamp_val is None: return datetime.now().strftime('%Y-%m-%d %H:%M:%S') elif len(str(stamp_val)) == 13: return datetime.fromtimestamp(stamp_val/1000).strftime('%Y-%m-%d %H:%M:%S') else: return datetime.fromtimestamp(stamp_val).strftime('%Y-%m-%d %H:%M:%S') @staticmethod def datetime2stamp(date_time_str=None, stamp_digits=10) -> int: if date_time_str is None: date_time_str = datetime.now().strftime('%Y-%m-%d %H:%M:%S') date_time_obj = datetime.strptime(date_time_str, '%Y-%m-%d %H:%M:%S') if stamp_digits == 13: return int(time.mktime(date_time_obj.timetuple()) * 1000 + date_time_obj.microsecond / 1000) else: return int(date_time_obj.timestamp()) if __name__ == '__main__': val = TimeStampExchange.stamp2datetime(1646201351000) print(val) print('-----------') val = TimeStampExchange.datetime2stamp("2022-03-02 14:09:11", 13) print(val)
51job-autotest-framework
/51job_autotest_framework-0.3.1-py3-none-any.whl/rolling_king/jason/python/tools/zy_stamp_tool.py
zy_stamp_tool.py
# -*- coding: utf-8 -*- # --- # @File: xmind_excel_converter.py # @Author: gaoxiang.404 # @Time: 4月 29, 2021 # --- import xmind import csv import time source = xmind.load('/Users/admin/Documents/Checklist/Checklist-应用代码位管理API删除聚合属性代码位限制.xmind') case_base = source.getData()[0]['topic']['topics'] def xmind2excel(): output_filename = 'testcase_{}.cvs'.format(str(time.time())[-5:]) with open(output_filename, 'w', newline='') as csvfile: fieldname = ['Node', 'Case', 'Status', 'Tester'] writer = csv.DictWriter(csvfile, delimiter='\t', fieldnames=fieldname) writer.writeheader() for node in case_base: row_node = node['title'] for case in node['topics']: row_case = case['title'] writer.writerow({'Node':row_node,'Case':row_case,'Status': 'NOT RUN', 'Tester': 'QA'}) if __name__ == '__main__': # print(source.getData()[0]['topic']['topics']) # print(source.to_prettify_json()) xmind2excel()
51job-autotest-framework
/51job_autotest_framework-0.3.1-py3-none-any.whl/rolling_king/jason/python/tools/xmind_excel_converter.py
xmind_excel_converter.py
#!/usr/bin/python3 # -*- coding: UTF-8 -*- # 开始学习Python线程 # Python中使用线程有两种方式:函数或者用类来包装线程对象。 # 函数式:调用 _thread 模块中的start_new_thread()函数来产生新线程。语法如下: # # _thread.start_new_thread ( function, args[, kwargs] ) # # 参数说明: # # function - 线程函数。 # args - 传递给线程函数的参数,他必须是个tuple类型。 # kwargs - 可选参数。 import _thread import time # 为线程定义一个函数 def print_time( threadName, delay): count = 0 while count < 5: time.sleep(delay) count += 1 print("%s: %s" % ( threadName, time.ctime(time.time()) )) # 创建两个线程 try: _thread.start_new_thread( print_time, ("Thread-1", 2)) _thread.start_new_thread( print_time, ("Thread-2", 4)) except: print("Error: 无法启动线程") while 1: pass
51job-autotest-framework
/51job_autotest_framework-0.3.1-py3-none-any.whl/rolling_king/jason/python/thread/_ThreadTest.py
_ThreadTest.py
#!/usr/bin/python3 # -*- coding: UTF-8 -*- # 开始学习Python线程 # Python中使用线程有两种方式:函数或者用类来包装线程对象。 # threading 模块 # threading 模块除了包含 _thread 模块中的所有方法外,还提供的其他方法: # # threading.currentThread(): 返回当前的线程变量。 # threading.enumerate(): 返回一个包含正在运行的线程的list。正在运行指线程启动后、结束前,不包括启动前和终止后的线程。 # threading.activeCount(): 返回正在运行的线程数量,与len(threading.enumerate())有相同的结果。 # # 除了使用方法外,线程模块同样提供了Thread类来处理线程,Thread类提供了以下方法: # # run(): 用以表示线程活动的方法。 # start():启动线程活动。 # join([time]): 等待至线程中止。这阻塞调用线程直至线程的join() 方法被调用中止-正常退出或者抛出未处理的异常-或者是可选的超时发生。 # isAlive(): 返回线程是否活动的。 # getName(): 返回线程名。 # setName(): 设置线程名。 # 我们可以通过直接从 threading.Thread 继承创建一个新的子类,并实例化后调用 start() 方法启动新线程,即它调用了线程的 run() 方法: import threading import time exitFlag = 0 class myThread (threading.Thread): def __init__(self, threadID, name, counter): threading.Thread.__init__(self) self.threadID = threadID self.name = name self.counter = counter def run(self): print("开始线程:" + self.name) print_time(self.name, self.counter, 5) print("退出线程:" + self.name) def print_time(threadName, delay, counter): while counter: if exitFlag: threadName.exit() time.sleep(delay) print("%s: %s" % (threadName, time.ctime(time.time()))) counter -= 1 # 创建新线程 thread1 = myThread(1, "Thread-1", 1) thread2 = myThread(2, "Thread-2", 2) # 开启新线程 thread1.start() thread2.start() thread1.join() # 让主线程暂时阻塞,以便等待thread1这个线程结束。 thread2.join() print("退出主线程") # 线程同步 # 线程锁 threadLock = threading.Lock() # 获取锁,用于线程同步 threadLock.acquire() # 需要执行的方法 要在 acquire和release之间 # # 释放锁,开启下一个线程 threadLock.release() # 线程优先级队列( Queue)
51job-autotest-framework
/51job_autotest_framework-0.3.1-py3-none-any.whl/rolling_king/jason/python/thread/ThreadingTest.py
ThreadingTest.py
#!/usr/bin/python3 # -*- coding: utf-8 -*- # @Time : 2022/1/26 12:17 下午 # @Author : zhengyu.0985 # @FileName: __init__.py.py # @Software: PyCharm
51job-autotest-framework
/51job_autotest_framework-0.3.1-py3-none-any.whl/rolling_king/jason/python/thread/__init__.py
__init__.py
#!/usr/bin/python3 # -*- coding: UTF-8 -*- """ Excel操作 """ from openpyxl import Workbook, load_workbook from openpyxl.worksheet.worksheet import Worksheet from openpyxl.styles import * import logging logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s') # logging.basicConfig函数对日志的输出格式及方式做相关配置 logger = logging.getLogger("excel_util") class ExcelUtil(object): def __init__(self, excel_path=None, excel_sheet=None): if excel_path is None: self.wb: Workbook = Workbook(write_only=False) logger.info("默认创建一个空workbook。") self.ws: Worksheet = self.wb.active logger.info("默认worksheet={0}。".format(self.ws)) else: self.wb: Workbook = load_workbook(filename=excel_path) if excel_sheet is not None: self.ws: Worksheet = self.wb[excel_sheet] logger.info("加载{0}文件的{1}表单。".format(excel_path, excel_sheet)) else: logger.info("加载{0}文件。".format(excel_path)) @property def rows(self): return self.ws.max_row @property def cols(self): return self.ws.max_column @property def cell(self, cell_name): self.cell = self.ws[cell_name] return self.cell @property def cell(self, row, col): self.cell = self.ws.cell(row, col) return self.cell def set_cell_value(self, content): self.cell.value = content def set_cell_value_by_cell_name(self, cell_name, content): self.ws[cell_name] = content def set_cell_value(self, row, col, content): self.ws.cell(row, col).value = content def get_cell_value_by_cell_name(self, cell_name): return self.ws[cell_name].value def get_cell_value(self, row, col): return self.ws.cell(row, col).value def change_active_sheet(self, index): self.wb._active_sheet_index = index def save(self, save_path): self.wb.save(save_path) def get_sheet_list(self) -> list: return self.wb.get_sheet_names() def get_sheet(self, sheet_name: str): self.ws: Worksheet = self.wb.get_sheet_by_name(sheet_name) if __name__ == '__main__': excelOperator = ExcelUtil(excel_path="../crawler/Temp.xlsx", excel_sheet="Records") logger.info(excelOperator.rows)
51job-autotest-framework
/51job_autotest_framework-0.3.1-py3-none-any.whl/rolling_king/jason/openpyxl/excel_util.py
excel_util.py
#!/usr/bin/python3 # -*- coding: UTF-8 -*- import pytest # in or below the directory where conftest.py is located # 若加上scope,则代码在某scope范围内,该fixture被调用多次的情况下,仅执行一次。创建一个share_fixture_func object实例。 # Fixtures are created when first requested by a test, and are destroyed based on their scope @pytest.fixture(scope="module") def share_fixture_func(): print("This is shared fixture") # Pytest only caches one instance of a fixture at a time, which means that when using a parametrized fixture, pytest may invoke a fixture more than once in the given scope.
51job-autotest-framework
/51job_autotest_framework-0.3.1-py3-none-any.whl/rolling_king/jason/pytest/conftest.py
conftest.py
#!/usr/bin/python3 # -*- coding: UTF-8 -*- import pytest # make sure to prefix your class with Test # it finds both test_ prefixed functions. class TestPytest(object): def test_one(self): x = "this" assert "h" in x def test_two(self): x = "hello" assert hasattr(x, "check") # pytest -k test_one test_class.py # 匹配的范围是文件名、类名、函数名为变量,用and来区分, 例:pytest -k "test_ and not test_two" test_class.py # 测试执行前,pytest会为每个测试创建独立的唯一的临时路径。 def test_needsfiles(tmpdir): print("tmpdir=", tmpdir) assert 0 @pytest.fixture def fix_func(self): print("fix_func has been called.") def test_fix_func(self, fix_func): # fix_func作为方法参数,会发现是一个被@pytest.fixture装饰器修饰的方法,则先执行。 print("test_fix_func has been called.") assert 0 # conftest.py: sharing fixture functions # The discovery of fixture functions starts at test classes, then test modules, then conftest.py files and finally builtin and third party plugins def test_share_fixture(self, share_fixture_func): print("test_share_fixture test case.") assert 0 def test_share_fixture1(self, share_fixture_func): # share_fixture_func即便在该module下被调用两次,但其定义处加上scope=module,则在module范围内也只执行一次。 print("test_share_fixture1 test case.") assert 0 # Sharing test data if __name__ == "__main__": pytest.main(["-s", "test_class.py"])
51job-autotest-framework
/51job_autotest_framework-0.3.1-py3-none-any.whl/rolling_king/jason/pytest/test_class.py
test_class.py
#!/usr/bin/python3 # -*- coding: UTF-8 -*- # pytest will run all files of the form test_*.py or *_test.py in the current directory and its subdirectories. import pytest def func(x): return x + 1 def test_answer(): assert func(3) == 5 def f(): raise SystemExit(1) def test_mytest(): with pytest.raises(SystemExit): f() # The -q/--quiet flag keeps the output brief in this and following examples.
51job-autotest-framework
/51job_autotest_framework-0.3.1-py3-none-any.whl/rolling_king/jason/pytest/test_sample.py
test_sample.py
#!/usr/bin/python3 # -*- coding: utf-8 -*- # @Time : 2022/1/26 12:17 下午 # @Author : zhengyu.0985 # @FileName: __init__.py.py # @Software: PyCharm
51job-autotest-framework
/51job_autotest_framework-0.3.1-py3-none-any.whl/rolling_king/jason/pytest/__init__.py
__init__.py
#!/usr/bin/python3 # -*- coding: utf-8 -*- # @Time : 2022/10/21 10:43 AM # @Author : zhengyu.0985 # @FileName: crawler_weibo.py # @Software: PyCharm import requests from requests import Response import re import datetime from concurrent.futures import ThreadPoolExecutor, as_completed from bs4 import BeautifulSoup from openpyxl import Workbook import logging logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s') # logging.basicConfig函数对日志的输出格式及方式做相关配置 logger = logging.getLogger('rolling_king.jason.crawler.crawler_weibo') # 微博热搜 class WeiBoCollection(object): headers = { "accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9", "user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/106.0.0.0 Safari/537.36", "cookie": "" } def __init__(self, cookie_val): self.headers['cookie'] = cookie_val self.host_url = 'https://s.weibo.com/weibo' self.content_url = self.host_url self.wb = Workbook() # 获取微博热搜 def get_hot_query_by_key(self, key: str) -> Response: hot_resp = requests.get(url="https://weibo.com/ajax/side/search?q="+key, headers={ "user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/106.0.0.0 Safari/537.36"} ) logger.info(f'微博热搜={hot_resp.json()}') return hot_resp # 微博内容 def get_weibo_html_content_by_key(self, key: str) -> str: self.content_url = self.host_url+'?q=' + key + '&nodup=1' # nodup=1代表查看微博全部结果 content_resp = requests.get(url=self.content_url, headers=self.headers) print(content_resp.encoding) # ISO-8859-1 print(content_resp.apparent_encoding) # GB2312 # content_resp.encoding = content_resp.apparent_encoding # print(content_resp.content) # bytes # print(content_resp.text) # str return content_resp.text # html_doc def get_total_page_num(self, html_doc: str = None) -> int: soup = BeautifulSoup(html_doc, "lxml") print(type(soup)) # print(soup.find('a', class_='pagenum').text) ul_tag = soup.find('ul', attrs={'action-type': 'feed_list_page_morelist'}) print(f'ul_tag={ul_tag}') page_num: int = len(ul_tag.find_all('li')) print('length=', page_num) return page_num def collect_func(self, curr_page: int) -> dict: print(f'current page = {curr_page}') curr_url = self.content_url + '&page=' + str(curr_page) print(f'current url = {curr_url}') curr_resp = requests.get(url=curr_url, headers=self.headers) curr_html_doc = curr_resp.text curr_soup = BeautifulSoup(curr_html_doc, "lxml") # from_results = curr_soup.find_all('div', class_='from') # print(len(from_results)) results = curr_soup.find_all('p', class_='txt', attrs={'node-type': 'feed_list_content'}) # results = curr_soup.find_all('p', class_='txt', attrs={'node-type': 'feed_list_content_full'}) print(len(results)) print(type(results)) print(results) count: int = 0 curr_dict = { 'content': [] } for item in results: count += 1 print(type(item)) print(item.name) # p print(f"微博名={item['nick-name']}") # 微博名 print(f'微博内容={item.text.strip()}') # 微博内容 regex = re.compile(r'#.*?#') s = regex.search(item.text.strip()) topic: str = '' if s is not None: print(f'话题={s.group()}') topic = s.group() curr_dict['content'].append({ '微博名': item['nick-name'], '微博话题': topic, '微博内容': item.text.strip(), }) print(f'--- 第{curr_page}页的{count}记录已获取 ---') curr_dict['count'] = count return curr_dict def save_weibo_content(self, page_num: int, key: str): thread_pool = ThreadPoolExecutor(page_num) thread_task_list = [] for page in range(1, page_num+1): thread_task_list.append(thread_pool.submit(self.collect_func, page)) print(self.wb.sheetnames) print(self.wb.active) ws = self.wb.active ws.title = key ws.cell(1, 1).value = '微博名' ws.cell(1, 2).value = '微博话题' ws.cell(1, 3).value = '微博内容' total_count = 0 curr_row = 2 for future in as_completed(thread_task_list): print(future.result()) total_count += future.result()['count'] # 存入Excel # 将一页的结果存入 for dict_val in future.result()['content']: curr_col = 1 ws.cell(curr_row, curr_col).value = dict_val['微博名'] curr_col += 1 ws.cell(curr_row, curr_col).value = dict_val['微博话题'] curr_col += 1 ws.cell(curr_row, curr_col).value = dict_val['微博内容'] curr_row += 1 # 一页的结果存完,从下一行存下一页的结果。 print(f'{page_num}页,一共{total_count}条记录') def save_weibo_hot_query(self, hot_resp, key: str): ws = self.wb.create_sheet(title='热搜_' + key) if hot_resp.json()['ok'] == 1: hot_query_json_list = hot_resp.json()['data']['hotquery'] if len(hot_query_json_list) > 0: key_list = hot_query_json_list[0].keys() curr_col = 1 for col_head in key_list: ws.cell(1, curr_col).value = col_head curr_col += 1 curr_row = 2 for hot_query_json_item in hot_query_json_list: curr_col = 1 for col_key in key_list: ws.cell(curr_row, curr_col).value = hot_query_json_item[col_key] curr_col += 1 curr_row += 1 else: print(f'hot_query_json_list is empty.') else: print(f'hot_resp is not ok.') def save_excel_to_disk(self, file_name: str) -> None: self.wb.save(file_name) if __name__ == '__main__': cookie_value: str = "XSRF-TOKEN=vH8eCkgP-JmRtN2Ia3VIZzNL; _s_tentry=weibo.com; Apache=8524959161901.953.1666270664916; SINAGLOBAL=8524959161901.953.1666270664916; ULV=1666270664920:1:1:1:8524959161901.953.1666270664916:; login_sid_t=b5127687703bbdcf584d351ad19bb4b4; cross_origin_proto=SSL; SSOLoginState=1666324094; SCF=ApUmMbNmgFup8JyPq2IgXMlCgCtSeadR43NF9Z6NG0KDyxJmqoy-q1BssnHP28j1ZKJlwOhyLRZzMNmw1cJ-FiM.; SUB=_2A25OUZ7RDeRhGedJ6VcV-SrLyDyIHXVtJvcZrDV8PUNbmtANLVr5kW9NVlLIFhGf5-a2Sp9qM7dSRByY1wlD_sSP; SUBP=0033WrSXqPxfM725Ws9jqgMF55529P9D9WW7wgizECTwskArQ2OMHFNw5JpX5KMhUgL.Fo2Neo-X1KBNe052dJLoIE-LxKnLB.-LB.xWi--4iKn0iK.pi--fi-z7iKysi--4iKn0iK.p; ALF=1698112000; WBPSESS=fbOmJTuMY3c-5Rw73SivynCCuNFzmQGVExuu7n6msq-AjXm4uN--xLuIUTml8RhJDN_nrrqPS1nQ2NIMyMdVyNKkaKtQladJWypSdM_rIwgLWcjOOCCCyt2nzPJT3IGPbG6yCmzbwCeOSpYz_m0h4g==" search_key = "南通" obj = WeiBoCollection(cookie_val=cookie_value) obj.save_weibo_content(obj.get_total_page_num(obj.get_weibo_html_content_by_key(key=search_key)), key=search_key) obj.save_weibo_hot_query(obj.get_hot_query_by_key(key=search_key), key=search_key) obj.save_excel_to_disk(file_name='WeiBo_'+datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')+'.xlsx')
51job-autotest-framework
/51job_autotest_framework-0.3.1-py3-none-any.whl/rolling_king/jason/crawler/crawler_weibo.py
crawler_weibo.py
#!/usr/bin/python3 # -*- coding: utf-8 -*- # @Time : 2022/10/24 5:42 PM # @Author : zhengyu.0985 # @FileName: TempBaidu.py # @Software: PyCharm import requests from bs4 import BeautifulSoup fileObj = open("/Users/admin/Desktop/baidu.html", mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None) print("文件名: ", fileObj.name) print("是否已关闭 : ", fileObj.closed) print("访问模式 : ", fileObj.mode) str_list = fileObj.readlines() val = '' for curr in str_list: val += curr # print(val) soup = BeautifulSoup(val, "lxml") print(type(soup)) # print(soup.find('a', class_='pagenum').text) div_tag = soup.find('div', attrs={'class': ['c-row', 'content-wrapper_1SuJ0']}) print('-------------------') print(f'div_tag={div_tag}') # page_num: int = len(ul_tag.find_all('li')) cookie = "BIDUPSID=4A1485563FA4A8F48BBA72A0DE6C86DD; PSTM=1666270645; BAIDUID=4A1485563FA4A8F4BC48518904109E08:FG=1; BD_UPN=123253; MCITY=-75:; BDORZ=B490B5EBF6F3CD402E515D22BCDA1598; H_PS_PSSID=36548_37358_37299_36885_37628_36807_36789_37540_37499_26350; BAIDUID_BFESS=4A1485563FA4A8F4BC48518904109E08:FG=1; delPer=0; BD_CK_SAM=1; PSINO=2; BA_HECTOR=0g85000la50k252l0424dqlu1hlcni51b; ZFY=6deFW77nFLKhW:A5JxO6akg7YzaDrDvStePnOta1Ka3U:C; H_PS_645EC=c8e7bAhaJW/MO9zWkp/H2nIXr8Xy3k5JAZTecHXru40trcMBk/SJguwj7SY; COOKIE_SESSION=3_0_8_9_5_17_0_1_7_6_1_3_28_0_2_0_1666604643_0_1666604641|9#0_0_1666604641|1; BDSVRTM=0; WWW_ST=1666605811625" url_str = "https://www.baidu.com/s?rtt=1&bsst=1&cl=2&tn=news&ie=utf-8&word=%E5%8D%97%E9%80%9A&x_bfe_rqs=03E80&x_bfe_tjscore=0.100000&tngroupname=organic_news&newVideo=12&goods_entry_switch=1&rsv_dl=news_b_pn&pn=10" # url_str = "https://www.baidu.com/s?ie=utf-8&medium=0&rtt=1&bsst=1&rsv_dl=news_t_sk&cl=2&wd=%E5%8D%97%E9%80%9A&tn=news&rsv_bp=1&rsv_sug3=1&rsv_sug1=2&rsv_sug7=100&rsv_sug2=0&oq=&rsv_btype=t&f=8&rsv_sug4=918&rsv_sug=1" headers = { "accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9", "user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/106.0.0.0 Safari/537.36", "cookie": "", # "Host": "www.baidu.com" # "Referer": "https://www.baidu.com/s?rtt=1&bsst=1&cl=2&tn=news&ie=utf-8&word=南通&x_bfe_rqs=03E80&x_bfe_tjscore=0.100000&tngroupname=organic_news&newVideo=12&goods_entry_switch=1&rsv_dl=news_b_pn&pn=10" } headers['cookie'] = cookie resp = requests.get(url=url_str, headers=headers) print(resp.text)
51job-autotest-framework
/51job_autotest_framework-0.3.1-py3-none-any.whl/rolling_king/jason/crawler/TempBaidu.py
TempBaidu.py
#!/usr/bin/python3 # -*- coding: UTF-8 -*- from openpyxl import Workbook, load_workbook from openpyxl.styles import * # 爬取城市肯德基餐厅的位置信息 http://www.kfc.com.cn/kfccda/storelist/index.aspx """ 抓包获取的数据 Request URL: http://www.kfc.com.cn/kfccda/ashx/GetStoreList.ashx?op=keyword Request Method: POST Status Code: 200 OK Remote Address: 120.92.131.8:80 Referrer Policy: no-referrer-when-downgrade """ import requests import json url = 'http://www.kfc.com.cn/kfccda/ashx/GetStoreList.ashx?op=keyword' headers = { 'user-agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.20 Safari/537.36' } ############## city = input('input a city:') data = { 'cname': '', 'pid': '', 'keyword': city, 'pageIndex': 0, 'pageSize': 10, } response = requests.post(url=url, headers=headers, data=data) print(response.json()) jsonVal = response.json() listVal = jsonVal['Table'] print("列表长度={0}".format(len(listVal))) for item in listVal: numb = item['rowcount'] data = { 'cname': '', 'pid': '', 'keyword': city, 'pageIndex': 1, 'pageSize': numb, } response = requests.post(url=url, headers=headers, data=data) jsonVal = response.json() print(jsonVal) cols = len(jsonVal['Table1'][0]) print("字段个数=", cols) wb = Workbook() # ws = wb.create_sheet("Record") print(wb.sheetnames) print(wb.active) ws = wb.active ws.title = "Records" currRow = 1 currCol = 0 for key in jsonVal['Table1'][0].keys(): print(key, end=",") currCol = currCol + 1 ws.cell(currRow, currCol).value = key print() for jsonItem in jsonVal['Table1']: currRow = currRow + 1 currCol = 0 for val in jsonItem.values(): print(val, end=',') currCol = currCol + 1 ws.cell(currRow, currCol).value = val print() # for jsonItem in jsonVal['Table1']: # print("---------------------") # for k, v in jsonItem.items(): # print(k, "=", v) wb.save("Temp.xlsx")
51job-autotest-framework
/51job_autotest_framework-0.3.1-py3-none-any.whl/rolling_king/jason/crawler/crawler_urllib.py
crawler_urllib.py
#!/usr/bin/python3 # -*- coding: utf-8 -*- # @Time : 2022/1/11 2:39 下午 # @Author : zhengyu.0985 # @FileName: auto_generate.py # @Software: PyCharm # 格式化符替代 template1 = "1、hello %s , your website is %s " % ("Jason", "http://www.baidu.com") # format函数 template2 = "2、hello {0} , your website is {1} ".format("Jason", "http://www.baidu.com") # 字符串命名格式化符 template3 = "3、hello %(name)s , your website is %(msg)s " % {"name": "Jason", "msg": "http://www.baidu.com"} template4 = "4、hello %(name)s , your website is %(msg)s " % ({"name": "Jason", "msg": "http://www.baidu.com"}) # format函数 template5 = "5、hello {name} , your website is {msg} ".format(name="Jason", msg="http://www.baidu.com") # 模版方法替换:使用string中的Template方法; from string import Template my_template = Template("hello ${name} , your website is ${msg} ") result = my_template.substitute(name="Jason", msg="http://www.baidu.com") if __name__ == "__main__": print(template1) print(template2) print(template3) print(template4) print(template5) print("*******") print(type(result)) print(result)
51job-autotest-framework
/51job_autotest_framework-0.3.1-py3-none-any.whl/rolling_king/jason/autogen/auto_generate.py
auto_generate.py
#!/usr/bin/python3 # -*- coding: utf-8 -*- # @Time : 2022/1/11 2:38 下午 # @Author : zhengyu.0985 # @FileName: __init__.py.py # @Software: PyCharm
51job-autotest-framework
/51job_autotest_framework-0.3.1-py3-none-any.whl/rolling_king/jason/autogen/__init__.py
__init__.py
#!/usr/bin/python3 # -*- coding: UTF-8 -*- from src.rolling_king.jason.requests.http_sender_module import HttpSender import json import pytest class TestCCCPlatform(object): def test_get(self): http_sender_obj = HttpSender("http://10.72.108.71:8080/") HttpSender.headers = {"header": "This is a customerized header"} input_param = {"groupName": "XY_CCC_GROUP"} http_sender_obj.send_get_request_by_suburi("meta/application.json", input_param) result_str = http_sender_obj.get_response.text print("结果:", result_str) dict_val = json.loads(result_str) print(type(dict_val)) # <class 'dict'> print(json.dumps(dict_val, indent=2)) if "msg" in dict_val: msg_val = dict_val['msg'] print("msg_val = {0}".format(msg_val)) if msg_val == "success": assert 1 else: assert 0 else: assert 0 if __name__ == "__main__": pytest.main(["-s", "test_ccc.py"])
51job-autotest-framework
/51job_autotest_framework-0.3.1-py3-none-any.whl/rolling_king/jason/newcore/test_ccc.py
test_ccc.py
#!/usr/bin/python3 # -*- coding: utf-8 -*- # @Time : 2022/4/2 10:37 AM # @Author : zhengyu.0985 # @FileName: conftest.py # @Software: PyCharm import pytest def pytest_addoption(parser): print("pytest_addoption func executes...") parser.addoption( "--cmdopt", action="store", default="type1", help="my option: type1 or type2" ) parser.addoption( "--env", action="store", default="dev", choices=['dev', 'test'], type=str, help="env:表示测试环境,默认dev环境" ) # @pytest.fixture(scope="module") # def cmdopt(pytestconfig): # return pytestconfig.getoption("cmdopt") @pytest.fixture(scope="module") def cmdopt(request): return request.config.getoption("--cmdopt") @pytest.fixture(scope="module") def env(request): print("execute...") return request.config.getoption("--env")
51job-autotest-framework
/51job_autotest_framework-0.3.1-py3-none-any.whl/tests/conftest.py
conftest.py
#!/usr/bin/python3 # -*- coding: utf-8 -*- # @Time : 2022/8/20 8:19 PM # @Author : zhengyu.0985 # @FileName: upload_file_test.py # @Software: PyCharm import pytest import requests class TestUploadFile(object): # def test_upload_file_by_form_data(self): # host_url = "XXX" # sub_uri = "xx/xx/xx" # data = { # "modelId": 10, # "file": "MODEL.xlsx" # } # files = { # "file": open("/Users/zy/Desktop/MODEL.xlsx", "rb") # } # headers = { # "token": "token_value", # "currentId": "5", # } # requests.request("POST", host_url+sub_uri, headers=headers, data=data, files=files) # 下面这个测试用例是我自己springboot服务的上传接口仅用于测试验证。 def test_my_upload_file_by_form_data(self): host_url = "http://127.0.0.1:8082" sub_uri = "/upload" file_obj = open("/Users/admin/Desktop/Empty.xlsx", mode='rb', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None) data = { # data里这两种写法均可。 "uploadFile": "/Users/admin/Desktop/Empty.xlsx" # "uploadFile": file_obj } files = { "uploadFile": open("/Users/admin/Desktop/Empty.xlsx", "rb") } headers = { "token": "token_value", "currentId": "5", } requests.post(host_url+sub_uri, headers=headers, data=data, files=files) if __name__ == '__main__': pytest.main(["-s", "upload_file_test.py"])
51job-autotest-framework
/51job_autotest_framework-0.3.1-py3-none-any.whl/tests/upload_file_test.py
upload_file_test.py
#!/usr/bin/python3 # -*- coding: utf-8 -*- # @Time : 2022/4/2 10:41 AM # @Author : zhengyu.0985 # @FileName: test_options.py # @Software: PyCharm import pytest import os def test_option(env): if env == 'dev': print("当前测试环境为:{},域名切换为开发环境".format(env)) elif env == 'test': print("当前测试环境为:{},域名切换为测试环境".format(env)) else: print("环境错误,当前环境{}不存在".format(env)) def test_param(cmdopt): print("current path={}".format(os.getcwd())) print(cmdopt) if __name__ == '__main__': # pytest.main(['-s', './src/tests/test_options.py', '--env=test']) pytest.main(['-s', '--cmdopt=abc', '--env=test', 'test_options.py'])
51job-autotest-framework
/51job_autotest_framework-0.3.1-py3-none-any.whl/tests/test_options.py
test_options.py
#!/usr/bin/python3 # -*- coding: utf-8 -*- # @Time : 2022/4/2 11:22 AM # @Author : zhengyu.0985 # @FileName: __init__.py.py # @Software: PyCharm
51job-autotest-framework
/51job_autotest_framework-0.3.1-py3-none-any.whl/tests/__init__.py
__init__.py
#!/usr/bin/python3 # -*- coding: utf-8 -*- # @Time : 2022/5/30 8:00 下午 # @Author : zhengyu.0985 # @FileName: excel_test.py # @Software: PyCharm from src.rolling_king.jason.openpyxl.excel_util import ExcelUtil def get_json(): excel_obj = ExcelUtil(excel_path="/Users/admin/Downloads/CICD.xlsx", excel_sheet="2") print(excel_obj.rows) sample_dict = { "business_name": "企业经营", "second_business_name": "", "bytetree_node": [], "drop_psm": [] } cat_dict = { } # for i in range(1, excel_obj.rows): for i in range(60, 87): # 不包括87,左闭右开。 val = excel_obj.get_cell_value(row=i, col=10) print(i, "=", val) if val == "Faas" or val == "Cronjob": dir_name = excel_obj.get_cell_value_by_cell_name(cell_name="{}{}".format("D", str(i))) point_id = excel_obj.get_cell_value_by_cell_name(cell_name="{}{}".format("E", str(i))) print("dir_name={}, point_id={}".format(dir_name, point_id)) if dir_name in cat_dict.keys(): cat_dict[dir_name].append(str(point_id)) else: cat_dict[dir_name] = [str(point_id)] print(cat_dict) result_list = [] for k, v in cat_dict.items(): curr_dict = { "business_name": "企业经营", "second_business_name": k, "bytetree_node": v, "drop_psm": [] } result_list.append(curr_dict) print(result_list) if __name__ == '__main__': get_json()
51job-autotest-framework
/51job_autotest_framework-0.3.1-py3-none-any.whl/tests/excel/excel_test.py
excel_test.py
#!/usr/bin/python3 # -*- coding: utf-8 -*- # @Time : 2022/5/30 8:00 下午 # @Author : zhengyu.0985 # @FileName: __init__.py.py # @Software: PyCharm
51job-autotest-framework
/51job_autotest_framework-0.3.1-py3-none-any.whl/tests/excel/__init__.py
__init__.py
from distutils.core import setup setup( name='51pub_pymodules', version='0.0.1', author='jun', author_email='jun.mr@qq.com', url='http://docs.51pub.cn/python/51pub_pymodules', packages=['opmysql'], description='system manage modules', license='MIT', install_requires=['pymysql'] )
51pub_pymodules
/51pub_pymodules-0.0.1.tar.gz/51pub_pymodules-0.0.1/setup.py
setup.py
import pymysql import time import os import subprocess import logging __all__ = ["PyMysqlDB"] logging.basicConfig(level=logging.DEBUG, format='%(asctime)s [%(levelname)s] %(funcName)s: %(message)s', datefmt="%d %b %Y %H:%M:%S") class PyMysqlDB: def __init__(self, host=None, user=None, pwd=None, port=3306, base_path=None, backup_path='/data/LocalBackup'): self.host = host self.user = user self.pwd = pwd self.port = int(port) self.base_path = base_path self.backup_path = backup_path def select_database(self): db_list = [] con = pymysql.connect(host=self.host, user=self.user, password=self.pwd, db='information_schema', port=self.port) cur = con.cursor() cur.execute('select SCHEMA_NAME from SCHEMATA') for (db,) in cur.fetchall(): db_list.append(db) return db_list def backup_by_database(self, database): logging.info('backup database: {}'.format(database)) today = time.strftime("%Y%m%d", time.localtime()) backup_dir = '{}/{}'.format(self.backup_path, today) if not os.path.isdir(backup_dir): os.makedirs(backup_dir) os.chdir(backup_dir) start_time = int(time.time()) cmd = "{}/bin/mysqldump --opt -h{} -P{} -u{} -p{} {} | gzip > {}/{}/{}-{}-{}.sql.gz".format(self.base_path, self.host, self.port, self.user, self.pwd, database, self.backup_path, today, today, self.host, database) result = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) content = result.stdout.read() if content and not content.decode().startswith("Warning:"): subject = "{} - {} backup error, reason: {}".format(self.host, database, content.decode()) logging.error(subject) end_time = int(time.time()) use_time = end_time - start_time logging.info('{} - {} backup finished, use time: {}s'.format(self.host, database, float('%.2f' % use_time))) def backup_by_table(self): pass def backup_all(self, **kwargs): exclude_db = kwargs.get('exclude_db', []) db_list = [val for val in self.select_database() if val not in exclude_db] logging.info('db_list: {}'.format(db_list)) for db in db_list: self.backup_by_database(db) logging.info('{} backup all finished'.format(self.host))
51pub_pymodules
/51pub_pymodules-0.0.1.tar.gz/51pub_pymodules-0.0.1/opmysql/mysqldb.py
mysqldb.py
import setuptools with open("README.md", "r") as fh: long_description = fh.read() setuptools.setup( name="51spiders", # 包的分发名称,使用字母、数字、_、- version="0.0.1", # 版本号, 版本号规范:https://www.python.org/dev/peps/pep-0440/ author="Orientaldi", # 作者名字 author_email="yfABO05@163.com", # 作者邮箱 description="51 bigdataspiders", # 包的简介描述 long_description=long_description, # 包的详细介绍(一般通过加载README.md) long_description_content_type="text/markdown", # 和上条命令配合使用,声明加载的是markdown文件 url="https://github.com/", # 项目开源地址 packages=setuptools.find_packages(), # 如果项目由多个文件组成,我们可以使用find_packages()自动发现所有包和子包,而不是手动列出每个包,在这种情况下,包列表将是example_pkg classifiers=[ # 关于包的其他元数据(metadata) "Programming Language :: Python :: 3", # 该软件包仅与Python3兼容 "License :: OSI Approved :: MIT License", # 根据MIT许可证开源 "Operating System :: OS Independent", # 与操作系统无关 ], install_requires=['pymysql>=0.10.0', 'retrying==1.3.3', 'xlrd>=1.2.0', 'openpyxl>=3.0.5'], # 依赖的包 python_requires='>=3' )
51spiders
/51spiders-0.0.1.tar.gz/51spiders-0.0.1/setup.py
setup.py
# -*- coding:utf-8 -*- import urllib.request import xlwt import re import urllib.parse import time header={ 'Host':'search.51job.com', 'Upgrade-Insecure-Requests':'1', 'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36' } def getfront(page,item): #page是页数,item是输入的字符串 result = urllib.parse.quote(item) #先把字符串转成十六进制编码 ur1 = result+',2,'+ str(page)+'.html' ur2 = 'https://search.51job.com/list/000000,000000,0000,00,9,99,' res = ur2+ur1 #拼接网址 a = urllib.request.urlopen(res) html = a.read().decode('gbk') # 读取源代码并转为unicode html = html.replace('\\','') # 将用于转义的"\"替换为空 html = html.replace('[', '') html = html.replace(']', '') #print(html) return html def getInformation(html): reg = re.compile(r'"type":"engine_jds".*?"job_href":"(.*?)","job_name":"(.*?)".*?"company_href":"(.*?)","company_name":"(.*?)","providesalary_text":"(.*?)".*?"updatedate":"(.*?)".*?,' r'"companytype_text":"(.*?)".*?"jobwelf":"(.*?)".*?"attribute_text":"(.*?)","(.*?)","(.*?)","(.*?)","companysize_text":"(.*?)","companyind_text":"(.*?)"',re.S)#匹配换行符 items=re.findall(reg,html) print(items) return items def main(): #新建表格空间 excel1 = xlwt.Workbook() # 设置单元格格式 sheet1 = excel1.add_sheet('Job', cell_overwrite_ok=True) sheet1.write(0, 0, '序号') sheet1.write(0, 1, '职位') sheet1.write(0, 2, '公司名称') sheet1.write(0, 3, '公司地点') sheet1.write(0, 4, '公司性质') sheet1.write(0, 5, '薪资') sheet1.write(0, 6, '学历要求') sheet1.write(0, 7, '工作经验') sheet1.write(0, 8, '公司规模') #sheet1.write(0, 9, '公司类型') sheet1.write(0, 9,'公司福利') sheet1.write(0, 10,'发布时间') number = 1 item = input("请输入需要搜索的职位:") #输入想搜索的职位关键字 for j in range(1,33): #页数自己随便改 try: print("正在爬取第"+str(j)+"页数据...") html = getfront(j,item) #调用获取网页原码 for i in getInformation(html): try: sheet1.write(number,0,number) sheet1.write(number,1,i[1]) sheet1.write(number,2,i[3]) sheet1.write(number,3,i[8]) sheet1.write(number,4,i[6]) sheet1.write(number,5,i[4]) sheet1.write(number,6,i[10]) sheet1.write(number,7,i[9]) sheet1.write(number,8,i[12]) #sheet1.write(number,9,i[7]) sheet1.write(number,9,i[7]) sheet1.write(number,10,i[5]) number+=1 excel1.save("51job.xls") time.sleep(0.3) #休息间隔,避免爬取海量数据时被误判为攻击,IP遭到封禁 except: pass except: pass if __name__ == '__main__': main() ###################################数据清洗####################################### #coding:utf-8 import pandas as pd import re #读取表格内容到data data = pd.read_excel(r'51job.xls',sheet_name='Job') result = pd.DataFrame(data) a = result.dropna(axis=0,how='any') pd.set_option('display.max_rows',None) #输出全部行,不省略 #清洗职位中的异常数据 b = u'数据' number = 1 li = a['职位'] for i in range(0,len(li)): try: if b in li[i]: #print(number,li[i]) number+=1 else: a = a.drop(i,axis=0) #删除整行 except: pass #清洗学历要求的异常数据 b2 = '人' li2 = a['学历要求'] for i in range(0,len(li2)): try: if b2 in li2[i]: # print(number,li2[i]) number += 1 a = a.drop(i, axis=0) except: pass #转换薪资单位 b3 =u'万/年' b4 =u'千/月' li3 = a['薪资'] #注释部分的print都是为了调试用的 for i in range(0,len(li3)): try: if b3 in li3[i]: x = re.findall(r'\d*\.?\d+',li3[i]) #print(x) min_ = format(float(x[0])/12,'.2f') #转换成浮点型并保留两位小数 max_ = format(float(x[1])/12,'.2f') li3[i][1] = min_+'-'+max_+u'万/月' if b4 in li3[i]: x = re.findall(r'\d*\.?\d+',li3[i]) #print(x) #input() min_ = format(float(x[0])/10,'.2f') max_ = format(float(x[1])/10,'.2f') li3[i][1] = str(min_+'-'+max_+'万/月') print(i,li3[i]) except: pass #保存成另一个excel文件 a.to_excel('51job2.xlsx', sheet_name='Job', index=False) ########################################数据可视化################################################ import pandas as pd import re from pyecharts.charts import Funnel,Pie,Geo import matplotlib.pyplot as plt from pyecharts import options as opts from pyecharts.datasets import register_url file = pd.read_excel(r'51job2.xlsx',sheet_name='Job') f = pd.DataFrame(file) pd.set_option('display.max_rows',None) add = f['公司地点'] sly = f['薪资'] edu = f['学历要求'] exp = f['工作经验'] address =[] salary = [] education = [] experience = [] for i in range(0,len(f)): try: a = add[i].split('-') address.append(a[0]) #print(address[i]) s = re.findall(r'\d*\.?\d+',sly[i]) s1= float(s[0]) s2 =float(s[1]) salary.append([s1,s2]) #print(salary[i]) education.append(edu[i]) #print(education[i]) experience.append(exp[i]) #print(experience[i]) except: pass min_s=[] #定义存放最低薪资的列表 max_s=[] #定义存放最高薪资的列表 for i in range(0,len(experience)): min_s.append(salary[i][0]) max_s.append(salary[i][0]) plt.rcParams['font.sans-serif'] = ['KaiTi'] # 指定默认字体 plt.rcParams['axes.unicode_minus'] = False # 解决保存图像是负号'-'显示为方块的问题 my_df = pd.DataFrame({'experience':experience, 'min_salay' : min_s, 'max_salay' : max_s}) #关联工作经验与薪资 data1 = my_df.groupby('experience').mean()['min_salay'].plot(kind='line') plt.show() my_df2 = pd.DataFrame({'education':education, 'min_salay' : min_s, 'max_salay' : max_s}) #关联学历与薪资 data2 = my_df2.groupby('education').mean()['min_salay'].plot(kind='line') plt.show() def get_edu(list): education2 = {} for i in set(list): education2[i] = list.count(i) return education2 dir1 = get_edu(education) attr= dir1.keys() value = dir1.values() c = ( Pie() .add( "", [list(z) for z in zip(attr, value)], radius=["40%", "75%"], ) .set_global_opts( title_opts=opts.TitleOpts(title="Pie-Radius"), legend_opts=opts.LegendOpts(orient="vertical", pos_top="15%", pos_left="2%"), ) .set_series_opts(label_opts=opts.LabelOpts(formatter="{b}: {c}")) .render("学历要求玫瑰图.html") ) def get_address(list): address2 = {} for i in set(list): address2[i] = list.count(i) try: address2.pop('异地招聘') except: pass return address2 dir2 = get_address(address) attr2 = dir2.keys() value2 = dir2.values() c = ( Geo() .add_schema(maptype="china") .add("geo", [list(z) for z in zip(attr2, value2)]) .set_series_opts(label_opts=opts.LabelOpts(is_show=False)) .set_global_opts( visualmap_opts=opts.VisualMapOpts(), title_opts=opts.TitleOpts(title="Geo-基本示例") ) .render("大数据城市需求分布图.html") ) def get_experience(list): experience2 = {} for i in set(list): experience2[i] = list.count(i) return experience2 dir3 = get_experience(experience) attr3= dir3.keys() value3 = dir3.values() c = ( Funnel() .add( "", [list(z) for z in zip(attr3, value3)], label_opts=opts.LabelOpts(position="inside"), ) .set_global_opts(title_opts=opts.TitleOpts(title="Funnel-Label(inside)")) .render("工作经验要求漏斗图.html") )
51spiders
/51spiders-0.0.1.tar.gz/51spiders-0.0.1/51/51.py
51.py
from setuptools import find_packages, setup # Package meta-data. import wu NAME = '520' DESCRIPTION = 'A daily useful kit by WU.' URL = 'https://github.com/username/wu.git' EMAIL = 'wu@foxmail.com' AUTHOR = 'WU' REQUIRES_PYTHON = '>=3.6.0' VERSION = wu.VERSION # What packages are required for this module to be executed? REQUIRED = [] # Setting. setup( name=NAME, version=VERSION, description=DESCRIPTION, author=AUTHOR, python_requires=REQUIRES_PYTHON, url=URL, packages=find_packages(), install_requires=REQUIRED, license="MIT", platforms=["all"], long_description=open('README.md', 'r', encoding='utf-8').read(), long_description_content_type="text/markdown" )
520
/520-0.0.0.tar.gz/520-0.0.0/setup.py
setup.py
import os import subprocess import time from subprocess import PIPE from urllib import parse, request import requests # TODO:找不到win32api # from win10toast import ToastNotifier def getTime(): return time.asctime( time.localtime(time.time()) ) def cmd(cmd): # 有点问题,自动输出到,还获取不了输出 # return os.system(cmd) return os.popen(cmd).read()
520
/520-0.0.0.tar.gz/520-0.0.0/wu/wy.py
wy.py
# this dir as module name,只要有__init__.py,那么那个目录就是module,比如放在上一级目录 # TODO #这里重点讨论 orbitkit 文件夹,也就是我们的核心代码文件夹。python 和 java 不一样,并不是一个文件就是一个类,在 python 中一个文件中可以写多个类。我们推荐把希望向用户暴漏的类和方法都先导入到 __init__.py 中,并且用关键词 __all__ 进行限定。下面是我的一个 __init__.py 文件。 #这样用户在使用的时候可以清楚的知道哪些类和方法是可以使用的,也就是关键词 __all__ 所限定的类和方法。 from wu import wy #另外,在写自己代码库的时候,即便我们可以使用相对导入,但是模块导入一定要从项目的根目录进行导入,这样可以避免一些在导入包的时候因路径不对而产生的问题。比如 # from orbitkit.file_extractor.dispatcher import FileDispatcher name = 'orbitkit' __version__ = '0.0.0' VERSION = __version__ __all__ = [ 'wy', ]
520
/520-0.0.0.tar.gz/520-0.0.0/wu/__init__.py
__init__.py
Mile converter package
533testgawain
/533testgawain-0.1.tar.gz/533testgawain-0.1/README.md
README.md
from setuptools import setup, find_packages setup( name='533testgawain', version='0.1', packages=find_packages(exclude=['tests*']), license='MIT', description='A test python package', url='https://github.com/khalad-hasan/myMileConverter', author='MK Hasan', author_email='khalad.hasan@gmail.com' )
533testgawain
/533testgawain-0.1.tar.gz/533testgawain-0.1/setup.py
setup.py
MILE_TO_YARD = 1760 MILE_TO_FEET = 5280 def to_yard(val): return val * MILE_TO_YARD def to_feet(val): return val * MILE_TO_FEET
533testgawain
/533testgawain-0.1.tar.gz/533testgawain-0.1/myMilePackage/mileConverter.py
mileConverter.py
from myMilePackage.mileConverter import to_yard from myMilePackage.mileConverter import to_feet
533testgawain
/533testgawain-0.1.tar.gz/533testgawain-0.1/myMilePackage/__init__.py
__init__.py
from __future__ import annotations import dataclasses import inspect import sys from typing import ( TYPE_CHECKING, Any, Awaitable, Callable, Coroutine, Dict, List, Mapping, Optional, Sequence, Type, TypeVar, Union, overload, ) from strawberry.annotation import StrawberryAnnotation from strawberry.exceptions import InvalidArgumentTypeError, InvalidDefaultFactoryError from strawberry.type import StrawberryType from strawberry.union import StrawberryUnion from strawberry.utils.cached_property import cached_property from .types.fields.resolver import StrawberryResolver if TYPE_CHECKING: import builtins from typing_extensions import Literal from strawberry.arguments import StrawberryArgument from strawberry.extensions.field_extension import FieldExtension from strawberry.types.info import Info from .object_type import TypeDefinition from .permission import BasePermission T = TypeVar("T") _RESOLVER_TYPE = Union[ StrawberryResolver[T], Callable[..., T], # we initially used Awaitable, but that was triggering the following mypy bug: # https://github.com/python/mypy/issues/14669 Callable[..., Coroutine[T, Any, Any]], "staticmethod[Any, T]", # type: ignore "classmethod[Any, Any, T]", # type: ignore ] UNRESOLVED = object() def _is_generic(resolver_type: Union[StrawberryType, type]) -> bool: """Returns True if `resolver_type` is generic else False""" if isinstance(resolver_type, StrawberryType): return resolver_type.is_generic # solves the Generic subclass case if hasattr(resolver_type, "_type_definition"): return resolver_type._type_definition.is_generic return False class StrawberryField(dataclasses.Field): type_annotation: Optional[StrawberryAnnotation] default_resolver: Callable[[Any, str], object] = getattr def __init__( self, python_name: Optional[str] = None, graphql_name: Optional[str] = None, type_annotation: Optional[StrawberryAnnotation] = None, origin: Optional[Union[Type, Callable, staticmethod, classmethod]] = None, is_subscription: bool = False, description: Optional[str] = None, base_resolver: Optional[StrawberryResolver] = None, permission_classes: List[Type[BasePermission]] = (), # type: ignore default: object = dataclasses.MISSING, default_factory: Union[Callable[[], Any], object] = dataclasses.MISSING, metadata: Optional[Mapping[Any, Any]] = None, deprecation_reason: Optional[str] = None, directives: Sequence[object] = (), extensions: List[FieldExtension] = (), # type: ignore ): # basic fields are fields with no provided resolver is_basic_field = not base_resolver kwargs: Dict[str, Any] = {} # kw_only was added to python 3.10 and it is required if sys.version_info >= (3, 10): kwargs["kw_only"] = dataclasses.MISSING super().__init__( default=default, default_factory=default_factory, # type: ignore init=is_basic_field, repr=is_basic_field, compare=is_basic_field, hash=None, metadata=metadata or {}, **kwargs, ) self.graphql_name = graphql_name if python_name is not None: self.python_name = python_name self.type_annotation = type_annotation self.description: Optional[str] = description self.origin = origin self._base_resolver: Optional[StrawberryResolver] = None if base_resolver is not None: self.base_resolver = base_resolver # Note: StrawberryField.default is the same as # StrawberryField.default_value except that `.default` uses # `dataclasses.MISSING` to represent an "undefined" value and # `.default_value` uses `UNSET` self.default_value = default if callable(default_factory): try: self.default_value = default_factory() except TypeError as exc: raise InvalidDefaultFactoryError() from exc self.is_subscription = is_subscription self.permission_classes: List[Type[BasePermission]] = list(permission_classes) self.directives = list(directives) self.extensions: List[FieldExtension] = list(extensions) self.deprecation_reason = deprecation_reason def __call__(self, resolver: _RESOLVER_TYPE) -> StrawberryField: """Add a resolver to the field""" # Allow for StrawberryResolvers or bare functions to be provided if not isinstance(resolver, StrawberryResolver): resolver = StrawberryResolver(resolver) for argument in resolver.arguments: if isinstance(argument.type_annotation.annotation, str): continue elif isinstance(argument.type, StrawberryUnion): raise InvalidArgumentTypeError( resolver, argument, ) elif getattr(argument.type, "_type_definition", False): if argument.type._type_definition.is_interface: # type: ignore raise InvalidArgumentTypeError( resolver, argument, ) self.base_resolver = resolver return self def get_result( self, source: Any, info: Optional[Info], args: List[Any], kwargs: Dict[str, Any] ) -> Union[Awaitable[Any], Any]: """ Calls the resolver defined for the StrawberryField. If the field doesn't have a resolver defined we default to using the default resolver specified in StrawberryConfig. """ if self.base_resolver: return self.base_resolver(*args, **kwargs) return self.default_resolver(source, self.python_name) @property def is_basic_field(self) -> bool: """ Flag indicating if this is a "basic" field that has no resolver or permission classes, i.e. it just returns the relevant attribute from the source object. If it is a basic field we can avoid constructing an `Info` object and running any permission checks in the resolver which improves performance. """ return ( not self.base_resolver and not self.permission_classes and not self.extensions ) @property def arguments(self) -> List[StrawberryArgument]: if not self.base_resolver: return [] return self.base_resolver.arguments def _python_name(self) -> Optional[str]: if self.name: return self.name if self.base_resolver: return self.base_resolver.name return None def _set_python_name(self, name: str) -> None: self.name = name python_name: str = property(_python_name, _set_python_name) # type: ignore[assignment] # noqa: E501 @property def base_resolver(self) -> Optional[StrawberryResolver]: return self._base_resolver @base_resolver.setter def base_resolver(self, resolver: StrawberryResolver) -> None: self._base_resolver = resolver # Don't add field to __init__, __repr__ and __eq__ once it has a resolver self.init = False self.compare = False self.repr = False # TODO: See test_resolvers.test_raises_error_when_argument_annotation_missing # (https://github.com/strawberry-graphql/strawberry/blob/8e102d3/tests/types/test_resolvers.py#L89-L98) # # Currently we expect the exception to be thrown when the StrawberryField # is constructed, but this only happens if we explicitly retrieve the # arguments. # # If we want to change when the exception is thrown, this line can be # removed. _ = resolver.arguments @property # type: ignore def type(self) -> Union[StrawberryType, type, Literal[UNRESOLVED]]: # type: ignore # We are catching NameError because dataclasses tries to fetch the type # of the field from the class before the class is fully defined. # This triggers a NameError error when using forward references because # our `type` property tries to find the field type from the global namespace # but it is not yet defined. try: # Prioritise the field type over the resolver return type if self.type_annotation is not None: return self.type_annotation.resolve() if self.base_resolver is not None: # Handle unannotated functions (such as lambdas) if self.base_resolver.type is not None: # Generics will raise MissingTypesForGenericError later # on if we let it be returned. So use `type_annotation` instead # which is the same behaviour as having no type information. if not _is_generic(self.base_resolver.type): return self.base_resolver.type # If we get this far it means that we don't have a field type and # the resolver doesn't have a return type so all we can do is return # UNRESOLVED here. # This case will raise a MissingReturnAnnotationError exception in the # _check_field_annotations function: # https://github.com/strawberry-graphql/strawberry/blob/846f060a63cb568b3cdc0deb26c308a8d0718190/strawberry/object_type.py#L76-L80 return UNRESOLVED except NameError: return UNRESOLVED @type.setter def type(self, type_: Any) -> None: # Note: we aren't setting a namespace here for the annotation. That # happens in the `_get_fields` function in `types/type_resolver` so # that we have access to the correct namespace for the object type # the field is attached to. self.type_annotation = StrawberryAnnotation.from_annotation( type_, namespace=None ) # TODO: add this to arguments (and/or move it to StrawberryType) @property def type_params(self) -> List[TypeVar]: if hasattr(self.type, "_type_definition"): parameters = getattr(self.type, "__parameters__", None) return list(parameters) if parameters else [] # TODO: Consider making leaf types always StrawberryTypes, maybe a # StrawberryBaseType or something if isinstance(self.type, StrawberryType): return self.type.type_params return [] def copy_with( self, type_var_map: Mapping[TypeVar, Union[StrawberryType, builtins.type]] ) -> StrawberryField: new_type: Union[StrawberryType, type] = self.type # TODO: Remove with creation of StrawberryObject. Will act same as other # StrawberryTypes if hasattr(self.type, "_type_definition"): type_definition: TypeDefinition = self.type._type_definition if type_definition.is_generic: type_ = type_definition new_type = type_.copy_with(type_var_map) elif isinstance(self.type, StrawberryType): new_type = self.type.copy_with(type_var_map) new_resolver = ( self.base_resolver.copy_with(type_var_map) if self.base_resolver is not None else None ) return StrawberryField( python_name=self.python_name, graphql_name=self.graphql_name, # TODO: do we need to wrap this in `StrawberryAnnotation`? # see comment related to dataclasses above type_annotation=StrawberryAnnotation(new_type), origin=self.origin, is_subscription=self.is_subscription, description=self.description, base_resolver=new_resolver, permission_classes=self.permission_classes, default=self.default_value, # ignored because of https://github.com/python/mypy/issues/6910 default_factory=self.default_factory, deprecation_reason=self.deprecation_reason, ) @property def _has_async_permission_classes(self) -> bool: for permission_class in self.permission_classes: if inspect.iscoroutinefunction(permission_class.has_permission): return True return False @property def _has_async_base_resolver(self) -> bool: return self.base_resolver is not None and self.base_resolver.is_async @cached_property def is_async(self) -> bool: return self._has_async_permission_classes or self._has_async_base_resolver @overload def field( *, resolver: _RESOLVER_TYPE[T], name: Optional[str] = None, is_subscription: bool = False, description: Optional[str] = None, init: Literal[False] = False, permission_classes: Optional[List[Type[BasePermission]]] = None, deprecation_reason: Optional[str] = None, default: Any = dataclasses.MISSING, default_factory: Union[Callable[..., object], object] = dataclasses.MISSING, metadata: Optional[Mapping[Any, Any]] = None, directives: Optional[Sequence[object]] = (), extensions: Optional[List[FieldExtension]] = None, graphql_type: Optional[Any] = None, ) -> T: ... @overload def field( *, name: Optional[str] = None, is_subscription: bool = False, description: Optional[str] = None, init: Literal[True] = True, permission_classes: Optional[List[Type[BasePermission]]] = None, deprecation_reason: Optional[str] = None, default: Any = dataclasses.MISSING, default_factory: Union[Callable[..., object], object] = dataclasses.MISSING, metadata: Optional[Mapping[Any, Any]] = None, directives: Optional[Sequence[object]] = (), extensions: Optional[List[FieldExtension]] = None, graphql_type: Optional[Any] = None, ) -> Any: ... @overload def field( resolver: _RESOLVER_TYPE[T], *, name: Optional[str] = None, is_subscription: bool = False, description: Optional[str] = None, permission_classes: Optional[List[Type[BasePermission]]] = None, deprecation_reason: Optional[str] = None, default: Any = dataclasses.MISSING, default_factory: Union[Callable[..., object], object] = dataclasses.MISSING, metadata: Optional[Mapping[Any, Any]] = None, directives: Optional[Sequence[object]] = (), extensions: Optional[List[FieldExtension]] = None, graphql_type: Optional[Any] = None, ) -> StrawberryField: ... def field( resolver: Optional[_RESOLVER_TYPE[Any]] = None, *, name: Optional[str] = None, is_subscription: bool = False, description: Optional[str] = None, permission_classes: Optional[List[Type[BasePermission]]] = None, deprecation_reason: Optional[str] = None, default: Any = dataclasses.MISSING, default_factory: Union[Callable[..., object], object] = dataclasses.MISSING, metadata: Optional[Mapping[Any, Any]] = None, directives: Optional[Sequence[object]] = (), extensions: Optional[List[FieldExtension]] = None, graphql_type: Optional[Any] = None, # This init parameter is used by PyRight to determine whether this field # is added in the constructor or not. It is not used to change # any behavior at the moment. init: Literal[True, False, None] = None, ) -> Any: """Annotates a method or property as a GraphQL field. This is normally used inside a type declaration: >>> @strawberry.type: >>> class X: >>> field_abc: str = strawberry.field(description="ABC") >>> @strawberry.field(description="ABC") >>> def field_with_resolver(self) -> str: >>> return "abc" it can be used both as decorator and as a normal function. """ type_annotation = StrawberryAnnotation.from_annotation(graphql_type) field_ = StrawberryField( python_name=None, graphql_name=name, type_annotation=type_annotation, description=description, is_subscription=is_subscription, permission_classes=permission_classes or [], deprecation_reason=deprecation_reason, default=default, default_factory=default_factory, metadata=metadata, directives=directives or (), extensions=extensions or [], ) if resolver: assert init is not True, "Can't set init as True when passing a resolver." return field_(resolver) return field_ __all__ = ["StrawberryField", "field"]
564bff00ff-strawberry-graphql
/564bff00ff_strawberry_graphql-0.168.2-py3-none-any.whl/strawberry/field.py
field.py
import dataclasses from enum import Enum from typing import Callable, List, Optional, Type, TypeVar from strawberry.object_type import _wrap_dataclass from strawberry.types.type_resolver import _get_fields from .directive import directive_field from .field import StrawberryField, field from .utils.typing import __dataclass_transform__ class Location(Enum): SCHEMA = "schema" SCALAR = "scalar" OBJECT = "object" FIELD_DEFINITION = "field definition" ARGUMENT_DEFINITION = "argument definition" INTERFACE = "interface" UNION = "union" ENUM = "enum" ENUM_VALUE = "enum value" INPUT_OBJECT = "input object" INPUT_FIELD_DEFINITION = "input field definition" @dataclasses.dataclass class StrawberrySchemaDirective: python_name: str graphql_name: Optional[str] locations: List[Location] fields: List["StrawberryField"] description: Optional[str] = None repeatable: bool = False print_definition: bool = True origin: Optional[Type] = None T = TypeVar("T", bound=Type) @__dataclass_transform__( order_default=True, kw_only_default=True, field_descriptors=(directive_field, field, StrawberryField), ) def schema_directive( *, locations: List[Location], description: Optional[str] = None, name: Optional[str] = None, repeatable: bool = False, print_definition: bool = True, ) -> Callable[..., T]: def _wrap(cls: T) -> T: cls = _wrap_dataclass(cls) fields = _get_fields(cls) cls.__strawberry_directive__ = StrawberrySchemaDirective( python_name=cls.__name__, graphql_name=name, locations=locations, description=description, repeatable=repeatable, fields=fields, print_definition=print_definition, origin=cls, ) return cls return _wrap __all__ = ["Location", "StrawberrySchemaDirective", "schema_directive"]
564bff00ff-strawberry-graphql
/564bff00ff_strawberry_graphql-0.168.2-py3-none-any.whl/strawberry/schema_directive.py
schema_directive.py
from typing import TypeVar from typing_extensions import Annotated, get_args, get_origin class StrawberryPrivate: ... T = TypeVar("T") Private = Annotated[T, StrawberryPrivate()] Private.__doc__ = """Represents a field that won't be exposed in the GraphQL schema Example: >>> import strawberry >>> @strawberry.type ... class User: ... name: str ... age: strawberry.Private[int] """ def is_private(type_: object) -> bool: if get_origin(type_) is Annotated: return any( isinstance(argument, StrawberryPrivate) for argument in get_args(type_) ) return False
564bff00ff-strawberry-graphql
/564bff00ff_strawberry_graphql-0.168.2-py3-none-any.whl/strawberry/private.py
private.py
import importlib import inspect import sys import warnings from dataclasses import dataclass from pathlib import Path from typing import ForwardRef, Generic, Optional, Type, TypeVar, cast TypeName = TypeVar("TypeName") Module = TypeVar("Module") @dataclass(frozen=True) class LazyType(Generic[TypeName, Module]): type_name: str module: str package: Optional[str] = None def __class_getitem__(cls, params): warnings.warn( ( "LazyType is deprecated, use " "Annotated[YourType, strawberry.lazy(path)] instead" ), DeprecationWarning, stacklevel=2, ) type_name, module = params package = None if module.startswith("."): current_frame = inspect.currentframe() assert current_frame is not None assert current_frame.f_back is not None package = current_frame.f_back.f_globals["__package__"] return cls(type_name, module, package) def resolve_type(self) -> Type: module = importlib.import_module(self.module, self.package) main_module = sys.modules.get("__main__", None) if main_module: # If lazy type points to the main module, use it instead of the imported # module. Otherwise duplication checks during schema-conversion might fail. # Refer to: https://github.com/strawberry-graphql/strawberry/issues/2397 if main_module.__spec__ and main_module.__spec__.name == self.module: module = main_module elif hasattr(main_module, "__file__") and hasattr(module, "__file__"): main_file = main_module.__file__ module_file = module.__file__ if main_file and module_file: try: is_samefile = Path(main_file).samefile(module_file) except FileNotFoundError: # Can be raised when run through the CLI as the __main__ file # path contains `strawberry.exe` is_samefile = False module = main_module if is_samefile else module return module.__dict__[self.type_name] # this empty call method allows LazyTypes to be used in generic types # for example: List[LazyType["A", "module"]] def __call__(self): # pragma: no cover return None class StrawberryLazyReference: def __init__(self, module: str) -> None: self.module = module self.package = None if module.startswith("."): frame = inspect.stack()[2][0] # TODO: raise a nice error if frame is None assert frame is not None self.package = cast(str, frame.f_globals["__package__"]) def resolve_forward_ref(self, forward_ref: ForwardRef) -> LazyType: return LazyType(forward_ref.__forward_arg__, self.module, self.package) def lazy(module_path: str) -> StrawberryLazyReference: return StrawberryLazyReference(module_path)
564bff00ff-strawberry-graphql
/564bff00ff_strawberry_graphql-0.168.2-py3-none-any.whl/strawberry/lazy_type.py
lazy_type.py
from __future__ import annotations import dataclasses from typing import TYPE_CHECKING, Any, Callable, List, Optional, TypeVar from typing_extensions import Annotated from graphql import DirectiveLocation from strawberry.field import StrawberryField from strawberry.types.fields.resolver import ( INFO_PARAMSPEC, ReservedType, StrawberryResolver, ) from strawberry.unset import UNSET from strawberry.utils.cached_property import cached_property if TYPE_CHECKING: import inspect from strawberry.arguments import StrawberryArgument def directive_field(name: str, default: object = UNSET) -> Any: return StrawberryField( python_name=None, graphql_name=name, default=default, ) T = TypeVar("T") class StrawberryDirectiveValue: ... DirectiveValue = Annotated[T, StrawberryDirectiveValue()] DirectiveValue.__doc__ = ( """Represents the ``value`` argument for a GraphQL query directive.""" ) # Registers `DirectiveValue[...]` annotated arguments as reserved VALUE_PARAMSPEC = ReservedType(name="value", type=StrawberryDirectiveValue) class StrawberryDirectiveResolver(StrawberryResolver[T]): RESERVED_PARAMSPEC = ( INFO_PARAMSPEC, VALUE_PARAMSPEC, ) @cached_property def value_parameter(self) -> Optional[inspect.Parameter]: return self.reserved_parameters.get(VALUE_PARAMSPEC) @dataclasses.dataclass class StrawberryDirective: python_name: str graphql_name: Optional[str] resolver: StrawberryDirectiveResolver locations: List[DirectiveLocation] description: Optional[str] = None @cached_property def arguments(self) -> List[StrawberryArgument]: return self.resolver.arguments def directive( *, locations: List[DirectiveLocation], description: Optional[str] = None, name: Optional[str] = None, ) -> Callable[[Callable[..., T]], T]: def _wrap(f: Callable[..., T]) -> T: return StrawberryDirective( # type: ignore python_name=f.__name__, graphql_name=name, locations=locations, description=description, resolver=StrawberryDirectiveResolver(f), ) return _wrap __all__ = ["DirectiveLocation", "StrawberryDirective", "directive"]
564bff00ff-strawberry-graphql
/564bff00ff_strawberry_graphql-0.168.2-py3-none-any.whl/strawberry/directive.py
directive.py
from .cli import run if __name__ == "__main__": run()
564bff00ff-strawberry-graphql
/564bff00ff_strawberry_graphql-0.168.2-py3-none-any.whl/strawberry/__main__.py
__main__.py
from __future__ import annotations from abc import ABC, abstractmethod from typing import TYPE_CHECKING, List, Mapping, TypeVar, Union if TYPE_CHECKING: from .types.types import TypeDefinition class StrawberryType(ABC): @property def type_params(self) -> List[TypeVar]: return [] @abstractmethod def copy_with( self, type_var_map: Mapping[TypeVar, Union[StrawberryType, type]] ) -> Union[StrawberryType, type]: raise NotImplementedError() @property @abstractmethod def is_generic(self) -> bool: raise NotImplementedError() def has_generic(self, type_var: TypeVar) -> bool: return False def __eq__(self, other: object) -> bool: from strawberry.annotation import StrawberryAnnotation if isinstance(other, StrawberryType): return self is other elif isinstance(other, StrawberryAnnotation): return self == other.resolve() else: # This could be simplified if StrawberryAnnotation.resolve() always returned # a StrawberryType resolved = StrawberryAnnotation(other).resolve() if isinstance(resolved, StrawberryType): return self == resolved else: return NotImplemented def __hash__(self) -> int: # TODO: Is this a bad idea? __eq__ objects are supposed to have the same hash return id(self) class StrawberryContainer(StrawberryType): def __init__(self, of_type: Union[StrawberryType, type]): self.of_type = of_type def __hash__(self) -> int: return hash((self.__class__, self.of_type)) def __eq__(self, other: object) -> bool: if isinstance(other, StrawberryType): if isinstance(other, StrawberryContainer): return self.of_type == other.of_type else: return False return super().__eq__(other) @property def type_params(self) -> List[TypeVar]: if hasattr(self.of_type, "_type_definition"): parameters = getattr(self.of_type, "__parameters__", None) return list(parameters) if parameters else [] elif isinstance(self.of_type, StrawberryType): return self.of_type.type_params else: return [] def copy_with( self, type_var_map: Mapping[TypeVar, Union[StrawberryType, type]] ) -> StrawberryType: of_type_copy: Union[StrawberryType, type] = self.of_type # TODO: Obsolete with StrawberryObject if hasattr(self.of_type, "_type_definition"): type_definition: TypeDefinition = self.of_type._type_definition if type_definition.is_generic: of_type_copy = type_definition.copy_with(type_var_map) elif isinstance(self.of_type, StrawberryType) and self.of_type.is_generic: of_type_copy = self.of_type.copy_with(type_var_map) return type(self)(of_type_copy) @property def is_generic(self) -> bool: # TODO: Obsolete with StrawberryObject type_ = self.of_type if hasattr(self.of_type, "_type_definition"): type_ = self.of_type._type_definition if isinstance(type_, StrawberryType): return type_.is_generic return False def has_generic(self, type_var: TypeVar) -> bool: if isinstance(self.of_type, StrawberryType): return self.of_type.has_generic(type_var) return False class StrawberryList(StrawberryContainer): ... class StrawberryOptional(StrawberryContainer): ... class StrawberryTypeVar(StrawberryType): def __init__(self, type_var: TypeVar): self.type_var = type_var def copy_with( self, type_var_map: Mapping[TypeVar, Union[StrawberryType, type]] ) -> Union[StrawberryType, type]: return type_var_map[self.type_var] @property def is_generic(self) -> bool: return True def has_generic(self, type_var: TypeVar) -> bool: return self.type_var == type_var @property def type_params(self) -> List[TypeVar]: return [self.type_var] def __eq__(self, other: object) -> bool: if isinstance(other, StrawberryTypeVar): return self.type_var == other.type_var if isinstance(other, TypeVar): return self.type_var == other return super().__eq__(other)
564bff00ff-strawberry-graphql
/564bff00ff_strawberry_graphql-0.168.2-py3-none-any.whl/strawberry/type.py
type.py
import dataclasses from enum import EnumMeta from typing import ( Any, Callable, Iterable, List, Mapping, Optional, TypeVar, Union, overload, ) from strawberry.type import StrawberryType from .exceptions import ObjectIsNotAnEnumError @dataclasses.dataclass class EnumValue: name: str value: Any deprecation_reason: Optional[str] = None directives: Iterable[object] = () description: Optional[str] = None @dataclasses.dataclass class EnumDefinition(StrawberryType): wrapped_cls: EnumMeta name: str values: List[EnumValue] description: Optional[str] directives: Iterable[object] = () def __hash__(self) -> int: # TODO: Is this enough for unique-ness? return hash(self.name) def copy_with( self, type_var_map: Mapping[TypeVar, Union[StrawberryType, type]] ) -> Union[StrawberryType, type]: # enum don't support type parameters, so we can safely return self return self @property def is_generic(self) -> bool: return False # TODO: remove duplication of EnumValueDefinition and EnumValue @dataclasses.dataclass class EnumValueDefinition: value: Any deprecation_reason: Optional[str] = None directives: Iterable[object] = () description: Optional[str] = None def enum_value( value: Any, deprecation_reason: Optional[str] = None, directives: Iterable[object] = (), description: Optional[str] = None, ) -> EnumValueDefinition: return EnumValueDefinition( value=value, deprecation_reason=deprecation_reason, directives=directives, description=description, ) EnumType = TypeVar("EnumType", bound=EnumMeta) def _process_enum( cls: EnumType, name: Optional[str] = None, description: Optional[str] = None, directives: Iterable[object] = (), ) -> EnumType: if not isinstance(cls, EnumMeta): raise ObjectIsNotAnEnumError(cls) if not name: name = cls.__name__ description = description values = [] for item in cls: # type: ignore item_value = item.value item_name = item.name deprecation_reason = None item_directives: Iterable[object] = () enum_value_description = None if isinstance(item_value, EnumValueDefinition): item_directives = item_value.directives enum_value_description = item_value.description deprecation_reason = item_value.deprecation_reason item_value = item_value.value # update _value2member_map_ so that doing `MyEnum.MY_VALUE` and # `MyEnum['MY_VALUE']` both work cls._value2member_map_[item_value] = item cls._member_map_[item_name]._value_ = item_value value = EnumValue( item_name, item_value, deprecation_reason=deprecation_reason, directives=item_directives, description=enum_value_description, ) values.append(value) cls._enum_definition = EnumDefinition( # type: ignore wrapped_cls=cls, name=name, values=values, description=description, directives=directives, ) return cls @overload def enum( _cls: EnumType, *, name: Optional[str] = None, description: Optional[str] = None, directives: Iterable[object] = () ) -> EnumType: ... @overload def enum( _cls: None = None, *, name: Optional[str] = None, description: Optional[str] = None, directives: Iterable[object] = () ) -> Callable[[EnumType], EnumType]: ... def enum( _cls: Optional[EnumType] = None, *, name: Optional[str] = None, description: Optional[str] = None, directives: Iterable[object] = () ) -> Union[EnumType, Callable[[EnumType], EnumType]]: """Registers the enum in the GraphQL type system. If name is passed, the name of the GraphQL type will be the value passed of name instead of the Enum class name. """ def wrap(cls: EnumType) -> EnumType: return _process_enum(cls, name, description, directives=directives) if not _cls: return wrap return wrap(_cls)
564bff00ff-strawberry-graphql
/564bff00ff_strawberry_graphql-0.168.2-py3-none-any.whl/strawberry/enum.py
enum.py
from __future__ import annotations import inspect import warnings from typing import ( TYPE_CHECKING, Any, Dict, Iterable, List, Mapping, Optional, Union, cast, ) from typing_extensions import Annotated, get_args, get_origin from strawberry.annotation import StrawberryAnnotation from strawberry.enum import EnumDefinition from strawberry.lazy_type import LazyType, StrawberryLazyReference from strawberry.type import StrawberryList, StrawberryOptional from .exceptions import MultipleStrawberryArgumentsError, UnsupportedTypeError from .scalars import is_scalar from .unset import UNSET as _deprecated_UNSET from .unset import _deprecated_is_unset # noqa if TYPE_CHECKING: from strawberry.custom_scalar import ScalarDefinition, ScalarWrapper from strawberry.schema.config import StrawberryConfig from strawberry.type import StrawberryType from .types.types import TypeDefinition DEPRECATED_NAMES: Dict[str, str] = { "UNSET": ( "importing `UNSET` from `strawberry.arguments` is deprecated, " "import instead from `strawberry` or from `strawberry.unset`" ), "is_unset": "`is_unset` is deprecated use `value is UNSET` instead", } class StrawberryArgumentAnnotation: description: Optional[str] name: Optional[str] deprecation_reason: Optional[str] directives: Iterable[object] def __init__( self, description: Optional[str] = None, name: Optional[str] = None, deprecation_reason: Optional[str] = None, directives: Iterable[object] = (), ): self.description = description self.name = name self.deprecation_reason = deprecation_reason self.directives = directives class StrawberryArgument: def __init__( self, python_name: str, graphql_name: Optional[str], type_annotation: StrawberryAnnotation, is_subscription: bool = False, description: Optional[str] = None, default: object = _deprecated_UNSET, deprecation_reason: Optional[str] = None, directives: Iterable[object] = (), ) -> None: self.python_name = python_name self.graphql_name = graphql_name self.is_subscription = is_subscription self.description = description self._type: Optional[StrawberryType] = None self.type_annotation = type_annotation self.deprecation_reason = deprecation_reason self.directives = directives # TODO: Consider moving this logic to a function self.default = ( _deprecated_UNSET if default is inspect.Parameter.empty else default ) if self._annotation_is_annotated(type_annotation): self._parse_annotated() @property def type(self) -> Union[StrawberryType, type]: return self.type_annotation.resolve() @classmethod def _annotation_is_annotated(cls, annotation: StrawberryAnnotation) -> bool: return get_origin(annotation.annotation) is Annotated def _parse_annotated(self): annotated_args = get_args(self.type_annotation.annotation) # The first argument to Annotated is always the underlying type self.type_annotation = StrawberryAnnotation(annotated_args[0]) # Find any instances of StrawberryArgumentAnnotation # in the other Annotated args, raising an exception if there # are multiple StrawberryArgumentAnnotations argument_annotation_seen = False for arg in annotated_args[1:]: if isinstance(arg, StrawberryArgumentAnnotation): if argument_annotation_seen: raise MultipleStrawberryArgumentsError( argument_name=self.python_name ) argument_annotation_seen = True self.description = arg.description self.graphql_name = arg.name self.deprecation_reason = arg.deprecation_reason self.directives = arg.directives if isinstance(arg, StrawberryLazyReference): self.type_annotation = StrawberryAnnotation( arg.resolve_forward_ref(annotated_args[0]) ) def convert_argument( value: object, type_: Union[StrawberryType, type], scalar_registry: Dict[object, Union[ScalarWrapper, ScalarDefinition]], config: StrawberryConfig, ) -> object: # TODO: move this somewhere else and make it first class if value is None: return None if value is _deprecated_UNSET: return _deprecated_UNSET if isinstance(type_, StrawberryOptional): return convert_argument(value, type_.of_type, scalar_registry, config) if isinstance(type_, StrawberryList): value_list = cast(Iterable, value) return [ convert_argument(x, type_.of_type, scalar_registry, config) for x in value_list ] if is_scalar(type_, scalar_registry): return value if isinstance(type_, EnumDefinition): return value if isinstance(type_, LazyType): return convert_argument(value, type_.resolve_type(), scalar_registry, config) if hasattr(type_, "_enum_definition"): enum_definition: EnumDefinition = type_._enum_definition return convert_argument(value, enum_definition, scalar_registry, config) if hasattr(type_, "_type_definition"): # TODO: Replace with StrawberryInputObject type_definition: TypeDefinition = type_._type_definition kwargs = {} for field in type_definition.fields: value = cast(Mapping, value) graphql_name = config.name_converter.from_field(field) if graphql_name in value: kwargs[field.python_name] = convert_argument( value[graphql_name], field.type, scalar_registry, config ) type_ = cast(type, type_) return type_(**kwargs) raise UnsupportedTypeError(type_) def convert_arguments( value: Dict[str, Any], arguments: List[StrawberryArgument], scalar_registry: Dict[object, Union[ScalarWrapper, ScalarDefinition]], config: StrawberryConfig, ) -> Dict[str, Any]: """Converts a nested dictionary to a dictionary of actual types. It deals with conversion of input types to proper dataclasses and also uses a sentinel value for unset values.""" if not arguments: return {} kwargs = {} for argument in arguments: assert argument.python_name name = config.name_converter.from_argument(argument) if name in value: current_value = value[name] kwargs[argument.python_name] = convert_argument( value=current_value, type_=argument.type, config=config, scalar_registry=scalar_registry, ) return kwargs def argument( description: Optional[str] = None, name: Optional[str] = None, deprecation_reason: Optional[str] = None, directives: Iterable[object] = (), ) -> StrawberryArgumentAnnotation: return StrawberryArgumentAnnotation( description=description, name=name, deprecation_reason=deprecation_reason, directives=directives, ) def __getattr__(name: str) -> Any: if name in DEPRECATED_NAMES: warnings.warn(DEPRECATED_NAMES[name], DeprecationWarning, stacklevel=2) return globals()[f"_deprecated_{name}"] raise AttributeError(f"module {__name__} has no attribute {name}") # TODO: check exports __all__ = [ # noqa: F822 "StrawberryArgument", "StrawberryArgumentAnnotation", "UNSET", # for backwards compatibility "argument", "is_unset", # for backwards compatibility ]
564bff00ff-strawberry-graphql
/564bff00ff_strawberry_graphql-0.168.2-py3-none-any.whl/strawberry/arguments.py
arguments.py
from typing import Any, Callable def is_default_resolver(func: Callable[..., Any]) -> bool: """Check whether the function is a default resolver or a user provided one.""" return getattr(func, "_is_default", False)
564bff00ff-strawberry-graphql
/564bff00ff_strawberry_graphql-0.168.2-py3-none-any.whl/strawberry/resolvers.py
resolvers.py
from __future__ import annotations import sys import typing from collections import abc from enum import Enum from typing import ( TYPE_CHECKING, Any, Dict, ForwardRef, Optional, TypeVar, Union, cast, ) from typing_extensions import Annotated, Self, get_args, get_origin from strawberry.custom_scalar import ScalarDefinition from strawberry.enum import EnumDefinition from strawberry.exceptions.not_a_strawberry_enum import NotAStrawberryEnumError from strawberry.lazy_type import LazyType from strawberry.private import is_private from strawberry.type import StrawberryList, StrawberryOptional, StrawberryTypeVar from strawberry.types.types import TypeDefinition from strawberry.unset import UNSET from strawberry.utils.typing import ( eval_type, is_generic, is_type_var, ) if TYPE_CHECKING: from strawberry.field import StrawberryField from strawberry.type import StrawberryType from strawberry.union import StrawberryUnion ASYNC_TYPES = ( abc.AsyncGenerator, abc.AsyncIterable, abc.AsyncIterator, typing.AsyncContextManager, typing.AsyncGenerator, typing.AsyncIterable, typing.AsyncIterator, ) class StrawberryAnnotation: def __init__( self, annotation: Union[object, str], *, namespace: Optional[Dict] = None ): self.annotation = annotation self.namespace = namespace def __eq__(self, other: object) -> bool: if not isinstance(other, StrawberryAnnotation): return NotImplemented return self.resolve() == other.resolve() @staticmethod def from_annotation( annotation: object, namespace: Optional[Dict] = None ) -> Optional[StrawberryAnnotation]: if annotation is None: return None if not isinstance(annotation, StrawberryAnnotation): return StrawberryAnnotation(annotation, namespace=namespace) return annotation def resolve(self) -> Union[StrawberryType, type]: annotation = self.annotation if isinstance(annotation, str): annotation = ForwardRef(annotation) evaled_type = eval_type(annotation, self.namespace, None) if is_private(evaled_type): return evaled_type if get_origin(evaled_type) is Annotated: evaled_type = get_args(evaled_type)[0] if self._is_async_type(evaled_type): evaled_type = self._strip_async_type(evaled_type) if self._is_lazy_type(evaled_type): return evaled_type if self._is_generic(evaled_type): if any(is_type_var(type_) for type_ in evaled_type.__args__): return evaled_type return self.create_concrete_type(evaled_type) # Simply return objects that are already StrawberryTypes if self._is_strawberry_type(evaled_type): return evaled_type # Everything remaining should be a raw annotation that needs to be turned into # a StrawberryType if self._is_enum(evaled_type): return self.create_enum(evaled_type) if self._is_list(evaled_type): return self.create_list(evaled_type) elif self._is_optional(evaled_type): return self.create_optional(evaled_type) elif self._is_union(evaled_type): return self.create_union(evaled_type) elif is_type_var(evaled_type) or evaled_type is Self: return self.create_type_var(cast(TypeVar, evaled_type)) # TODO: Raise exception now, or later? # ... raise NotImplementedError(f"Unknown type {evaled_type}") return evaled_type def set_namespace_from_field(self, field: StrawberryField) -> None: module = sys.modules[field.origin.__module__] self.namespace = module.__dict__ def create_concrete_type(self, evaled_type: type) -> type: if _is_object_type(evaled_type): type_definition: TypeDefinition type_definition = evaled_type._type_definition # type: ignore return type_definition.resolve_generic(evaled_type) raise ValueError(f"Not supported {evaled_type}") def create_enum(self, evaled_type: Any) -> EnumDefinition: try: return evaled_type._enum_definition except AttributeError: raise NotAStrawberryEnumError(evaled_type) def create_list(self, evaled_type: Any) -> StrawberryList: of_type = StrawberryAnnotation( annotation=evaled_type.__args__[0], namespace=self.namespace, ).resolve() return StrawberryList(of_type) def create_optional(self, evaled_type: Any) -> StrawberryOptional: types = evaled_type.__args__ non_optional_types = tuple( filter( lambda x: x is not type(None) and x is not type(UNSET), types, ) ) # Note that passing a single type to `Union` is equivalent to not using `Union` # at all. This allows us to not di any checks for how many types have been # passed as we can safely use `Union` for both optional types # (e.g. `Optional[str]`) and optional unions (e.g. # `Optional[Union[TypeA, TypeB]]`) child_type = Union[non_optional_types] # type: ignore of_type = StrawberryAnnotation( annotation=child_type, namespace=self.namespace, ).resolve() return StrawberryOptional(of_type) def create_type_var(self, evaled_type: TypeVar) -> StrawberryTypeVar: return StrawberryTypeVar(evaled_type) def create_union(self, evaled_type) -> StrawberryUnion: # Prevent import cycles from strawberry.union import StrawberryUnion # TODO: Deal with Forward References/origin if isinstance(evaled_type, StrawberryUnion): return evaled_type types = evaled_type.__args__ union = StrawberryUnion( type_annotations=tuple(StrawberryAnnotation(type_) for type_ in types), ) return union @classmethod def _is_async_type(cls, annotation: type) -> bool: origin = getattr(annotation, "__origin__", None) return origin in ASYNC_TYPES @classmethod def _is_enum(cls, annotation: Any) -> bool: # Type aliases are not types so we need to make sure annotation can go into # issubclass if not isinstance(annotation, type): return False return issubclass(annotation, Enum) @classmethod def _is_generic(cls, annotation: Any) -> bool: if hasattr(annotation, "__origin__"): return is_generic(annotation.__origin__) return False @classmethod def _is_lazy_type(cls, annotation: Any) -> bool: return isinstance(annotation, LazyType) @classmethod def _is_optional(cls, annotation: Any) -> bool: """Returns True if the annotation is Optional[SomeType]""" # Optionals are represented as unions if not cls._is_union(annotation): return False types = annotation.__args__ # A Union to be optional needs to have at least one None type return any(x is type(None) for x in types) @classmethod def _is_list(cls, annotation: Any) -> bool: """Returns True if annotation is a List""" annotation_origin = getattr(annotation, "__origin__", None) return (annotation_origin in (list, tuple)) or annotation_origin is abc.Sequence @classmethod def _is_strawberry_type(cls, evaled_type: Any) -> bool: # Prevent import cycles from strawberry.union import StrawberryUnion if isinstance(evaled_type, EnumDefinition): return True elif _is_input_type(evaled_type): # TODO: Replace with StrawberryInputObject return True # TODO: add support for StrawberryInterface when implemented elif isinstance(evaled_type, StrawberryList): return True elif _is_object_type(evaled_type): # TODO: Replace with StrawberryObject return True elif isinstance(evaled_type, TypeDefinition): return True elif isinstance(evaled_type, StrawberryOptional): return True elif isinstance( evaled_type, ScalarDefinition ): # TODO: Replace with StrawberryScalar return True elif isinstance(evaled_type, StrawberryUnion): return True return False @classmethod def _is_union(cls, annotation: Any) -> bool: """Returns True if annotation is a Union""" # this check is needed because unions declared with the new syntax `A | B` # don't have a `__origin__` property on them, but they are instances of # `UnionType`, which is only available in Python 3.10+ if sys.version_info >= (3, 10): from types import UnionType if isinstance(annotation, UnionType): return True # unions declared as Union[A, B] fall through to this check # even on python 3.10+ annotation_origin = getattr(annotation, "__origin__", None) return annotation_origin is typing.Union @classmethod def _strip_async_type(cls, annotation) -> type: return annotation.__args__[0] @classmethod def _strip_lazy_type(cls, annotation: LazyType) -> type: return annotation.resolve_type() ################################################################################ # Temporary functions to be removed with new types ################################################################################ def _is_input_type(type_: Any) -> bool: if not _is_object_type(type_): return False return type_._type_definition.is_input def _is_object_type(type_: Any) -> bool: return hasattr(type_, "_type_definition")
564bff00ff-strawberry-graphql
/564bff00ff_strawberry_graphql-0.168.2-py3-none-any.whl/strawberry/annotation.py
annotation.py
from functools import partial from .field import field # Mutations and subscriptions are field, we might want to separate # things in the long run for example to provide better errors mutation = field subscription = partial(field, is_subscription=True)
564bff00ff-strawberry-graphql
/564bff00ff_strawberry_graphql-0.168.2-py3-none-any.whl/strawberry/mutation.py
mutation.py
from __future__ import annotations import dataclasses from abc import ABC, abstractmethod from asyncio import create_task, gather, get_event_loop from asyncio.futures import Future from dataclasses import dataclass from typing import ( TYPE_CHECKING, Any, Awaitable, Callable, Dict, Generic, Hashable, Iterable, List, Mapping, Optional, Sequence, TypeVar, Union, overload, ) from .exceptions import WrongNumberOfResultsReturned if TYPE_CHECKING: from asyncio.events import AbstractEventLoop T = TypeVar("T") K = TypeVar("K") @dataclass class LoaderTask(Generic[K, T]): key: K future: Future @dataclass class Batch(Generic[K, T]): tasks: List[LoaderTask] = dataclasses.field(default_factory=list) dispatched: bool = False def add_task(self, key: Any, future: Future) -> None: task = LoaderTask[K, T](key, future) self.tasks.append(task) def __len__(self) -> int: return len(self.tasks) class AbstractCache(Generic[K, T], ABC): @abstractmethod def get(self, key: K) -> Union[Future[T], None]: pass @abstractmethod def set(self, key: K, value: Future[T]) -> None: pass @abstractmethod def delete(self, key: K) -> None: pass @abstractmethod def clear(self) -> None: pass class DefaultCache(AbstractCache[K, T]): def __init__(self, cache_key_fn: Optional[Callable[[K], Hashable]] = None) -> None: self.cache_key_fn: Callable[[K], Hashable] = ( cache_key_fn if cache_key_fn is not None else lambda x: x ) self.cache_map: Dict[Hashable, Future[T]] = {} def get(self, key: K) -> Union[Future[T], None]: return self.cache_map.get(self.cache_key_fn(key)) def set(self, key: K, value: Future[T]) -> None: self.cache_map[self.cache_key_fn(key)] = value def delete(self, key: K) -> None: del self.cache_map[self.cache_key_fn(key)] def clear(self) -> None: self.cache_map.clear() class DataLoader(Generic[K, T]): batch: Optional[Batch[K, T]] = None cache: bool = False cache_map: AbstractCache[K, T] @overload def __init__( self, # any BaseException is rethrown in 'load', so should be excluded from the T type load_fn: Callable[[List[K]], Awaitable[Sequence[Union[T, BaseException]]]], max_batch_size: Optional[int] = None, cache: bool = True, loop: Optional[AbstractEventLoop] = None, cache_map: Optional[AbstractCache[K, T]] = None, cache_key_fn: Optional[Callable[[K], Hashable]] = None, ) -> None: ... # fallback if load_fn is untyped and there's no other info for inference @overload def __init__( self: DataLoader[K, Any], load_fn: Callable[[List[K]], Awaitable[List[Any]]], max_batch_size: Optional[int] = None, cache: bool = True, loop: Optional[AbstractEventLoop] = None, cache_map: Optional[AbstractCache[K, T]] = None, cache_key_fn: Optional[Callable[[K], Hashable]] = None, ) -> None: ... def __init__( self, load_fn: Callable[[List[K]], Awaitable[Sequence[Union[T, BaseException]]]], max_batch_size: Optional[int] = None, cache: bool = True, loop: Optional[AbstractEventLoop] = None, cache_map: Optional[AbstractCache[K, T]] = None, cache_key_fn: Optional[Callable[[K], Hashable]] = None, ): self.load_fn = load_fn self.max_batch_size = max_batch_size self._loop = loop self.cache = cache if self.cache: self.cache_map = ( DefaultCache(cache_key_fn) if cache_map is None else cache_map ) @property def loop(self) -> AbstractEventLoop: if self._loop is None: self._loop = get_event_loop() return self._loop def load(self, key: K) -> Awaitable[T]: if self.cache: future = self.cache_map.get(key) if future and not future.cancelled(): return future future = self.loop.create_future() if self.cache: self.cache_map.set(key, future) batch = get_current_batch(self) batch.add_task(key, future) return future def load_many(self, keys: Iterable[K]) -> Awaitable[List[T]]: return gather(*map(self.load, keys)) def clear(self, key: K) -> None: if self.cache: self.cache_map.delete(key) def clear_many(self, keys: Iterable[K]) -> None: if self.cache: for key in keys: self.cache_map.delete(key) def clear_all(self) -> None: if self.cache: self.cache_map.clear() def prime(self, key: K, value: T, force: bool = False) -> None: self.prime_many({key: value}, force) def prime_many(self, data: Mapping[K, T], force: bool = False) -> None: # Populate the cache with the specified values if self.cache: for key, value in data.items(): if not self.cache_map.get(key) or force: future: Future = Future(loop=self.loop) future.set_result(value) self.cache_map.set(key, future) # For keys that are pending on the current batch, but the # batch hasn't started fetching yet: Remove it from the # batch and set to the specified value if self.batch is not None and not self.batch.dispatched: batch_updated = False for task in self.batch.tasks: if task.key in data: batch_updated = True task.future.set_result(data[task.key]) if batch_updated: self.batch.tasks = [ task for task in self.batch.tasks if not task.future.done() ] def should_create_new_batch(loader: DataLoader, batch: Batch) -> bool: if ( batch.dispatched or loader.max_batch_size and len(batch) >= loader.max_batch_size ): return True return False def get_current_batch(loader: DataLoader) -> Batch: if loader.batch and not should_create_new_batch(loader, loader.batch): return loader.batch loader.batch = Batch() dispatch(loader, loader.batch) return loader.batch def dispatch(loader: DataLoader, batch: Batch) -> None: loader.loop.call_soon(create_task, dispatch_batch(loader, batch)) async def dispatch_batch(loader: DataLoader, batch: Batch) -> None: batch.dispatched = True keys = [task.key for task in batch.tasks] if len(keys) == 0: # Ensure batch is not empty # Unlikely, but could happen if the tasks are # overriden with preset values return # TODO: check if load_fn return an awaitable and it is a list try: values = await loader.load_fn(keys) values = list(values) if len(values) != len(batch): raise WrongNumberOfResultsReturned( expected=len(batch), received=len(values) ) for task, value in zip(batch.tasks, values): # Trying to set_result in a cancelled future would raise # asyncio.exceptions.InvalidStateError if task.future.cancelled(): continue if isinstance(value, BaseException): task.future.set_exception(value) else: task.future.set_result(value) except Exception as e: for task in batch.tasks: task.future.set_exception(e)
564bff00ff-strawberry-graphql
/564bff00ff_strawberry_graphql-0.168.2-py3-none-any.whl/strawberry/dataloader.py
dataloader.py