3 Simple dispatcher for the REST API.
5 Only intended for test purposes.
10 * ===================================================================
11 * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
12 * ===================================================================
13 * Licensed under the Apache License, Version 2.0 (the "License");
14 * you may not use this file except in compliance with the License.
15 * You may obtain a copy of the License at
17 * http://www.apache.org/licenses/LICENSE-2.0
19 * Unless required by applicable law or agreed to in writing, software
20 * distributed under the License is distributed on an "AS IS" BASIS,
21 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
22 * See the License for the specific language governing permissions and
23 * limitations under the License.
28 logger = logging.getLogger('collector.disp')
32 template_404 = b'''POST {0}'''
34 def set_404_content(url):
36 Called at initialization to set the base URL so that we can serve helpful
37 diagnostics as part of the 404 response.
43 def notfound_404(environ, start_response):
45 Serve the 404 Not Found response.
47 Provides diagnostics in the 404 response showing the hierarchy of valid
50 logger.warning('Unexpected URL/Method: {0} {1}'.format(
51 environ['REQUEST_METHOD'].upper(),
52 environ['PATH_INFO']))
53 start_response('404 Not Found', [ ('Content-type', 'text/plain') ])
54 return [template_404.format(base_url)]
58 A dispatcher which can take HTTP requests in a WSGI environment and invoke
59 appropriate methods for each request.
62 '''Constructor: initialize the pathmap to be empty.'''
65 def __call__(self, environ, start_response):
67 The main callable that the WSGI app will invoke with each request.
69 #----------------------------------------------------------------------
70 # Extract the method and path from the environment.
71 #----------------------------------------------------------------------
72 method = environ['REQUEST_METHOD'].lower()
73 path = environ['PATH_INFO']
74 logger.info('Dispatcher called for: {0} {1}'.format(method, path))
75 logger.debug('Dispatcher environment is: {0}'.format(environ))
77 #----------------------------------------------------------------------
78 # See if we have a handler for this path, and if so invoke it.
79 # Otherwise, return a 404.
80 #----------------------------------------------------------------------
81 handler = self.pathmap.get((method, path), notfound_404)
82 logger.debug('Dispatcher will use handler: {0}'.format(handler))
83 return handler(environ, start_response)
85 def register(self, method, path, function):
87 Register a handler for a method/path, adding it to the pathmap.
89 logger.debug('Registering for {0} at {1}'.format(method, path))
90 print('Registering for {0} at {1}'.format(method, path))
91 self.pathmap[method.lower(), path] = function