Completed
Push — master ( fe41f8...0e5b36 )
by Roy
01:04
created

pyspider.libs.WSGIXMLRPCApplication.handler()   A

Complexity

Conditions 2

Size

Total Lines 8

Duplication

Lines 0
Ratio 0 %
Metric Value
cc 2
dl 0
loc 8
rs 9.4285
1
#   Copyright (c) 2006-2007 Open Source Applications Foundation
2
#
3
#   Licensed under the Apache License, Version 2.0 (the "License");
4
#   you may not use this file except in compliance with the License.
5
#   You may obtain a copy of the License at
6
#
7
#       http://www.apache.org/licenses/LICENSE-2.0
8
#
9
#   Unless required by applicable law or agreed to in writing, software
10
#   distributed under the License is distributed on an "AS IS" BASIS,
11
#   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
#   See the License for the specific language governing permissions and
13
#   limitations under the License.
14
#
15
#   Origin: https://code.google.com/p/wsgi-xmlrpc/
16
17
18
from six.moves.xmlrpc_server import SimpleXMLRPCDispatcher
19
import logging
20
21
logger = logging.getLogger(__name__)
22
23
24
class WSGIXMLRPCApplication(object):
25
    """Application to handle requests to the XMLRPC service"""
26
27
    def __init__(self, instance=None, methods=[]):
28
        """Create windmill xmlrpc dispatcher"""
29
        try:
30
            self.dispatcher = SimpleXMLRPCDispatcher(allow_none=True, encoding=None)
31
        except TypeError:
32
            # python 2.4
33
            self.dispatcher = SimpleXMLRPCDispatcher()
34
        if instance is not None:
35
            self.dispatcher.register_instance(instance)
36
        for method in methods:
37
            self.dispatcher.register_function(method)
38
        self.dispatcher.register_introspection_functions()
39
40
    def register_instance(self, instance):
41
        return self.dispatcher.register_instance(instance)
42
43
    def register_function(self, function, name=None):
44
        return self.dispatcher.register_function(function, name)
45
46
    def handler(self, environ, start_response):
47
        """XMLRPC service for windmill browser core to communicate with"""
48
49
        if environ['REQUEST_METHOD'] == 'POST':
50
            return self.handle_POST(environ, start_response)
51
        else:
52
            start_response("400 Bad request", [('Content-Type', 'text/plain')])
53
            return ['']
54
55
    def handle_POST(self, environ, start_response):
56
        """Handles the HTTP POST request.
57
58
        Attempts to interpret all HTTP POST requests as XML-RPC calls,
59
        which are forwarded to the server's _dispatch method for handling.
60
61
        Most code taken from SimpleXMLRPCServer with modifications for wsgi and my custom dispatcher.
62
        """
63
64
        try:
65
            # Get arguments by reading body of request.
66
            # We read this in chunks to avoid straining
67
            # socket.read(); around the 10 or 15Mb mark, some platforms
68
            # begin to have problems (bug #792570).
69
70
            length = int(environ['CONTENT_LENGTH'])
71
            data = environ['wsgi.input'].read(length)
72
73
            # In previous versions of SimpleXMLRPCServer, _dispatch
74
            # could be overridden in this class, instead of in
75
            # SimpleXMLRPCDispatcher. To maintain backwards compatibility,
76
            # check to see if a subclass implements _dispatch and
77
            # using that method if present.
78
            response = self.dispatcher._marshaled_dispatch(
79
                data, getattr(self.dispatcher, '_dispatch', None)
80
            )
81
            response += b'\n'
82
        except Exception as e:  # This should only happen if the module is buggy
83
            # internal error, report as HTTP server error
84
            logger.exception(e)
85
            start_response("500 Server error", [('Content-Type', 'text/plain')])
86
            return []
87
        else:
88
            # got a valid XML RPC response
89
            start_response("200 OK", [('Content-Type', 'text/xml'), ('Content-Length', str(len(response)),)])
90
            return [response]
91
92
    def __call__(self, environ, start_response):
93
        return self.handler(environ, start_response)
94