コード例 #1
0
ファイル: test_binary.py プロジェクト: dNG-git/pas_core
    def test_formats(self):
        # global: _PY_BYTES, _PY_BYTES_TYPE, _PY_STR, _PY_UNICODE, _PY_UNICODE_TYPE

        self.assertEqual(_PY_BYTES_TYPE, type(Binary.bytes("data")))
        self.assertEqual(str, type(Binary.raw_str("data")))
        self.assertEqual(str, type(Binary.str("data")))
        self.assertEqual(_PY_UNICODE_TYPE, type(Binary.utf8("data")))
        self.assertEqual(_PY_BYTES_TYPE, type(Binary.utf8_bytes("data")))
コード例 #2
0
    def request(self, method, separator = ";", params = None, data = None):
        """
Call a given request method on the connected HTTP server.

:param method: HTTP method
:param separator: Query parameter separator
:param params: Parsed query parameters as str
:param data: HTTP body

:return: (dict) Response data; 'body' may contain the catched exception
:since:  v1.0.0
        """

        # pylint: disable=broad-except,star-args

        if (self._log_handler is not None): self._log_handler.debug("#echo(__FILEPATH__)# -{0!r}.request({1})- (#echo(__LINE__)#)".format(self, method))

        try:
            path = self.path

            if (type(params) is str):
                if ("?" not in path): path += "?"
                elif (not path.endswith(separator)): path += separator

                path += params
            #

            headers = (None if (self.headers is None) else self.headers.copy())
            kwargs = { "url": path }

            if (data is not None):
                if (isinstance(data, dict)):
                    if (headers is None): headers = { }
                    if ("content-type" not in headers): headers['content-type'] = "application/x-www-form-urlencoded"

                    data = urlencode(data)
                #

                kwargs['body'] = Binary.utf8_bytes(data)
            #

            if (self.auth_username is not None):
                auth_data = "{0}:{1}".format(self.auth_username, self.auth_password)

                if (type(auth_data) is not Binary.BYTES_TYPE): auth_data = Binary.utf8_bytes(auth_data)
                base64_data = b64encode(auth_data)
                if (type(base64_data) is not str): base64_data = Binary.str(base64_data)

                kwargs['headers'] = { "Authorization": "Basic {0}".format(base64_data) }
                if (headers is not None): kwargs['headers'].update(headers)
            elif (headers is not None): kwargs['headers'] = headers

            _return = self._request(method, **kwargs)
        except Exception as handled_exception: _return = { "code": None, "headers": None, "body": handled_exception }

        return _return
コード例 #3
0
ファイル: dispatcher.py プロジェクト: dNG-git/pas_server
    def prepare_socket(listener_type, *listener_data):
        """
Prepare socket returns a bound socket for the given listener data.

:param listener_type: Listener type
:param listener_data: Listener data

:since: v1.0.0
        """

        _return = None

        if (listener_type == socket.AF_INET or listener_type == socket.AF_INET6):
            listener_data = ( Binary.str(listener_data[0]), listener_data[1] )

            _return = socket.socket(listener_type, socket.SOCK_STREAM)
            _return.setblocking(0)
            if (hasattr(socket, "SO_REUSEADDR")): _return.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
            _return.bind(listener_data)
        elif (listener_type == socket.AF_UNIX):
            unixsocket_path_name = path.normpath(Binary.str(listener_data[0]))

            if (os.access(unixsocket_path_name, os.F_OK)):
                if (os.environ.get("PAS_SERVER_REMOVE_UNIX_SOCKETS_ON_START") in ( "1", "t", "true", "yes" )):
                    Dispatcher._remove_unixsocket(unixsocket_path_name)
                else: raise IOException("UNIX socket file '{0}' already exists".format(unixsocket_path_name))
            #

            _return = socket.socket(listener_type, socket.SOCK_STREAM)
            _return.bind(unixsocket_path_name)

            socket_chmod = 0
            socket_chmod_value = int(Settings.get("pas_global_server_chmod_unix_sockets", "600"), 8)

            if (1000 & socket_chmod_value): socket_chmod |= stat.S_ISVTX
            if (2000 & socket_chmod_value): socket_chmod |= stat.S_ISGID
            if (4000 & socket_chmod_value): socket_chmod |= stat.S_ISUID
            if (0o100 & socket_chmod_value): socket_chmod |= stat.S_IXUSR
            if (0o200 & socket_chmod_value): socket_chmod |= stat.S_IWUSR
            if (0o400 & socket_chmod_value): socket_chmod |= stat.S_IRUSR
            if (0o010 & socket_chmod_value): socket_chmod |= stat.S_IXGRP
            if (0o020 & socket_chmod_value): socket_chmod |= stat.S_IWGRP
            if (0o040 & socket_chmod_value): socket_chmod |= stat.S_IRGRP
            if (0o001 & socket_chmod_value): socket_chmod |= stat.S_IXOTH
            if (0o002 & socket_chmod_value): socket_chmod |= stat.S_IWOTH
            if (0o004 & socket_chmod_value): socket_chmod |= stat.S_IROTH

            os.chmod(unixsocket_path_name, socket_chmod)
        #

        return _return
コード例 #4
0
    def render_json_rewrite(self, json_resource, json_base_path,
                            json_value_path):
        """
Renders the data identified by the given node value path in the JSON
resource.

:param json_resource: JSON resource instance
:param json_base_path: JSON base node path
:param json_value_path: JSON value node path

:return: (str) Rendered content
:since:  v1.0.0
        """

        if (self._log_handler is not None):
            self._log_handler.debug(
                "#echo(__FILEPATH__)# -{0!r}.render_json_rewrite({1}, {2})- (#echo(__LINE__)#)",
                self,
                json_base_path,
                json_value_path,
                context="pas_tag_parser")

        if (json_base_path != ""):
            json_value_path = "{0} {1}".format(json_base_path, json_value_path)

        _return = (json_resource.get_node(json_value_path) if
                   (isinstance(json_resource, JsonResource)) else "")

        _return = ("" if (_return is None) else Binary.str(_return))
        if (type(_return) is not str): _return = str(_return)

        return _return
コード例 #5
0
ファイル: handler.py プロジェクト: dNG-git/pas_server
    def write_data(self, data):
        """
Write data to the socket.

:param data: Data to be written

:return: (bool) True on success
:since:  v1.0.0
        """

        # pylint: disable=broad-except

        _return = True

        data = Binary.bytes(data)

        if (self.socket is not None and len(data) > 0):
            try: self.socket.sendall(data)
            except Exception as handled_exception:
                if (self._log_handler is not None): self._log_handler.error(handled_exception, context = "pas_server")
                _return = False
            #
        #

        return _return
コード例 #6
0
ファイル: l10n.py プロジェクト: dNG-git/pas_l10n
    def get_relative_file_path_name(file_id):
        """
Returns the relative file path and name for the file ID given.

:param file_id: L10n file ID

:return: (str) File path and name
:since:  v1.0.0
        """

        file_id = Binary.str(file_id)

        file_id_elements = file_id.split(".")
        _return = ""

        for file_id_element in file_id_elements:
            if (file_id_element):
                file_id_element = L10n.RE_SPECIAL_CHARACTERS.sub(
                    " ", file_id_element)
                _return += ("/" if
                            (len(_return) > 0) else "") + file_id_element
            #
        #

        return _return
コード例 #7
0
    def __init__(self, filter_string):
        """
Constructor __init__(AbstractFilterParser)

:param filter_string: Raw JSON filter definition

:since: v1.0.0
        """

        filter_string = Binary.str(filter_string)
        if (not isinstance(filter_string, str)): raise InputValidationException("Filter given is invalid")

        SupportsMixin.__init__(self)

        self._blacklisted_keys = [ ]
        """
List of keys marked as blacklisted
        """
        self._filter = None
        """
Parser specific filter representation
        """
        self._lock = ThreadLock()
        """
Thread safety lock
        """
        self._raw_filter_string = filter_string.strip()
        """
Raw JSON filter definition
        """

        if (len(self._raw_filter_string) < 1): self._set_empty_filter()
コード例 #8
0
    def render_xml_if_condition(self, xml_parser, xml_base_path, xml_value_path, operator, value, data):
        """
Checks and renders the content of the "if" condition.

:param data: Conditional data
:param source: Source for comparison
:param key: Key in source for comparison
:param operator: Comparison operator
:param value: Comparison value

:return: (str) Conditional data if successful
:since:  v1.0.0
        """

        if (self._log_handler is not None): self._log_handler.debug("#echo(__FILEPATH__)# -{0!r}.render_xml_if_condition({1}, {2}, {3}, {4})- (#echo(__LINE__)#)", self, xml_base_path, xml_value_path, operator, value, context = "pas_tag_parser")
        _return = ""

        is_valid = False
        xml_value = xml_parser.get_node_value("{0} {1}".format(xml_base_path, xml_value_path))

        xml_value = ("" if (xml_value is None) else Binary.str(xml_value))
        if (type(xml_value) is not str): xml_value = str(xml_value)

        if (operator == "==" and xml_value == value): is_valid = True
        if (operator == "!=" and xml_value != value): is_valid = True

        if (is_valid): _return = data
        return _return
コード例 #9
0
ファイル: l10n_instance.py プロジェクト: dNG-git/pas_l10n
    def __getitem__(self, key):
        """
python.org: Called to implement evaluation of self[key].

:param key: L10n key

:return: (str) L10n value
:since:  v1.0.0
        """

        return Binary.str(dict.__getitem__(self, key))
コード例 #10
0
ファイル: handler.py プロジェクト: dNG-git/pas_server
    def _set_data(self, data):
        """
Sets data returned next time "get_data()" is called. It is placed in front of
the data buffer.

:param data: Data to be buffered

:since: v1.0.0
        """

        self.data = (Binary.bytes(data) + self.data)
コード例 #11
0
    def url(self, url):
        """
Sets a new URL for all subsequent requests.

:param url: URL to be called

:since: v1.0.0
        """

        url = Binary.str(url)
        if (type(url) is not str): raise TypeException("URL given is invalid")

        self._configure(url)
コード例 #12
0
    def __format__(self, format_spec):
        """
python.org: Convert a value to a "formatted" representation, as controlled by
format_spec.

:param format_spec: String format specification

:since: v1.0.0
        """

        if (format_spec == "l10n_message"):
            return Binary.str(self.l10n_message)
        else:
            _TracedException.__format__(self, format_spec)
コード例 #13
0
    def send_data(self, data):
        """
Sends the given data as part of the response.

:param data: Data to send

:since: v1.0.0
        """

        if (self.active):
            data = Binary.bytes(data)

            if (self.stream_mode == AbstractStreamResponse.STREAM_NONE):
                if (self._data is None): self._data = Binary.BYTES_TYPE()
                self._data += data
            else: self._write(data)
コード例 #14
0
    def render_rewrite(self, source, key):
        """
Renders the data identified by the given key.

:param source: Source for rewrite
:param key: Key in source for rewrite

:return: (str) Rendered content
:since:  v1.0.0
        """

        if (self._log_handler is not None): self._log_handler.debug("#echo(__FILEPATH__)# -{0!r}.render_rewrite({1})- (#echo(__LINE__)#)", self, key, context = "pas_tag_parser")
        _return = self.get_source_value(source, key)

        _return = ("" if (_return is None) else Binary.str(_return))
        if (type(_return) is not str): _return = str(_return)

        return _return
コード例 #15
0
ファイル: l10n.py プロジェクト: dNG-git/pas_l10n
    def get_base_path():
        """
Returns the base path to localization specific directories and files.

:return: (str) Localization base path
:since:  v1.0.0
        """

        _return = Settings.get("path_lang")

        if (_return is None):
            _return = (Binary.str(os.environ['PAS_PATH_LANG']) if
                       ("PAS_PATH_LANG" in os.environ) else path.join(
                           Settings.get("path_base"), "lang"))

            Settings.set("path_lang", _return)
        #

        return _return
コード例 #16
0
    def render_json_if_condition(self, json_resource, json_base_path,
                                 json_value_path, operator, value, data):
        """
Checks and renders the content of the "if" condition.

:param json_resource: JSON resource instance
:param json_base_path: JSON base node path
:param json_value_path: JSON value node path
:param operator: Comparison operator
:param value: Comparison value
:param data: Conditional data

:return: (str) Conditional data if successful
:since:  v1.0.0
        """

        if (self._log_handler is not None):
            self._log_handler.debug(
                "#echo(__FILEPATH__)# -{0!r}.render_json_if_condition({1}, {2}, {3}, {4})- (#echo(__LINE__)#)",
                self,
                json_base_path,
                json_value_path,
                operator,
                value,
                context="pas_tag_parser")
        _return = ""

        is_valid = False
        if (json_base_path != ""):
            json_value_path = "{0} {1}".format(json_base_path, json_value_path)

        json_value = (json_resource.get_node(json_value_path) if
                      (isinstance(json_resource, JsonResource)) else "")

        json_value = ("" if (json_value is None) else Binary.str(json_value))
        if (type(json_value) is not str): json_value = str(json_value)

        if (operator == "==" and json_value == value): is_valid = True
        if (operator == "!=" and json_value != value): is_valid = True

        if (is_valid): _return = data
        return _return
コード例 #17
0
    def get_headers(data):
        """
Returns a RFC 7231 compliant dict of headers from the entire HTTP response.

:param data: Input message

:return: (str) Dict with parsed headers; None on error
:since:  v1.0.0
        """

        if (type(data) is not str): data = Binary.str(data)
        header = data.split("\r\n\r\n", 1)[0]
        _return = Header.get_headers(header)

        if (_return is not None and "@nameless" in _return and "\n" not in _return['@nameless']):
            _return['@http'] = _return['@nameless']
            del(_return['@nameless'])
        #

        return _return
コード例 #18
0
    def render_xml_rewrite(self, xml_resource, xml_base_path, xml_value_path):
        """
Renders the data identified by the given node value path in the XML
resource.

:param xml_resource: XML resource instance
:param xml_base_path: XML base node path
:param xml_value_path: XML value node path

:return: (str) Rendered content
:since:  v1.0.0
        """

        if (self._log_handler is not None): self._log_handler.debug("#echo(__FILEPATH__)# -{0!r}.render_xml_rewrite({1}, {2})- (#echo(__LINE__)#)", self, xml_base_path, xml_value_path, context = "pas_tag_parser")
        _return = xml_resource.get_node_value("{0} {1}".format(xml_base_path, xml_value_path))

        _return = ("" if (_return is None) else Binary.str(_return))
        if (type(_return) is not str): _return = str(_return)

        return _return
コード例 #19
0
    def render_rewrite(self, source, key):
        """
Renders the data identified by the given key.

:param source: Source for rewrite
:param key: Key in source for rewrite

:return: (str) Rendered content
:since:  v1.0.0
        """

        if (self._log_handler is not None):
            self._log_handler.debug(
                "#echo(__FILEPATH__)# -{0!r}.render_rewrite({1})- (#echo(__LINE__)#)",
                self,
                key,
                context="pas_tag_parser")
        _return = self.get_source_value(source, key)

        _return = ("" if (_return is None) else Binary.str(_return))
        if (type(_return) is not str): _return = str(_return)

        return _return
コード例 #20
0
    def get_headers(data):
        """
Parses a string of headers.

:param data: String of headers

:return: (dict) Dict with parsed headers; None on error
:since:  v1.0.0
        """

        _return = None

        if (str is not Binary.UNICODE_TYPE and type(data) is Binary.UNICODE_TYPE): data = Binary.str(data)

        if (isinstance(data, str) and len(data) > 0):
            data = Header.RE_HEADER_FOLDED_LINE.sub("\\2\\4\\6", data)
            _return = { }

            headers = data.split("\r\n")

            for header_line in headers:
                header = header_line.split(":", 1)

                if (len(header) == 2):
                    header_name = header[0].strip().lower()
                    header[1] = header[1].strip()

                    if (header_name in _return):
                        if (type(_return[header_name]) is list): _return[header_name].append(header[1])
                        else: _return[header_name] = [ _return[header_name], header[1] ]
                    else: _return[header_name] = header[1]
                elif (len(header[0]) > 0):
                    if ("@nameless" in _return): _return['@nameless'] += "\n" + header[0].strip()
                    else: _return['@nameless'] = header[0].strip()
                #
            #
        #

        return _return