Пример #1
0
    def __call__(self, environ, start_response):
        #  create webob Request
        req = Request(environ)
        req.charset = 'utf8'

        client_id = db.is_authorized(environ['pysmsd.db.path'], req.params.get('name', ''), req.params.get('password', ''))
        if client_id != None:
            environ['pysmsd.client.id'] = client_id
            environ['pysmsd.client.name'] = req.params.get('name')
            return self.application(environ, start_response)
        else:
            return HTTPUnauthorizedJSON()(environ, start_response)
Пример #2
0
    def __call__(self, environ, start_response):
        # going through proxy messes up path_info, so fix it
        if environ['PATH_INFO'].startswith('http'):
            host_url = environ['wsgi.url_scheme']+'://'
            if environ.get('HTTP_HOST'):
                host_url += environ['HTTP_HOST']
            else:
                host_url += environ['SERVER_NAME']
                
                if environ['wsgi.url_scheme'] == 'https':
                    if environ['SERVER_PORT'] != '443':
                        host_url += ':'+environ['SERVER_PORT']
                else:
                    if environ['SERVER_PORT'] != '80':
                        host_url += ':'+environ['SERVER_PORT']

            environ['PATH_INFO'] = environ['PATH_INFO'][len(host_url):]

        #  create webob Request
        req = Request(environ)
        req.charset = 'utf8'

        # try to match a route
        for regex, controller, action, args in self.routes:
            matches = regex.search(req.path_url)
            if matches:
                # interpolate any backreferences into controller, action and args 
                controller = matches.expand(controller)
                action = matches.expand(action)
                
                # add in named groups from the regex
                req.urlvars = matches.groupdict()

                # add in unamed groups (this includes numerically keyed copies of the named groups)
                unamed_groups = matches.groups()
                req.urlvars.update(dict(zip(range(len(unamed_groups)), unamed_groups)))

                # interpolate backreferences into arg values and add to request
                if args:
                    args = dict([(k, urllib.unquote(matches.expand(v))) for k,v in args.items()])
                    req.urlvars.update(args)

                # add a reference to the router
                req.environ['pysmsd.router'] = self

                # load controller
                try:
                    controller = self.load_controller(controller)
                except RouterException, e:
                    logging.exception('wsgiserver: could not load controller.')
                    logging.debug("\n" + '-' * 80)
                    return HTTPNotFoundJSON('Could not load controller: %s' % e)(environ, start_response)
                    
                if controller:
                    # get the action
                    try:
                        logging.debug('--> Req: [%s]' % (req.path_url))
                        action = getattr(controller, action)
                        if action:
                            try:
                                # if auth is needed, validate
                                if req.urlvars.get('auth', 'no') == 'yes':
                                    client_id = db.is_authorized(req.environ['pysmsd.db.path'], req.params.get('name', ''), req.params.get('password', ''))
                                    if client_id != None:
                                        req.environ['pysmsd.client.id'] = client_id
                                        req.environ['pysmsd.client.name'] = req.params.get('name')
                                    else:
                                        return HTTPUnauthorizedJSON()(environ, start_response)

                                # execute action and get response
                                try:
                                    res = action(req)
                                except:
                                    return HTTPInternalServerErrorJSON()(environ, start_response)

                                if isinstance(res, basestring):
                                    if req.path_url[-4:] == 'json':
                                        res = Response(body=res, content_type='application/json')
                                    else:
                                        res = Response(body=res)

                                elif not res:
                                    logging.debug('No such action (0)')
                                    logging.debug("\n" + '-' * 80)
                                    return HTTPNotFoundJSON('No such action')(environ, start_response)

                                logging.debug('<-- res: %s %s' % (res.status, res.content_length))
                                return res(environ, start_response)
                            except:
                                logging.exception('wsgiserver: error executing action.')
                                logging.debug("\n" + '-' * 80)
                                return HTTPInternalServerErrorJSON('Error executing action')(environ, start_response)
                        else:
                            logging.debug('No such action (1)')
                            logging.debug("\n" + '-' * 80)
                            return HTTPNotFoundJSON('No such action')(environ, start_response)
                    except Exception, e:
                        logging.exception('No such action (2)')
                        logging.debug("\n" + '-' * 80)
                        return HTTPNotFoundJSON('No such action: %s' % e)(environ, start_response)
                else:
                    logging.debug('No such controller')
                    logging.debug("\n" + '-' * 80)
                    return HTTPNotFoundJSON('No such controller')(environ, start_response)