Exemplo n.º 1
0
    def __call__(self, environ, start_response):
        req = Request(environ)
        if self.notheme_request(req):
            return self.app(environ, start_response)

        req.environ['deliverance.base_url'] = req.application_url
        ## FIXME: copy_get?:
        orig_req = Request(environ.copy())
        if 'deliverance.log' in req.environ:
            log = req.environ['deliverance.log']
        else:
            log = self.log_factory(req, self, **self.log_factory_kw)
            ## FIXME: should this be put in both the orig_req and this req?
            req.environ['deliverance.log'] = log

        def resource_fetcher(url, retry_inner_if_not_200=False):
            """
            Return the Response object for the given URL
            """
            return self.get_resource(url, orig_req, log,
                                     retry_inner_if_not_200)

        if req.path_info_peek() == '.deliverance':
            req.path_info_pop()
            resp = self.internal_app(req, resource_fetcher)
            return resp(environ, start_response)
        rule_set = self.rule_getter(resource_fetcher, self.app, orig_req)
        clientside = rule_set.check_clientside(req, log)
        if clientside and req.url in self.known_html:
            if req.cookies.get('jsEnabled'):
                log.debug(self,
                          'Responding to %s with a clientside theme' % req.url)
                return self.clientside_response(req, rule_set,
                                                resource_fetcher,
                                                log)(environ, start_response)
            else:
                log.debug(
                    self,
                    'Not doing clientside theming because jsEnabled cookie not set'
                )

        head_response = None
        if req.method == "HEAD":
            # We need to copy the request instead of reusing it,
            # in case the downstream app modifies req.environ in-place
            head_req = req.copy()
            head_response = head_req.get_response(self.app)
            req.method = "GET"

        resp = req.get_response(self.app)

        ## FIXME: also XHTML?
        if resp.content_type != 'text/html':
            ## FIXME: remove from known_html?
            return resp(environ, start_response)

        # XXX: Not clear why such responses would have a content type, but
        # they sometimes do (from Zope/Plone, at least) and that then breaks
        # when trying to apply a theme.
        if resp.status_int in (301, 302, 304):
            return resp(environ, start_response)

        if resp.content_length == 0:
            return resp(environ, start_response)

        if resp.body == '':
            return resp(environ, start_response)

        if clientside and req.url not in self.known_html:
            log.debug(
                self,
                '%s would have been a clientside check; in future will be since we know it is HTML'
                % req.url)
            self.known_titles[req.url] = self._get_title(resp.body)
            self.known_html.add(req.url)
        resp = rule_set.apply_rules(req,
                                    resp,
                                    resource_fetcher,
                                    log,
                                    default_theme=self.default_theme(environ))
        if clientside:
            resp.decode_content()
            resp.body = self._substitute_jsenable(resp.body)
        resp = log.finish_request(req, resp)

        if head_response:
            head_response.headers = resp.headers
            resp = head_response

        return resp(environ, start_response)
Exemplo n.º 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 = \
                                        req.environ['pysmsd.db'].is_authorized(
                                                        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
                                res = action(req)

                                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)
Exemplo n.º 3
0
 def __call__(self, environ, start_response):
     request = Request(environ)
     request.is_mobile = bool(self.detect_mobile(request))
     response = request.get_response(self.application)
     return response(environ, start_response)
Exemplo n.º 4
0
    def respond(self, environ, start_response):
        req = Request(environ)
        if req.environ.get('paste.throw_errors'):
            return self.application(environ, start_response)
        base_path = req.application_url + '/' + self.debug_url_prefix
        req.environ['paste.throw_errors'] = True
        started = []
        def detect_start_response(status, headers, exc_info=None):
            try:
                return start_response(status, headers, exc_info)
            except:
                raise
            else:
                started.append(True)
        try:
            __traceback_supplement__ = errormiddleware.Supplement, self, environ
            app_iter = self.application(environ, detect_start_response)
            
            # Don't create a list from a paste.fileapp object 
            if isinstance(app_iter, fileapp._FileIter): 
                return app_iter
            
            try:
                return_iter = list(app_iter)
                return return_iter
            finally:
                if hasattr(app_iter, 'close'):
                    app_iter.close()
        except:
            exc_info = sys.exc_info()

            # Tell the Registry to save its StackedObjectProxies current state
            # for later restoration
            ## FIXME: needs to be more abstract (something in the environ)
            ## to remove the Paste dependency
            registry.restorer.save_registry_state(environ)

            count = get_debug_count(environ)
            view_uri = self.make_view_url(environ, base_path, count)
            if not started:
                headers = [('content-type', 'text/html')]
                headers.append(('X-Debug-URL', view_uri))
                start_response('500 Internal Server Error',
                               headers,
                               exc_info)
            environ['wsgi.errors'].write('Debug at: %s\n' % view_uri)

            exc_data = collector.collect_exception(*exc_info)
            exc_data.view_url = view_uri
            if self.reporters:
                for reporter in self.reporters:
                    reporter.report(exc_data)
            debug_info = DebugInfo(count, exc_info, exc_data, base_path,
                                   environ, view_uri, self.error_template,
                                   self.templating_formatters, self.head_html,
                                   self.footer_html, self.libraries)
            assert count not in self.debug_infos
            self.debug_infos[count] = debug_info

            if self.xmlhttp_key:
                if self.xmlhttp_key in req.params:
                    exc_data = collector.collect_exception(*exc_info)
                    html, extra_html = formatter.format_html(
                        exc_data, include_hidden_frames=False,
                        include_reusable=False, show_extra_data=False)
                    return [html, extra_html]

            # @@: it would be nice to deal with bad content types here
            return debug_info.content()
Exemplo n.º 5
0
    def __call__(self, environ, start_response):
        request = Request(environ)

        try:
            endpoint, _ = self.router.match(request)
        except NotFoundException:
            endpoint = {}

        # NOTE: We don't track per request and response metrics for /v1/executions/<id> and some
        # other endpoints because this would result in a lot of unique metrics which is an
        # anti-pattern and causes unnecessary load on the metrics server.
        submit_metrics = endpoint.get('x-submit-metrics', True)
        if not submit_metrics:
            LOG.debug('Not submitting request metrics for path: %s' % (request.path))
            return self.app(environ, start_response)

        metrics_driver = get_driver()

        key = '%s.request.total' % (self._service_name)
        metrics_driver.inc_counter(key)

        key = '%s.request.method.%s' % (self._service_name, request.method)
        metrics_driver.inc_counter(key)

        path = request.path.replace('/', '_')
        key = '%s.request.path.%s' % (self._service_name, path)
        metrics_driver.inc_counter(key)

        if self._service_name == 'stream':
            # For stream service, we also record current number of open connections.
            # Due to the way stream service works, we need to utilize eventlet posthook to
            # correctly set the counter when the connection is closed / full response is returned.
            # See http://eventlet.net/doc/modules/wsgi.html#non-standard-extension-to-support-post-
            # hooks for details

            # Increase request counter
            key = '%s.request' % (self._service_name)
            metrics_driver.inc_counter(key)

            # Increase "total number of connections" gauge
            metrics_driver.inc_gauge('stream.connections', 1)

            start_time = get_datetime_utc_now()

            def update_metrics_hook(env):
                # Hook which is called at the very end after all the response has been sent and
                # connection closed
                time_delta = (get_datetime_utc_now() - start_time)
                duration = time_delta.total_seconds()

                # Send total request time
                metrics_driver.time(key, duration)

                # Decrease "current number of connections" gauge
                metrics_driver.dec_gauge('stream.connections', 1)

            # NOTE: Some tests mock environ and there 'eventlet.posthooks' key is not available
            if 'eventlet.posthooks' in environ:
                environ['eventlet.posthooks'].append((update_metrics_hook, (), {}))

            return self.app(environ, start_response)
        else:
            # Track and time current number of processing requests
            key = '%s.request' % (self._service_name)

            with CounterWithTimer(key=key):
                return self.app(environ, start_response)
Exemplo n.º 6
0
    def __call__(self, environ, start_response):
        """Resolves the URL in PATH_INFO, and uses wsgi.routing_args
        to pass on URL resolver results."""
        old_method = None
        if self.use_method_override:
            req = None

            # In some odd cases, there's no query string
            try:
                qs = environ['QUERY_STRING']
            except KeyError:
                qs = ''
            if '_method' in qs:
                req = Request(environ)
                req.errors = 'ignore'
                if '_method' in req.GET:
                    old_method = environ['REQUEST_METHOD']
                    environ['REQUEST_METHOD'] = req.GET['_method'].upper()
                    if self.log_debug:
                        log.debug(
                            "_method found in QUERY_STRING, altering "
                            "request method to %s", environ['REQUEST_METHOD'])
            elif environ['REQUEST_METHOD'] == 'POST' and is_form_post(environ):
                if req is None:
                    req = Request(environ)
                    req.errors = 'ignore'
                if '_method' in req.POST:
                    old_method = environ['REQUEST_METHOD']
                    environ['REQUEST_METHOD'] = req.POST['_method'].upper()
                    if self.log_debug:
                        log.debug(
                            "_method found in POST data, altering "
                            "request method to %s", environ['REQUEST_METHOD'])

        # Run the actual route matching
        # -- Assignment of environ to config triggers route matching
        if self.singleton:
            config = request_config()
            config.mapper = self.mapper
            config.environ = environ
            match = config.mapper_dict
            route = config.route
        else:
            results = self.mapper.routematch(environ=environ)
            if results:
                match, route = results[0], results[1]
            else:
                match = route = None

        if old_method:
            environ['REQUEST_METHOD'] = old_method

        if not match:
            match = {}
            if self.log_debug:
                urlinfo = "%s %s" % (environ['REQUEST_METHOD'],
                                     environ['PATH_INFO'])
                log.debug("No route matched for %s", urlinfo)
        elif self.log_debug:
            urlinfo = "%s %s" % (environ['REQUEST_METHOD'],
                                 environ['PATH_INFO'])
            log.debug("Matched %s", urlinfo)
            log.debug("Route path: '%s', defaults: %s", route.routepath,
                      route.defaults)
            log.debug("Match dict: %s", match)

        url = URLGenerator(self.mapper, environ)
        environ['wsgiorg.routing_args'] = ((url), match)
        environ['routes.route'] = route
        environ['routes.url'] = url

        if route and route.redirect:
            route_name = '_redirect_%s' % id(route)
            location = url(route_name, **match)
            log.debug(
                "Using redirect route, redirect to '%s' with status"
                "code: %s", location, route.redirect_status)
            start_response(route.redirect_status,
                           [('Content-Type', 'text/plain; charset=utf8'),
                            ('Location', location)])
            return []

        # If the route included a path_info attribute and it should be used to
        # alter the environ, we'll pull it out
        if self.path_info and 'path_info' in match:
            oldpath = environ['PATH_INFO']
            newpath = match.get('path_info') or ''
            environ['PATH_INFO'] = newpath
            if not environ['PATH_INFO'].startswith('/'):
                environ['PATH_INFO'] = '/' + environ['PATH_INFO']
            environ['SCRIPT_NAME'] += re.sub(
                r'^(.*?)/' + re.escape(newpath) + '$', r'\1', oldpath)

        response = self.app(environ, start_response)

        # Wrapped in try as in rare cases the attribute will be gone already
        try:
            del self.mapper.environ
        except AttributeError:
            pass
        return response
Exemplo n.º 7
0
def application(environ, start_response):
    """this application merely spits out the keys of the form that was
    posted. we are using webob Request and Response for brevity
    """
    request = Request(environ)
    return Response(str(request.POST.keys()))(environ, start_response)
Exemplo n.º 8
0
    def __call__(self,environ,start_response):
        '''
        controller here to parse user's http request
        '''
        
        
        #use webob to pack the environment value
        req = Request(environ)
        res = Response()
           
        #here we set a flag value
        #flag == HTTPOk: operation success
        #flag != HTTPOk: operation failed 
        req.headers['http-flag'] = HTTPOk
        #here content type includes scloud-object, scloud-domain, scloud-container, scloud-capability
        #later we may add scloud-queue type
        self.content_type = req.headers.get('Content-Type', '')
        #DomainName.scloud.ecust.com
        self.host = req.headers.get('Host', '')
        self.cdmi_version = req.headers.get('X-CDMI-Specification-Version', '')
        self.authorization = req.headers.get('Authorization', '')
        self.date = req.headers.get('Date', '')
        self.path = req.path
 
        #Make sure req.headers not ""
        if not (self.content_type and self.host and self.cdmi_version and self.date and self.authorization):
            req.headers['http-flag'] = HTTPBadRequest
            return self.app(environ,start_response)
        
        #Set X-Auth-User and X-Auth-Key
        req.headers['X-Auth-User'], req.headers['X-Auth-Key'] = self.authorization.strip().split(':')
        #make sure X-Auth-User and X-Auth-Key not ""
        if not (req.headers['X-Auth-User'] and req.headers['X-Auth-Key']):
            req.headers['http-flag'] = HTTPBadRequest
            return self.app(environ,start_response)
            
        #Make sure content-type is legal
        if self.content_type not in ['scloud-domain', 'scloud-container', 'scloud-object', 'scloud-capability', 'scloud-queue']:
            req.headers['http-flag'] = HTTPBadRequest
            return self.app(environ,start_response)
            
        
        url_path = req.path.strip('/').split('/')
        
        req.headers['url_pattern'] = url_path[0]
        
        if url_path[0]=='scloud_domain':
            req.headers['domain'] = url_path[1]
            
            return self.app(environ,start_response)
        
        elif url_path[0] == 'scloud_container':
            req.headers['domain'] = url_path[1]
            req.headers['container'] = url_path[2:]
            
            return self.app(environ,start_response)
        
        elif url_path[0] == 'scloud_object':
            req.headers['domain'] = url_path[1]
            req.headers['container'] = url_path[2:-1]
            req.headers['object'] = url_path[-1]
            
            return self.app(environ,start_response)
        
        elif url_path[0] == 'scloud_user':
            req.headers['domain'] = url_path[1]
            req.headers['container'] = url_path[2:-1]
            req.headers['object'] = url_path[-1]
            
            return self.app(environ,start_response)
            
        else:
            start_response("403 AccessDenied",[("Content-type", "text/plain"),
                                         ])
            return ''
def test_request_no_method():
    assert Request({}).method == 'GET'
Exemplo n.º 10
0
def application(environ, start_response):
    import cgi, os, sys
    from datetime import datetime
    from webob import Request, Response
    request = Request(environ)

    import redis
    r = redis.StrictRedis(host='localhost', port=6379, db=1)
    y = datetime.today().year
    m = datetime.today().month
    d = datetime.today().day
    post = request.POST
    #for row in range(int(len(post.getall('changes[value][]')))):
    #r.set("%s_%s"%(post.getall('changes[value][]')[int(row)].split("<#>")[1],post['changes[account]'].split('<#>')[3]),"%s"%post.getall('changes[value][]')[int(row)].split("<#>")[2],57600)

    #cur.execute("""create table if not exists omnivore_question_%s_%s_%s
    #						(
    #						id serial8 primary key,
    #no text,agent text, module text,domain text,title text,link text, quest text, answer text, time timestamp default now(), process_time numeric,img_id text,
    #							update_time timestamp default now() )"""%(y,m,d))

    #cur.execute("""insert into  example (agent,module,domain,title,link,quest,answer) values(%s,%s,%s,%s,%s,%s,%s) """,(post['agent'],module,post['domain'],post['title'],post['link'],post['value'],post['answer']+'ask'))
    #page ="test"
    #if post['value'] =='long sleeve':
    #	quest ="<h5>Tay dài</h5>"
    #else:
    #	quest =""
    if post['agent'] == '*****@*****.**':
        dog = 'bấm phím e để tăng tốc độ dàn trang'
    elif post['agent'] == '*****@*****.**':
        dog = 'bấm phím e để tăng tốc độ dàn trang'
    else:
        dog = ''

    if post['value'] == 'low heel':
        quest = """PASS thể thao đế xuồng thấp(21/04),có gót, dốc, dạng dress shoes.SKIP ko đế ,Athletic (ngoại trừ fashion Sneaker có lấy),Outdoor shoes; Men's shoes (27/04) <a href='https://172.16.29.6/wsgi/omnivore/demo/LOW_%20HEEL_%20KH_%20traloi_27-Apr-16.htm' target='_blank'>update</a> """
    elif post['value'] == 'flat':
        quest = "SKIP sneaker,athletic,low heel, wedges, platform. Pass:đế <=1.5cm, men(1-3cm),sliper,Slip on (trừ đế trắng giống sneaker),bale,Mokassins <a href='https://172.16.29.6/wsgi/omnivore/demo/FLAT_%20KH_%20traloi_28-Apr-16.htm' target='_blank'>update</a> "
    elif post['value'] == 'tunic':
        quest = 'Tunic lấy váy thụng có buộc eo như váy xanh trong hướng dẫn'
    elif post['value'] == 'sheath':
        quest = 'váy bó sát thật là bó'
    elif post['value'] == 'high heel':
        quest = 'PASS (high heel) thể thao, giầy giấu đế(25/04/16)'
    elif post['value'] == 'wedge heel':
        quest = """PASS(de xuong) thể thao, cách điệu, giấu đế;Chụp sai hướng nhìn giống wedge heel tham khảo title (25/04/16) <a href='https://172.16.29.6/wsgi/omnivore/demo/WEDGE_HEEL_KH_traloi_26-Apr-16.htm' target='_blank'>update</a> """
    elif post['value'] == 'tstrap':
        quest = """ <a href='https://172.16.29.6/wsgi/omnivore/demo/image/7.SilhouettesTrainingHarveyNash_17Jul15_tran.htm#id.uu9d4xfk7yvi' target='_blank' > Xem tai lieu</a>"""
    elif post['value'] == 'full coverage':
        quest = """<a href='https://172.16.29.6/wsgi/omnivore/demo/image/7.SilhouettesTrainingHarveyNash_17Jul15_tran.htm#id.x3rlx0j13gbs' target='_blank'> xem tai lieu</a> = full back coverage """
    elif post['value'] == 'slingback':
        quest = """<a href='https://172.16.29.6/wsgi/omnivore/demo/image/7.SilhouettesTrainingHarveyNash_17Jul15_tran.htm#id.2quqatydm8td' target='_blank'> xem tai lieu</a>"""
    elif post['value'] == 'black':
        quest = """nero=noir=schwarz= black """
    elif post['value'] == 'purple':
        quest = """Lilac =lila=lavender = violet = purple """
    elif post['value'] == 'gray':
        quest = """gris=grau(tieng duc)=gray """
    elif post['value'] == 'brown':
        quest = """braun=brown """
    elif post['value'] == 'red':
        quest = """rosso(tieng italy)=rouge=rot=red """
    elif post['value'] == 'pink':
        quest = """rosa=pink """
    elif post['value'] == 'green':
        quest = """olive=Grün=green """
    elif post['value'] == 'white':
        quest = """blank=weiß=white, ivory chap nhan duoc la white """
    elif post['value'] == 'yellow':
        quest = """jaune=yellow """
    elif post['value'] == 'blue':
        quest = """navy=bleu=blue """
    elif post['value'] == 'vneck':
        quest = """cổ ngũ giác không lấy,áo con ko lấy """
    elif post['value'] == 'round neck':
        quest = """cổ tau = tron"""
    else:
        quest = ''
    #items = [1, 2, 3, 4, 5, 6, 7]
    #a= random.sample(items,1)[0]
    #random.sample([1, 2, 3, 4, 5],  3)  # Choose 3 elements http://emojipedia-us.s3.amazonaws.com/cache/c2/91/c2918417595a77f6e2257eb6ea996a2d.png

    #	quest ="<img src='http://www.anglaisfacile.com/cgi2/myexam/images/21961.gif'>" + quest
    page = """document.getElementById('guide').innerHTML="%s<span id='trangt'></span>%s<a href='https://172.16.29.6/wsgi/omnivore/demo/consensus_cu' target='_blank'>$</a>  <a href='https://172.16.29.6' target='_blank'>?</a> Yamaha,comming soon,not image=Placeholder | Youth có lấy".fontsize(1);
			 if (document.getElementById('attributetype').innerHTML != 'color'){
			 document.getElementById('log_all').innerHTML =(document.getElementById('value').innerHTML).fontcolor('red') +"<br /><span='test'>%s</span>".fontsize(0.1).fontcolor('green');}""" % (
        dog, quest, quest)

    page += """
			//var buttongt = document.createElement('button');
			//buttongt.id='trangt';
			//buttongt.style.zIndex = 1000;
			//title.style.position = "fixed";
			//buttongt.style.position = "absolute";
			//buttongt.style.top = "1%";
			//buttongt.style.left= "80%";
			//buttongt.style.font='30px bold';
			//buttongt.innerHTML='test';	
			//document.body.appendChild(buttongt);	
	
	//document.getElementById('trangt').onclick= function(){
	//window.open("http://172.16.29.6");}
	//document.getElementById('sanluong').onclick= function(){
	//window.open("https://172.16.29.6/wsgi/omnivore/demo/report_quantity_module_by_day");}"""
    response = Response(body=page,
                        content_type="text/javascript",
                        charset="utf8",
                        status="200 OK")

    return response(environ, start_response)
Exemplo n.º 11
0
    def __call__(self, environ, start_response):
        request = Request(environ)
        trace_utils.activate_distributed_headers(
            self._tracer,
            int_config=ddconfig.pylons,
            request_headers=request.headers)

        with self._tracer.trace("pylons.request",
                                service=self._service,
                                span_type=SpanTypes.WEB) as span:
            span.set_tag(SPAN_MEASURED_KEY)
            # Set the service in tracer.trace() as priority sampling requires it to be
            # set as early as possible when different services share one single agent.

            # set analytics sample rate with global config enabled
            span.set_tag(
                ANALYTICS_SAMPLE_RATE_KEY,
                ddconfig.pylons.get_analytics_sample_rate(
                    use_global_config=True))

            trace_utils.set_http_meta(span,
                                      ddconfig.pylons,
                                      request_headers=request.headers)

            if not span.sampled:
                return self.app(environ, start_response)

            # tentative on status code, otherwise will be caught by except below
            def _start_response(status, *args, **kwargs):
                """ a patched response callback which will pluck some metadata. """
                if len(args):
                    response_headers = args[0]
                else:
                    response_headers = kwargs.get("response_headers", {})
                http_code = int(status.split()[0])
                trace_utils.set_http_meta(span,
                                          ddconfig.pylons,
                                          status_code=http_code,
                                          response_headers=response_headers)
                return start_response(status, *args, **kwargs)

            try:
                return self.app(environ, _start_response)
            except Exception as e:
                # store current exceptions info so we can re-raise it later
                (typ, val, tb) = sys.exc_info()

                # e.code can either be a string or an int
                code = getattr(e, "code", 500)
                try:
                    int(code)
                except (TypeError, ValueError):
                    code = 500
                trace_utils.set_http_meta(span,
                                          ddconfig.pylons,
                                          status_code=code)

                # re-raise the original exception with its original traceback
                reraise(typ, val, tb=tb)
            except SystemExit:
                span.set_tag(http.STATUS_CODE, 500)
                span.error = 1
                raise
            finally:
                controller = environ.get("pylons.routes_dict",
                                         {}).get("controller")
                action = environ.get("pylons.routes_dict", {}).get("action")

                # There are cases where users re-route requests and manually
                # set resources. If this is so, don't do anything, otherwise
                # set the resource to the controller / action that handled it.
                if span.resource == span.name:
                    span.resource = "%s.%s" % (controller, action)

                url = "%s://%s:%s%s" % (
                    environ.get("wsgi.url_scheme"),
                    environ.get("SERVER_NAME"),
                    environ.get("SERVER_PORT"),
                    environ.get("PATH_INFO"),
                )
                trace_utils.set_http_meta(
                    span,
                    ddconfig.pylons,
                    method=environ.get("REQUEST_METHOD"),
                    url=url,
                    query=environ.get("QUERY_STRING"),
                )
                if controller:
                    span._set_str_tag("pylons.route.controller", controller)
                if action:
                    span._set_str_tag("pylons.route.action", action)
Exemplo n.º 12
0
 def __call__(self, env, start_response):
     if not self.storage_domain:
         return self.app(env, start_response)
     given_domain = env['HTTP_HOST']
     port = ''
     if ':' in given_domain:
         given_domain, port = given_domain.rsplit(':', 1)
     if given_domain == self.storage_domain[1:]:  # strip initial '.'
         return self.app(env, start_response)
     a_domain = given_domain
     if not a_domain.endswith(self.storage_domain):
         if self.memcache is None:
             self.memcache = cache_from_env(env)
         error = True
         for tries in xrange(self.lookup_depth):
             found_domain = None
             if self.memcache:
                 memcache_key = ''.join(['cname-', a_domain])
                 found_domain = self.memcache.get(memcache_key)
             if not found_domain:
                 ttl, found_domain = lookup_cname(a_domain)
                 if self.memcache:
                     memcache_key = ''.join(['cname-', given_domain])
                     self.memcache.set(memcache_key,
                                       found_domain,
                                       timeout=ttl)
             if found_domain is None or found_domain == a_domain:
                 # no CNAME records or we're at the last lookup
                 error = True
                 found_domain = None
                 break
             elif found_domain.endswith(self.storage_domain):
                 # Found it!
                 self.logger.info(
                     _('Mapped %(given_domain)s to %(found_domain)s') % {
                         'given_domain': given_domain,
                         'found_domain': found_domain
                     })
                 if port:
                     env['HTTP_HOST'] = ':'.join([found_domain, port])
                 else:
                     env['HTTP_HOST'] = found_domain
                 error = False
                 break
             else:
                 # try one more deep in the chain
                 self.logger.debug(_('Following CNAME chain for  ' \
                         '%(given_domain)s to %(found_domain)s') %
                         {'given_domain': given_domain,
                          'found_domain': found_domain})
                 a_domain = found_domain
         if error:
             if found_domain:
                 msg = 'CNAME lookup failed after %d tries' % \
                         self.lookup_depth
             else:
                 msg = 'CNAME lookup failed to resolve to a valid domain'
             resp = HTTPBadRequest(request=Request(env),
                                   body=msg,
                                   content_type='text/plain')
             return resp(env, start_response)
     return self.app(env, start_response)
Exemplo n.º 13
0
def extract_post(environ):
    request = Request(environ)
    if request.content_type == 'application/json':
        return request.json
    params = request.POST
    return params.dict_of_lists()
Exemplo n.º 14
0
def extract_get(environ):
    request = Request(environ)
    params = request.GET
    return params.dict_of_lists()
Exemplo n.º 15
0
 def wrapped(environ, start_response):
     request = Request(environ)
     app = view(request).response()
     return app(environ, start_response)
Exemplo n.º 16
0
 def _get_form_data(self, environ):
     request = Request(environ)
     query = dict(request.GET)
     query.update(request.POST)
     return query
Exemplo n.º 17
0
 def new_app(environ, start_response):
     req = Request(environ)
     for i in range(0, num_to_pop):
         req.path_info_pop()
     return app(environ, start_response)
Exemplo n.º 18
0
def web_app(environ, start_response):
    request = Request(environ)
    if request.path == '/':
        template = ('<html><body>'
                    '<form method=POST action="/invite">invite <input name=id /> '
                    'count<input name=count value=10 /> name<input name=name /><input type=submit /></form>'
                    '<form method=POST action="/add">add <input name="id" /><input name="pwd" /> '
                    'group:<input name=group /><input type=submit /></form>'
                    '<pre>%s</pre></body></html>')
        content = []
        content.append('<h1>RUNNING</h1><hr />')
        now = time.time()
        for cur in accountdb.scan('RUNNING'):
            cur['mintime'] = datetime.datetime.fromtimestamp(cur['intime'])
            cur['mnextime'] = cur['nextime'] - time.time()
            content.append('%(mintime)s <a href="/log?id=%(id)s">%(id)s</a>:%(invite)s %(name)s lv:%(lv)s '
                    'rounds:%(rounds)s <a href="/stop?id=%(id)s">stop</a>' % cur)
        content.append('<h1>PENDING</h1><hr />')
        for cur in accountdb.scan('PENDING'):
            cur['mintime'] = datetime.datetime.fromtimestamp(cur['intime'])
            cur['mnextime'] = cur['nextime'] - time.time()
            content.append('%(mintime)s <a href="/log?id=%(id)s">%(id)s</a>:%(invite)s %(name)s lv:%(lv)s '
                    'rounds:%(rounds)s %(mnextime)s <a href="/run?id=%(id)s&done=0">run</a> '
                    '<a href="/rm?id=%(id)s">del</a>' % cur)
        content.append('<h1>DONE</h1><hr />')
        done = []
        for cur in accountdb.scan('DONE'):
            cur['mintime'] = datetime.datetime.fromtimestamp(cur['intime'])
            cur['mnextime'] = cur['nextime'] - time.time()
            content.append('%(mintime)s <a href="/log?id=%(id)s">%(id)s</a>:%(invite)s %(name)s lv:%(lv)s '
                    'rounds:%(rounds)s' % cur)
        content.append(' '.join(done))
        content.append('<h1>FAILED</h1><hr />')
        for cur in accountdb.scan('FAILED'):
            cur['mintime'] = datetime.datetime.fromtimestamp(cur['intime'])
            cur['mnextime'] = cur['nextime'] - time.time()
            content.append('%(mintime)s <a href="/log?id=%(id)s">%(id)s</a>:%(invite)s %(name)s lv:%(lv)s '
                    'rounds:%(rounds)s <a href="/run?id=%(id)s&done=0">run</a>' % cur)
        # return 
        start_response("200 OK", [("Content-Type", "text/html")])
        return template % '\n'.join([x.encode('utf8') for x in content])
    elif request.path == '/add':
        _id = request.POST['id']
        pwd = request.POST['pwd']
        group = request.POST['group']
        accountdb.add(_id, pwd, group=group)
        start_response("302 FOUND", [("Location", "/")])
        return 'redirect'
    elif request.path == '/invite':
        invitation_id = request.POST['id']
        count = request.POST['count']
        name_prefix = request.POST.get('name')
        def do(invitation_id, count):
            for _ in range(count):
                try:
                    ret = regist.all_in_one(invitation_id, name_prefix)
                except Exception, e:
                    ret = [e, ]
                finally:
                    message = ' '.join([str(x) for x in ret])
                    print message
                    with open('/tmp/libma.%s.log' % invitation_id, 'a') as fp:
                        fp.write(message)
                        fp.write('\n')
Exemplo n.º 19
0
def identify(self, environ):
    """this method is called when a request is incoming.

    After the challenge has been called we might get here a response
    from an openid provider.

    """

    request = Request(environ)
    # #1659 fix - Use PATH_INFO rather than request.path as the former
    #             strips off the mount point.
    path = environ['PATH_INFO']

    # first test for logout as we then don't need the rest
    if path == self.logout_handler_path:
        res = Response()
        # set forget headers
        for a,v in self.forget(environ,{}):
            res.headers.add(a,v)
        res.status = 302

        res.location = get_full_path(self.logged_out_url, environ)
        
        environ['repoze.who.application'] = res
        return {}

    identity = {}

    # first we check we are actually on the URL which is supposed to be the
    # url to return to (login_handler_path in configuration)
    # this URL is used for both: the answer for the login form and
    # when the openid provider redirects the user back.
    if path == self.login_handler_path:

    # in the case we are coming from the login form we should have 
    # an openid in here the user entered
        open_id = request.params.get(self.openid_field, None)
        if environ['repoze.who.logger'] is not None:
            environ['repoze.who.logger'].debug('checking openid results for : %s ' %open_id)

        if open_id is not None:
            open_id = open_id.strip()

        # we don't do anything with the openid we found ourselves but we put it in here
        # to tell the challenge plugin to initiate the challenge
        identity['repoze.whoplugins.openid.openid'] = environ['repoze.whoplugins.openid.openid'] = open_id

        # this part now is for the case when the openid provider redirects
        # the user back. We should find some openid specific fields in the request.
        mode=request.params.get("openid.mode", None)
        if mode=="id_res":
            oidconsumer = self.get_consumer(environ)
            info = oidconsumer.complete(request.params, request.url)
            if info.status == consumer.SUCCESS:

                fr = ax.FetchResponse.fromSuccessResponse(info)
                if fr is not None:
                    items = chain(self.ax_require.items(), self.ax_optional.items())
                    for key, value in items:
                        try:
                            identity['repoze.who.plugins.openid.' + key] = fr.get(value)
                        except KeyError:
                            pass

                fr = sreg.SRegResponse.fromSuccessResponse(info)
                if fr is not None:
                    items = chain(self.sreg_require, self.sreg_optional)
                    for key in items:
                        try:
                            identity['repoze.who.plugins.openid.' + key] = fr.get(key)
                        except KeyError:
                            pass

                environ['repoze.who.logger'].info('openid request successful for : %s ' %open_id)

                display_identifier = info.identity_url

                # remove this so that the challenger is not triggered again
                del environ['repoze.whoplugins.openid.openid']

                # store the id for the authenticator
                identity['repoze.who.plugins.openid.userid'] = display_identifier

                # now redirect to came_from or the success page
                self.redirect_to_logged_in(environ)
                return identity

            # TODO: Do we have to check for more failures and such?
            # 
        elif mode=="cancel":
            # cancel is a negative assertion in the OpenID protocol,
            # which means the user did not authorize correctly.
            environ['repoze.whoplugins.openid.error'] = 'OpenID authentication failed.'
            pass
    return identity
Exemplo n.º 20
0
 def __call__(self, environ, start_response):
     if self._users:
         request = Request(environ)
         if not self.is_authorized(request):
             return self._login(environ, start_response)
     return self._app(environ, start_response)
Exemplo n.º 21
0
 def __call__(self, env, start_response):
     req = Request(env)
     if req.path == '/healthcheck':
         return self.GET(req)(env, start_response)
     else:
         return self.app(env, start_response)
Exemplo n.º 22
0
def application(environment, start_response):
    from webob import Request, Response
    request = Request(environment)
    params = request.params
    post = request.POST
    res = Response()

    import pyad.conn, pyad.login
    importlib.reload(pyad.conn)
    importlib.reload(pyad.login)

    # Get the session object from the environ
    session = environment['beaker.session']

    # Set some other session variable
    #session['user_id'] = 10
    #user_id = 'user_id' in session

    if not 'username' in session:
        page = pyad.login.loginform
    elif not 'password' in session:
        page = pyad.login.loginform
    else:
        user = session['username']
        passwd = session['password']

        import psycopg2, pyad.module
        try:
            con = psycopg2.connect(pyad.conn.conn)
        except:
            page = "Can not access databases"

        cur = con.cursor()
        cur.execute(
            "select username,account_password,account_level from account where username=%s and account_password=%s ",
            (
                user,
                passwd,
            ))
        ps = cur.fetchall()
        if len(ps) == 0:
            page = pyad.login.login_again
        else:
            if int(ps[0][2]) == 2:
                importlib.reload(pyad.module)
                from pyad.module import head, headlink, menuadmin, menuuser, load, save, menuhead, menufoot

                from datetime import datetime, date
                year_today = date.today().year
                month_today = date.today().month
                day_today = date.today().day
                if not 'display' in post:
                    display = 200
                else:
                    display = post['display']

                if not 'table' in post:
                    table = ''
                else:
                    table = post['table']
                if table == "":
                    cur.execute("select")
                else:
                    cur.execute("select * from %s limit 0" % table)
                colHeaders = [
                    desc[0].title().replace("_", " ")
                    for desc in cur.description
                ]
                cols = [desc[0] for desc in cur.description]
                columns = []
                for colname in cols:
                    if colname == 'id':
                        columns.append({'readOnly': 'true'})
                    elif colname == 'account_password':
                        columns.append({"type": "password"})
                    elif colname == 'update_time':
                        columns.append({'readOnly': 'true'})
                    elif colname == 'account_level':
                        columns.append({'type': 'numeric'})
                    else:
                        columns.append({})

                saveurl = """'%s/save_account'""" % save
                loadurl = """'%s/load_account_manager'""" % load
                page = ""
                page += head
                page += "<title>Account manager</title>"
                page += headlink
                page += """</head>
				<body>"""
                page += menuhead
                if int(ps[0][2]) == 2:
                    page += menuadmin

                else:
                    page += menuuser
                page += menufoot
                page += """<br />
							<br />"""

                page += """<ul class="nav nav-tabs">
								<li class="active"><a href="%s/account_manager">%s</a></li>
							</ul>
							
									  <h2>Table  %s </h2> """ % (pyad.module.control, table, table)

                page += """		<br />
								<form method="post" action="">
								  <input list="table" name="table" value="%s" onchange='if(this.value != 0) { this.form.submit(); }'>
								  <datalist id="table">
									<option value="account">
									<option value="admin_first_menu">
									<option value="admin_second_menu">
									<option value="first_menu">
									<option value="second_menu">
								  </datalist>									
									
									
									
									
																								
								Row : <input class="input-mini" type="number" name ="display" value = %s />""" % (
                    table, display)
                page += """		<input type="submit" value="Chon" />
								</form>

	  <p>
		<button name="load" id="load_dog">Load</button>
		<button name="reset">Reset</button>
		<label><input id="autosave" type="checkbox" name="autosave" checked="checked" autocomplete="off"> Autosave</label>
		<input class="toggle" data-column="0" type="button" value="show/hide col 0">
<input class="toggle" data-column="1" type="button" value="show/hide col 1">
<input class="toggle" data-column="2" type="button" value="show/hide col 2">
	  </p>
	  <p>
		Instruction:Username must be unique, not duplicate. Should input account level column first, account level must be integer and not empty please. Do not forget input account level . Account level 2 is admin user and 1 is normal user.After insert new row, should update password last. Password always update last
	  </p>
		<div>
	  <span id="exampleConsole" class="console">Click "Load" to load data from server </span> | 
							<span class="page2">No page selected</span> 
	  </div>
	  <div id="example1" style="width:100%; height: 500px; overflow: hidden"></div>
	  <div class="demo2"></div>

	  <script>"""
                page += """
			var colu = %s;""" % cols
                page += """
	    
		  var
$$ = function(id) {
  return document.getElementById(id);
},
autosave = $$('autosave'),
		 $container = $("#example1"),
		  $console = $("#exampleConsole"),
		  $parent = $container.parent(),
		  autosaveNotification,
		  hot;

		  hot = new Handsontable($container[0], {
		  columnSorting: true,
		  startRows: 8,
		  startCols: 3,
			currentRowClassName: 'currentRow',
currentColClassName: 'currentCol',
autoWrapRow: true,
		  rowHeaders: true,"""
                page += """			colHeaders: %s,
							columns: %s,""" % (str(colHeaders), str(columns))
                page += """					
//colWidths: [0.1,50,200,50,50,50,50],		
manualColumnResize: true,		
autoColumnSize : true,
//stretchH: 'all',	
hiddenColumns: true,			
		  minSpareCols: 0,
		  minSpareRows: 1,
		  contextMenu: true,
			beforeRemoveRow: function(index, amount) {
			var dellist=[];
			for(var i=0; i<amount; i++){
			dellist.push(hot.getData()[index +i][0]);
			}
			//alert(dellist);
				  $.ajax({
					url: """ + saveurl + """,
					data: {delete:dellist,table:"%s"}, // returns all cells' data
					dataType: 'json',
					type: 'POST',
					success: function(res) {//alert(res);
					if (res.result === 'ok') {
						$console.text('Data saved');
						//document.getElementById("load_dog").click();
					  }
					  else {
						$console.text('Save error');
					  }
					},
					error: function () {
					  $console.text('Save error');
					}
				  });        
		},              
		  afterChange: function (change, source) {
			var data;

			if (source === 'loadData' || !$parent.find('input[name=autosave]').is(':checked')) {
			  return;
			}
		   
			data = change[0];""" % table
                page += """				var update = [],insert=[],rows=[],unique=[];
								for (var i=0;i<change.length;i++){
									if (hot.getData()[change[i][0]][0] == null){
										rows.push(change[i][0]);
									}
									else{
										update.push({"id":hot.getData()[change[i][0]][0],"column":colu[change[i][1]],"value":change[i][3]});
									}
								}
								if (rows.length >0) {	
									for(var i in rows){
										if(unique.indexOf(rows[i]) === -1){
											unique.push(rows[i]);
										}
									}                
								for (var i in unique){
									var son = {};
									for (var k in colu){
										son[colu[k]] = hot.getData()[unique[i]][k]
									}
									
									insert.push(son);
								}
							}
			// transform sorted row to original row
			data[0] = hot.sortIndex[data[0]] ? hot.sortIndex[data[0]][0] : data[0];

			clearTimeout(autosaveNotification);
			$.ajax({
			  url: """ + saveurl + """,
			  dataType: 'json',
			  type: 'POST',
			  //data: {"changes": change}, // contains changed cells' data
			  data: {update:update,insert:insert,lenupdate:update.length,leninsert:insert.length,table:"%s"},
			  success: function (/*res*/) {
//alert(res);
				//$console.text('Autosaved (' + change.length + ' cell' + (change.length > 1 ? 's' : '') + ')');
document.getElementById("load_dog").click();
				autosaveNotification = setTimeout(function () {
				  $console.text('Changes will be autosaved');
				}, 1000);
				
			  }
			});
			   
		  }
		});
		
		
		$parent.find('button[name=load]').click(function () {
		  $.ajax({
			url: """ % table + loadurl + ""","""
                page += """	data: {"display":%s,table:"%s"},""" % (display,
                                                                   table)
                page += """	dataType: 'json',
							type: 'POST',					
				success: function (res) {
					var data = [], row;
					for (var i = 0, ilen = res.product.length; i < ilen; i++) {
						row = [];
						for(var m in colu){
						row[m] = res.product[i][colu[m]];
						}
				data[res.product[i].index - 1] = row;
			  }
			  $console.text('Data loaded');
			  hot.loadData(data);
			  $(".page2").html("<strong>Page 1/ "  + Math.round(res.sum_page)+"</strong>");
										$('.demo2').bootpag({
											total: res.sum_page,
											page: 1,
											maxVisible: 10,
											//href:'../demo/account_manager.py?page={{number}}',
											leaps: false,
												firstLastUse: true,
											first: '←',
											last: '→',
											wrapClass: 'pagination',
											activeClass: 'active',
											disabledClass: 'disabled',
											nextClass: 'next',
											prevClass: 'prev',
											lastClass: 'last',
											firstClass: 'first'
										}).on('page', function(event, num){
												$(".page2").html("<strong>Page " + num + '/' + Math.round(res.sum_page)+"</strong>" );
							  $.ajax({
									url: """ + loadurl + ""","""

                page += """ 		data: {"page":num,"display":%s,table:"%s"},""" % (
                    display, table)
                page += """			dataType: 'json',
									type: 'POST',
									success: function (res) {
					var data = [], row;

					for (var i = 0, ilen = res.product.length; i < ilen; i++) {
						row = [];
						for(var m in colu){
						row[m] = res.product[i][colu[m]];
						
						}
					
				data[res.product[i].index - 1] = row;
			  }
										$console.text('Data loaded');
										hot.loadData(data);

									}
							});
											});                  
			}
		  });
		}).click(); // execute immediately

		$parent.find('button[name=reset]').click(function () {
		  $.ajax({
			url: 'php/reset.php',
			success: function () {
			  $parent.find('button[name=load]').click();
			},
			error: function () {
			  $console.text('Data reset failed');
			}
		  });
		});

		$parent.find('input[name=autosave]').click(function () {
		  if ($(this).is(':checked')) {
			$console.text('Changes will be autosaved');
		  }
		  else {
			$console.text('Changes will not be autosaved');
		  }
		});
		hot.selectCell(3,3);

//hot.updateSettings({columns: [{data:1},{data:2,type:"password"},{data:3},{data:4},{data:5},{data:6}] });
	  </script>


</body>
</html>
"""

            else:
                page = pyad.login.login_again

        con.commit()
        cur.close()
        con.close()
        #request.headers['Cookie']
    response = Response(body=page,
                        content_type="text/html",
                        charset="utf8",
                        status="200 OK")

    return response(environment, start_response)
Exemplo n.º 23
0
    def __call__(self, environ, start_response):
        req = Request(environ)
        req.flash = Flash()
        req.flash.info('info message display with Flash.render()')
        req.flash.warn('warning message')
        req.flash.error('error message')
        req.flash.critical('critical message is sticky')
        req.inline_flash = Flash()
        req.inline_flash.info(
            'info message display with Flash.render_inline()')
        req.inline_flash.warn('warning message')
        req.inline_flash.error('error message')
        req.inline_flash.critical('critical message is sticky')
        if req.path.endswith('/fa.jquery/ajax_values'):
            resp = Response()
            resp.content_type = 'application/json'
            resp.body = simplejson.dumps([{
                'value': 'Ajax'
            }, {
                'value': 'Borax'
            }, {
                'value': 'Corax'
            }, {
                'value': 'Dorax'
            }, {
                'value': 'Manix'
            }])
        elif req.path.endswith('/fa.jquery/demo.html'):
            req.remove_conditional_headers()
            script_name = req.environ.get('HTTP_X_FORWARDED_PATH', '')
            Form.ajax.set(
                renderer=AutoCompleteFieldRenderer(script_name +
                                                   '/fa.jquery/ajax_values'))
            obj = Form.gen_model()
            obj.context['slider'] = '10'
            obj.context['sortable'] = '1;2;3'
            obj.context['radioset'] = 'd'
            obj.context['checkboxset'] = ['b', 'a']
            obj.context['selectable'] = 'f'
            obj.context['selectables'] = ['b', 'c']
            fs = Form.bind(obj, data=req.POST or None)
            fs.engine = engine

            fs1.engine = engine
            fs2.engine = engine
            fs3.engine = engine
            fs4.engine = engine

            tabs = Tabs('my_tabs', ('tab1', 'My first tab', fs1),
                        ('tab2', 'The second', fs2),
                        footer='<input type="submit" name="%(id)s" />')
            tabs.tab1.rebind(fs1.gen_model(), data=req.POST or None)
            tabs.tab2.rebind(fs2.gen_model(), data=req.POST or None)
            accordion = Accordion(
                'my_accordion', ('tab1', 'My first section', fs3),
                ('tab2', 'The second', fs4),
                footer='<input type="submit" name="%(id)s" />')
            accordion.tab1.rebind(fs3.gen_model(), data=req.POST or None)
            accordion.tab2.rebind(fs4.gen_model(), data=req.POST or None)
            if req.POST:
                if fs.validate():
                    fs.sync()
                if tabs.validate():
                    tabs.sync()
                if accordion.validate():
                    accordion.sync()

            template = templates.get_template('index.mako')
            head = templates.get_template('head.mako').render()
            body = template.render(req=req,
                                   fs=fs,
                                   tabs=tabs,
                                   accordion=accordion,
                                   headers=self.headers,
                                   head=head,
                                   mim=req.GET.get('mim', False))

            if self.headers:
                resp = Response()
                resp.body = body
            else:
                req.method = 'get'
                resp = req.get_response(self.app)
                resp.body = resp.body.replace('</head>', head + '</head>')
                resp.body = resp.body.replace('<div id="demo"></div>', body)
        else:
            return self.app(environ, start_response)
        return resp(environ, start_response)
Exemplo n.º 24
0
    def __call__(self, environ, start_response):
        """
        @param environ: WSGI environment
        @type environ: dict
        @param start_response: WSGI start response function
        @type start_response: 
        @return: WSGI response
        @rtype: iterable
        """
        log.debug("Oauth2ClientMiddleware.__call__ ...")

        req = Request(environ)
        log.debug("Request url: %s", req.url)
        log.debug("Request host_url: %s", req.host_url)
        log.debug("Request application_url: %s", req.application_url)
        is_redirect_back = False

        original_environ = {
            'PATH_INFO': environ['PATH_INFO'],
            'QUERY_STRING': environ['QUERY_STRING'],
            'SCRIPT_NAME': environ['SCRIPT_NAME'],
            'url': req.url
        }

        # Get session.
        session = environ.get(self.session_env_key)
        if session is None:
            raise Oauth2ClientMiddlewareSessionError(
                'Oauth2ClientMiddleware.__call__: No beaker session key '
                '"%s" found in environ' % self.session_env_key)

        # Determine trigger for starting authentication process.
        authenticate_before_delegating = False
        authenticate_on_unauthorized = False
        is_authentication_url = (
            environ['PATH_INFO'].strip('/') == self.authentication_url)
        if (self.authentication_trigger ==
                self.__class__.AUTHENTICATION_TRIGGER_ALWAYS):
            authenticate_before_delegating = True

        elif (self.authentication_trigger ==
              self.__class__.AUTHENTICATION_TRIGGER_URL):

            if is_authentication_url:
                authenticate_before_delegating = True

        elif (self.authentication_trigger ==
              self.__class__.AUTHENTICATION_TRIGGER_UNAUTHORIZED):
            authenticate_on_unauthorized = True

        # Check whether redirecting back after requesting authorization.
        redirect_url = None
        if self.client_config.is_redirect_uri(req.application_url, req.url):
            try:
                token = self._get_token_after_redirect(session, req)

            except Oauth2ClientAccessTokenRetrievalError as \
                                                access_token_retrieval_error:
                log.error(
                    "%r response from OAuth 2.0 authorization "
                    "server: %r", access_token_retrieval_error.error,
                    access_token_retrieval_error.error_description)

                session[
                    self.__class__.
                    SESSION_ACCESS_TOKEN_REQ_FAILURE_KEY] = access_token_retrieval_error
                session.save()

                app_iter = self._app(environ, start_response)
                return app_iter

            # Only set redirect if token was successfully retrieved
            is_redirect_back = True
            log.debug("Redirected back after requesting authorization.")

            original_environ = session[self.__class__.SESSION_CALL_CONTEXT_KEY]
        else:
            # Start the OAuth2 transaction to get a token.
            log.debug("Starting OAuth2 protocol")
            token, redirect_url = self._get_token(session, req.application_url)
            if authenticate_before_delegating and redirect_url:
                session[
                    self.__class__.SESSION_CALL_CONTEXT_KEY] = original_environ
                session.save()
                log.debug("Redirecting to %s", redirect_url)
                start_response(self._get_http_status_string(httplib.FOUND),
                               [('Location', redirect_url)])
                return []

        local_start_response = start_response
        if token:
            log.debug("Setting token in environ[%s]=%s", self.token_env_key,
                      token)
            environ[self.token_env_key] = token

        elif authenticate_on_unauthorized and redirect_url:

            def local_start_response(status, response_headers, exc_info=None):
                status_code = status.split(' ')[0]
                log.debug("Response HTTP status %s", status_code)
                if status_code == str(httplib.UNAUTHORIZED):
                    session[self.__class__.
                            SESSION_CALL_CONTEXT_KEY] = original_environ
                    session.save()
                    log.debug("Redirecting to %s", redirect_url)
                    start_response(self._get_http_status_string(httplib.FOUND),
                                   [('Location', redirect_url)])
                    return []
                else:
                    return start_response(status, response_headers, exc_info)

        if is_authentication_url:
            c = {'baseURL': req.application_url}
            response = self.renderer.render(
                self.authentication_complete_tmpl_filepath,
                self._renderingConfiguration.merged_parameters(c))

            start_response(self._get_http_status_string(httplib.OK),
                           [('Content-type', 'text/html'),
                            ('Content-length', str(len(response)))])

            return [response]

        # Ensure that the URL is that prior to authentication redirection.
        elif is_redirect_back:
            original_url = original_environ['url']
            log.debug("Redirecting to %s", original_url)
            start_response(self._get_http_status_string(httplib.FOUND),
                           [('Location', original_url)])
            return []
        else:
            app_iter = self._app(environ, local_start_response)
            return app_iter
Exemplo n.º 25
0
 def wsgi_app(self, environ, start_response):
     filename = environ["PATH_INFO"]
     if filename == "/status":
         response_headers = [("Content-type", "text/html")]
         start_response("200 OK", response_headers)
         return [b"200 OK"]
     # Sometimes, even after the user has clicked 'exit' in the page,
     # a browser sends a request for e.g. an audio file.
     if self.is_shutting_down and filename != "/release_database":
         response_headers = [("Content-type", "text/html")]
         start_response("503 Service Unavailable", response_headers)
         return [b"Server stopped"]
     # Load database if needed.
     if not self.is_mnemosyne_loaded and filename != "/release_database":
         self.load_mnemosyne()
     self.release_database_after_timeout.ping()
     # All our request return to the root page, so if the path is '/',
     # return the html of the review widget.
     if filename == "/":
         # Process clicked buttons in the form.
         form = cgi.FieldStorage(fp=environ["wsgi.input"], environ=environ)
         if "show_answer" in form and not self.is_just_started:
             self.mnemosyne.review_widget().show_answer()
             page = self.mnemosyne.review_widget().to_html()
         elif "grade" in form and not self.is_just_started:
             grade = int(form["grade"].value)
             self.mnemosyne.review_widget().grade_answer(grade)
             page = self.mnemosyne.review_widget().to_html()
         elif "star" in form:
             self.mnemosyne.controller().star_current_card()
             page = self.mnemosyne.review_widget().to_html()
         elif "exit" in form:
             self.unload_mnemosyne()
             page = "Server stopped"
             self.wsgi_server.stop()
             self.stop_server_after_timeout = \
                 StopServerAfterTimeout(self.wsgi_server)
             self.stop_server_after_timeout.start()
             self.is_shutting_down = True
         else:
             page = self.mnemosyne.review_widget().to_html()
         if self.is_just_started:
             self.is_just_started = False
         # Serve the web page.
         response_headers = [("Content-type", "text/html")]
         start_response("200 OK", response_headers)
         return [page]
     elif filename == "/release_database":
         self.unload_mnemosyne()
         response_headers = [("Content-type", "text/html")]
         start_response("200 OK", response_headers)
         return [b"200 OK"]
     # We need to serve a media file.
     else:
         # Late import to speed up application startup.
         from webob import Request
         from webob.static import FileApp
         full_path = self.mnemosyne.database().media_dir()
         for word in filename.split("/"):
             full_path = os.path.join(full_path, word)
         request = Request(environ)
         if os.path.exists(full_path):
             etag = "%s-%s-%s" % (os.path.getmtime(full_path),
                                  os.path.getsize(full_path),
                                  hash(full_path))
         else:
             etag = "none"
         app = FileApp(full_path, etag=etag)
         return app(request)(environ, start_response)
Exemplo n.º 26
0
 def __call__(self, env, start_response):
     self.req = Request(env)
     start_response('200 OK')
     start_response([])
Exemplo n.º 27
0
def application(environment, start_response):
    from webob import Request, Response
    request = Request(environment)
    params = request.params
    post = request.POST
    res = Response()
    import pyad.login
    importlib.reload(pyad.login)
    # Get the session object from the environ
    session = environment['beaker.session']

    # Check to see if a value is in the session
    #user = '******' in session

    if not 'username' in session:
        page = pyad.login.loginform
        response = Response(body=page,
                            content_type="text/html",
                            charset="utf8",
                            status="200 OK")

    elif not 'password' in session:
        page = pyad.login.loginform
        response = Response(body=page,
                            content_type="text/html",
                            charset="utf8",
                            status="200 OK")
    else:
        user = session['username']
        passwd = session['password']

        import psycopg2, pyad.conn, hashlib, datetime
        importlib.reload(pyad.conn)

        try:
            con = psycopg2.connect(pyad.conn.conn)
        except:
            page = "Can not access databases"

        cur = con.cursor()
        cur.execute(
            "select username,account_password,account_level from account where username=%s and account_password=%s ",
            (
                user,
                passwd,
            ))
        ps = cur.fetchall()
        if len(ps) == 0:
            page = pyad.login.login_again
            response = Response(body=page,
                                content_type="text/html",
                                charset="utf8",
                                status="200 OK")

        else:
            if ps[0][2] == 2:
                if not 'table' in post:
                    page = pyad.login.login_again
                    response = Response(body=page,
                                        content_type="text/html",
                                        charset="utf8",
                                        status="200 OK")
                else:
                    table = post['table']
                cur.execute(
                    "select column_name, data_type from information_schema.columns where table_name = '"
                    + table + "'")
                rows = cur.fetchall()

                #cur.execute("select * from %s limit 1"%table)
                #cols = [desc[0] for desc in cur.description]

                cols = [desc[0] for desc in rows]
                insertcols = [
                    col for col in cols if col not in ['id', 'update_time']
                ]
                types = {}

                for row in rows:
                    types[row[0]] = row[1]

                page = ""

                if 'leninsert' in post:
                    if int(post['leninsert']) > 0:
                        for i in range(int(post['leninsert'])):
                            values = ()
                            for colname in insertcols:
                                if colname == 'account_password':
                                    values += ("NULLIF('" + hashlib.sha512(
                                        post['insert[%s][%s]' %
                                             (i, colname)].encode(
                                                 'utf-8')).hexdigest() +
                                               "','')", )
                                elif types[colname] == 'integer':
                                    values += ("NULLIF('" +
                                               post['insert[%s][%s]' %
                                                    (i, colname)] +
                                               "','')::integer", )
                                elif types[colname] == 'bigint':
                                    values += ("NULLIF('" +
                                               post['insert[%s][%s]' %
                                                    (i, colname)] +
                                               "','')::integer", )
                                else:
                                    values += ("NULLIF('" +
                                               post['insert[%s][%s]' %
                                                    (i, colname)] + "','')", )
                            try:
                                cur.execute("""insert into """ + table +
                                            """ (""" + ",".join(insertcols) +
                                            """) values ( """ +
                                            ",".join(values) + """)""")
                            except:
                                con.rollback()

                if 'lenupdate' in post:
                    if int(post['lenupdate']) > 0:
                        for i in range(int(post['lenupdate'])):
                            if post['update[%s][column]' %
                                    i] == 'account_password':
                                cur.execute(
                                    "update " + table + " set " +
                                    post['update[%s][column]' % i] +
                                    """ = %s, update_time = %s where id = %s """,
                                    (hashlib.sha512(
                                        post['update[%s][value]' %
                                             i].encode('utf-8')).hexdigest(),
                                     datetime.datetime.today(),
                                     post['update[%s][id]' % i]))
                            else:
                                cur.execute(
                                    "update " + table + " set " +
                                    post['update[%s][column]' % i] +
                                    """ = %s, update_time = %s  where id = %s """,
                                    (post['update[%s][value]' % i],
                                     datetime.datetime.today(),
                                     post['update[%s][id]' % i]))
                if 'delete[]' in post:
                    for row in list(post.getall('delete[]')):
                        if row != '':
                            cur.execute(
                                "delete from " + table + " where id = %s"
                                "", (int(row), ))

                page = """{"result":"ok"}"""
                response = Response(body=page,
                                    content_type="application/json",
                                    charset="utf8",
                                    status="200 OK")
            else:
                page = pyad.login.login_again
                response = Response(body=page,
                                    content_type="text/html",
                                    charset="utf8",
                                    status="200 OK")
        con.commit()
        cur.close()
        con.close()

    return response(environment, start_response)
Exemplo n.º 28
0
def application(environment, start_response):
	from webob import Request, Response
	request = Request(environment)
	params = request.params
	post = request.POST
	res = Response()

	import pyad.conn,pyad.login
	importlib.reload(pyad.conn)
	importlib.reload(pyad.login)

	# Get the session object from the environ
	session = environment['beaker.session']

	# Set some other session variable
	#session['user_id'] = 10
	#user_id = 'user_id' in session

	if not 'username' in session:
		page = pyad.login.loginform
	elif not 'password' in session:
		page = pyad.login.loginform
	else:
		user = session['username']
		passwd = session['password']

		import psycopg2,pyad.module
		try:
			con = psycopg2.connect(pyad.conn.conn)
		except:
			page ="Can not access databases"

		cur = con.cursor()
		cur.execute("select username,account_password,account_level from account where username=%s and account_password=%s ",(user,passwd,))
		ps = cur.fetchall()
		if len(ps) == 0:
			page = pyad.login.login_again
		else:
			if int(ps[0][2]) == 2:
				importlib.reload(pyad.module)
				from pyad.module import head,headlink,menuadmin,menuuser,load,save,menuhead,menufoot

				from datetime import datetime,date
				year_today = date.today().year
				month_today = date.today().month
				day_today = date.today().day
				if not 'display' in post:
					display = 200
				else:
					display = post['display']



				if not 'table' in post or post['table']=='':
					table = ''
				else:
					table = post['table']



				if not 'hidecols' in post:
					hidecols = []
				else:
					hidecols = post.getall('hidecols')

				if not 'hidefils' in post:
					hidefils = []
				else:
					hidefils = post.getall('hidefils')

				if not 'orderby' in post:
					orderby =['id']
				else:
					orderby = post.getall('orderby')

				if not 'by' in post:
					by = 'asc'
				else:
					by = post['by']

				if table =="":
					cur.execute("select")
				else:
					cur.execute("select * from %s limit 1"%table)

				colHeaders = [desc[0].title().replace("_"," ") for desc in cur.description if desc[0] not in hidecols]
				cols = [desc[0] for desc in cur.description if desc[0] not in hidecols]
				colslist = [desc[0] for desc in cur.description]
				filcols = [fils for fils in cols if fils not in hidefils]

				if 'movecols' in post:
					if len(post.getall('movecols')) != 0:
						movecols = ",movecols:%s"%str(post.getall('movecols'))
						cols = [co for co in post.getall('movecols') if co not in hidecols]
						cur.execute("select " + ",".join(cols) + " from %s limit 1"%table)
						colHeaders = [desc[0].title().replace("_"," ") for desc in cur.description if desc[0] not in hidecols]
						colslist = [desc[0] for desc in cur.description]
						filcols = [fils for fils in cols if fils not in hidefils]

				else:
					movecols  =""



				if table =="":
					cur.execute("select")
				else:
					cur.execute("select " + ",".join(cols) + " from %s limit 1"%table)
				daty = cur.fetchone()
				data_types = [type(val).__name__ for index,val in enumerate(daty)]
				types ={}
				for i in range(len(cols)):
					types[cols[i]] = data_types[i]
				data =[]
				grofil =""
				for fil in filcols:

					if types[fil] == 'int':
						grofil += fil.title().replace("_"," ") + """ > <input class="input-mini" name='mor""" + fil + """' value=''/> and """
						grofil += fil.title().replace("_"," ") + """ < <input class="input-mini" name='les""" + fil + """' value=''/> || """
					elif types[fil] =='datetime':
						grofil += fil.title().replace("_"," ") + """ > <input class="input-mini" name='mor""" + fil + """' value=''/> and """
						grofil += fil.title().replace("_"," ") + """ < <input class="input-mini" name='les""" + fil + """' value=''/> || """
					else:
						grofil += fil.title().replace("_"," ") + """ like <input class="input-mini" name='fil""" + fil + """' value=''/>|| """
					grofil +=fil.title().replace("_"," ") + """ <select name="%snull">
  <option value=""></option>
    <option value="null">Empty</option>
  <option value="not_null">not empty</option>
</select> """%fil

					if 'mor%s'%fil in post :
						data.append(""" mor%s:'%s' """ %(fil,post["mor%s"%fil]))
					if 'les%s'%fil in post:
						data.append(""" les%s:'%s' """ %(fil,post["les%s"%fil]))
					if 'fil%s'%fil in post:
						data.append(""" fil%s:'%s' """ %(fil,post["fil%s"%fil]))
					if '%snull'%fil in post:
						data.append(""" %snull:'%s' """ %(fil,post["%snull"%fil]))

				if len(data)>0:
					send_data = "," + ",".join(data)
				else:
					send_data=""

				hidefilter =""
				hidefilter +="""
				<div class="btn-group">
				  <button data-toggle="dropdown" class="btn dropdown-toggle"  data-placeholder="Hide filter">
					Hide filter <span class="caret"></span>
				  </button>
					<ul id="sortable3" class="connectedSortable dropdown-menu">
					"""
				for colsname in colslist:
					if colsname in hidefils:
						hidefilter +="""<li class="ui-state-default"><input type="checkbox" id="fil%s" name="hidefils" value="%s"><label for="fil%s" name="hidefils" value="%s" checked>%s</label></li>"""%(colsname,colsname,colsname,colsname,colsname.title().replace("_"," "))
					else:
						hidefilter +="""<li class="ui-state-default"><input type="checkbox" id="fil%s" name="hidefils" value="%s"><label for="fil%s" name="hidefils" value="%s" >%s</label></li>"""%(colsname,colsname,colsname,colsname,colsname.title().replace("_"," "))
				hidefilter +="""
					  <!-- Other items -->
					</ul>
				</div>"""
				columns =[]
				for colname in cols:
					if colname == 'id':
						columns.append({'readOnly':'true'})
					elif colname == 'account_password':
						columns.append({"type":"password"})
					elif colname == 'update_time':
						columns.append({'readOnly':'true'})
					elif colname == 'account_level':
						columns.append({'type':'numeric','allowEmpty': 'false'})
					elif colname =='username':
						columns.append({'allowEmpty': 'false'})
					elif colname =='fid':
						columns.append({'type':'numeric','allowEmpty': 'false'})

					else:
						columns.append({})



				saveurl ="""'%s/save_account_backup'"""%save
				loadurl = """'%s/load_account_manager_backup'"""%load
				page=""
				page +=head
				page +="<title>Account manager</title>"
				page +=headlink
				page +="""
			
				
				
				</head>
				<body>"""
				page +=menuhead
				if int(ps[0][2]) == 2:
					page += menuadmin

				else:
					page += menuuser
				page += menufoot
				page += """<br />
							<br />"""
				page += """<ul class="nav nav-tabs">
								<li class="active"><a href="%s/account_manager">%s</a></li>
							</ul>"""%(pyad.module.control,table)
				page +="""<h2>Table  %s</h2>"""%(table)

				page +=	"""Order by: %s. Sort by: %s. Hide columns: %s	| Hide filter: %s + %s  <br />
								<form method="post" action="">
<div class='navbar-inner'>								
								<div class="btn-group">
								  <input list="table" name="table" value="%s" onchange='if(this.value != 0) { this.form.submit(); }'>
								  <datalist id="table">
									<option value="account">
									<option value="admin_first_menu">
									<option value="admin_second_menu">
									<option value="first_menu">
									<option value="second_menu">
								  </datalist>
								 </div> 	

<select class="connectedSortable" id="example-dropDown" multiple="multiple">
<ul id="sortable5" class="connectedSortable ">
 <li class="ui-state-default" ><option class="ui-state-default"  value="1" selected="selected">Option 1</option></li>
    <li class="ui-state-default" ><option class="ui-state-default" value="2">Option 2</option></li>
    <li class="ui-state-default" ><option class="ui-state-default"  value="3">Option 3</option></li>
    <li class="ui-state-default" ><option class="ui-state-default"  data-role="divider"></option></li>
    <li class="ui-state-default" ><option class="ui-state-default"  value="4">Option 4</option></li>
</ul>    
</select>								 
<div class="btn-group">
  <button data-toggle="dropdown" class="btn dropdown-toggle"  data-placeholder="Hide column">
	Move columns <span class="caret"></span>
  </button>
    <ul id="sortable6" class="connectedSortable dropdown-menu">"""%(",".join(orderby), by ,",".join(hidecols),",".join(hidefils),movecols,table)
				for colsname in colslist:
					page +="""<li class="ui-state-default"><input type="checkbox" id="move%s" name="movecols" value="%s"><label for="move%s" name="movecols" value="%s" >%s</label></li>"""%(colsname,colsname,colsname,colsname,colsname.title().replace("_"," "))
				page +="""
      <!-- Other items -->
    </ul>
</div>									 								
<div class="btn-group">
  <button data-toggle="dropdown" class="btn dropdown-toggle"  data-placeholder="Hide column">
	Hide columns <span class="caret"></span>
  </button>
    <ul id="sortable1" class="connectedSortable dropdown-menu">"""
				for colsname in colslist:
					page +="""<li class="ui-state-default"><input type="checkbox" id="%s" name="hidecols" value="%s"><label for="%s" name="hidecols" value="%s" >%s</label></li>"""%(colsname,colsname,colsname,colsname,colsname.title().replace("_"," "))
				page +="""
      <!-- Other items -->
    </ul>
</div>	
<div class="btn-group">
  <button data-toggle="dropdown" class="btn dropdown-toggle"  data-placeholder="Hide column">
	Order by <span class="caret"></span>
  </button>
    <ul id="sortable2" class="connectedSortable dropdown-menu">"""
				for colsname in colslist:
					page +="""<li class="ui-state-default"><input type="checkbox" id="by%s" name="orderby" value="%s"><label for="by%s" name="orderby" value="%s" >%s</label></li>"""%(colsname,colsname,colsname,colsname,colsname.title().replace("_"," "))
				page +="""
      <!-- Other items -->
    </ul>
</div>	
<div class="btn-group">
  <button data-toggle="dropdown" class="btn dropdown-toggle"  data-placeholder="Sort by">
	Sort by <span class="caret"></span>
  </button>
    <ul class="dropdown-menu">
    <li class="ui-state-default"><input type="radio" id="asc" name="by" value="asc"><label for="asc" name="by" value="asc" >asc</label></li>
    <li class="ui-state-default"><input type="radio" id="desc" name="by" value="desc"><label for="desc" name="by" value="desc" >desc</label></li>
      <!-- Other items -->
    </ul>
</div>"""
				page += "<div id='filadv' style='display:none'>"
				page += hidefilter
				page += grofil
				page += "</div>"
				page += """Show filter<input class="input-mini" type="checkbox" onclick="myFunction()"/>"""
				page +="""
				Row : <input class="input-mini" type="number" name ="display" value = %s />"""%(display)
				page += """		<input type="submit" id ="chon" value="Chon" />
					
				</div>
								</form>

	  <p>
		<button name="load" id="load_dog">Load</button>
		<button name="reset">Reset</button>
		<label><input id="autosave" type="checkbox" name="autosave" checked="checked" autocomplete="off"> Autosave</label>
	  </p>
	  <p>
		Instruction:Username must be unique, not duplicate. Should input account level column first, account level must be integer and not empty please. Do not forget input account level . Account level 2 is admin user and 1 is normal user.After insert new row, should update password last. Password always update last
	  </p>
		<div>
	  <span id="exampleConsole" class="console">Click "Load" to load data from server </span> | 
							<span class="page2">No page selected</span> 
	  </div>
	  <div id="example1" style="width:100%; height: 500px; overflow: hidden"></div>
	  <div class="demo2"></div>

	  <script>"""
				for hids in hidefils:
					page +="""$("#fil%s").click();"""%hids
				#for c in cols:
					#page +="""$("#move%s").click();"""%c

				page +="""
				
    $(document).ready(function() {
        $('#example-dropDown').multiselect({
            enableFiltering: true,
            includeSelectAllOption: true,
            maxHeight: 400,
            dropDown: true
        });
    });
			
function myFunction() {
    var x = document.getElementById('filadv');
    if (x.style.display === 'none') {
        x.style.display = 'inline';
    } else {
        x.style.display = 'none';
    }
}			
	  
  $( function() {
    $( "#sortable1, #sortable2,#sortable3,#sortable5 ,#sortable6").sortable({
      connectWith: ".connectedSortable"
    }).disableSelection();
$( "ul, li" ).disableSelection();

    
  } );
  
 

	  """
				page +="""
			var colu = %s;"""%cols
				page +="""
  emailValidator = function (value, callback) {
    setTimeout(function(){
      if (/.+@.+/.test(value)) {
        callback(true);
      }
      else {
        callback(false);
      }
    }, 1000);
  };				
emptyValidator = function(value, callback) {
    setTimeout(function(){
    if (isEmpty(value)) { // isEmpty is a function that determines emptiness, you should define it
        callback(true);
    } else {
        callback(fasle);
    }
    }, 1000);    
}	    
		  var
$$ = function(id) {
  return document.getElementById(id);
},
autosave = $$('autosave'),
		 $container = $("#example1"),
		  $console = $("#exampleConsole"),
		  $parent = $container.parent(),
		  autosaveNotification,
		  hot;

		  hot = new Handsontable($container[0], {
		  columnSorting: true,
		  startRows: 8,
		  startCols: 3,
			currentRowClassName: 'currentRow',
currentColClassName: 'currentCol',
autoWrapRow: true,
		  rowHeaders: true,"""
				page +="""			colHeaders: %s,
							columns: %s,"""%(str(colHeaders),str(columns))
				page +="""					
//colWidths: [0.1,50,200,50,50,50,50],		
manualColumnResize: true,		
autoColumnSize : true,
//stretchH: 'all',	
hiddenColumns: true,			
		  minSpareCols: 0,
		  minSpareRows: 1,
		  contextMenu: true,
			beforeRemoveRow: function(index, amount) {
			var dellist=[];
			for(var i=0; i<amount; i++){
			dellist.push(hot.getData()[index +i][0]);
			}
			//alert(dellist);
				  $.ajax({
					url: """ + saveurl +""",
					data: {delete:dellist,table:"%s"}, // returns all cells' data
					dataType: 'json',
					type: 'POST',
					success: function(res) {//alert(res);
					if (res.result === 'ok') {
						$console.text('Data saved');
						document.getElementById("load_dog").click();
					  }
					  else {
						$console.text('Save error');
					  }
					},
					error: function () {
					  $console.text('Save error');
					}
				  });        
		},              
		  afterChange: function (change, source) {
			var data;

			if (source === 'loadData' || !$parent.find('input[name=autosave]').is(':checked')) {
			  return;
			}
		   
			data = change[0];"""%table
				page +="""				var update = [],insert=[],rows=[],unique=[];
								for (var i=0;i<change.length;i++){
									if (hot.getData()[change[i][0]][0] == null){
										rows.push(change[i][0]);
									}
									else{
										update.push({"id":hot.getData()[change[i][0]][0],"column":colu[change[i][1]],"value":change[i][3]});
									}
								}
								if (rows.length >0) {	
									for(var i in rows){
										if(unique.indexOf(rows[i]) === -1){
											unique.push(rows[i]);
										}
									}                
								for (var i in unique){
									var son = {};
									for (var k in colu){
										son[colu[k]] = hot.getData()[unique[i]][k]
									}
									
									insert.push(son);
								}
							}
			// transform sorted row to original row
			data[0] = hot.sortIndex[data[0]] ? hot.sortIndex[data[0]][0] : data[0];

			clearTimeout(autosaveNotification);
			$.ajax({
			  url: """ + saveurl + """,
			  dataType: 'json',
			  type: 'POST',
			  //data: {"changes": change}, // contains changed cells' data
			  data: {update:update,insert:insert,lenupdate:update.length,leninsert:insert.length,table:"%s",cols:%s},
			  success: function (res) {
			  					if (res.result === 'ok') {
//alert(res);
				//$console.text('Autosaved (' + change.length + ' cell' + (change.length > 1 ? 's' : '') + ')');
document.getElementById("load_dog").click();
				autosaveNotification = setTimeout(function () {
				  $console.text('Changes will be autosaved ');
				}, 1000);
}else{$console.html("<font color='red'>Data save error</font>");}
			  },
			error: function (res) {
							autosaveNotification = setTimeout(function () {
			  $console.html("<font color='red'>Data save error:</font>");
				}, 1000);

			}
			});
			   
		  }
		});
		
		
		$parent.find('button[name=load]').click(function () {
		  $.ajax({
			url: """%(table,str(cols)) + loadurl + ""","""
				page += """	data: {types:%s,"display":%s,table:"%s",cols:%s,orderby:%s,by:"%s",filcols:%s%s%s},"""%(str(types),display,table,str(cols),str(orderby),by,str(filcols),send_data,movecols)
				page += """	dataType: 'json',
							type: 'POST',					
				success: function (res) {
					var data = [], row;
					for (var i = 0, ilen = res.product.length; i < ilen; i++) {
						row = [];
						for(var m in colu){
						row[m] = res.product[i][colu[m]];
						}
				data[res.product[i].index - 1] = row;
			  }
			  $console.text('Data loaded');
			  hot.loadData(data);
			  
			  $(".page2").html("<strong>Page 1/ "  + Math.round(res.sum_page)+"</strong> ::::" + res.test);
										$('.demo2').bootpag({
											total: res.sum_page,
											page: 1,
											maxVisible: 10,
											//href:'../demo/account_manager.py?page={{number}}',
											leaps: false,
												firstLastUse: true,
											first: '←',
											last: '→',
											wrapClass: 'pagination',
											activeClass: 'active',
											disabledClass: 'disabled',
											nextClass: 'next',
											prevClass: 'prev',
											lastClass: 'last',
											firstClass: 'first'
										}).on('page', function(event, num){
												$(".page2").html("<strong>Page " + num + '/' + Math.round(res.sum_page)+"</strong>"/* + res.test */);
							  $.ajax({
									url: """+ loadurl +""","""

				page += """ 		data: {types:%s,"page":num,"display":%s,table:"%s",cols:%s,orderby:%s,by:"%s",filcols:%s%s%s},"""%(str(types),display,table,str(cols),str(orderby),by,str(filcols),send_data,movecols)
				page += """			dataType: 'json',
									type: 'POST',
									success: function (res) {
					var data = [], row;

					for (var i = 0, ilen = res.product.length; i < ilen; i++) {
						row = [];
						for(var m in colu){
						row[m] = res.product[i][colu[m]];
						
						}
					
				data[res.product[i].index - 1] = row;
			  }
										$console.text('Data loaded');
										
										hot.loadData(data);

									}
							});
							
							
											});                  
			}
		  });
		}).click(); // execute immediately

		$parent.find('button[name=reset]').click(function () {
		  $.ajax({
			url: 'php/reset.php',
			success: function () {
			  $parent.find('button[name=load]').click();
			},
			error: function () {
			  $console.text('Data reset failed');
			}
		  });
		});

		$parent.find('input[name=autosave]').click(function () {
		  if ($(this).is(':checked')) {
			$console.text('Changes will be autosaved');
		  }
		  else {
			$console.text('Changes will not be autosaved');
		  }
		});
		hot.selectCell(3,3);

//hot.updateSettings({columns: [{data:1},{data:2,type:"password"},{data:3},{data:4},{data:5},{data:6}] });
	  </script>


</body>
</html>
"""

			else:
				page=pyad.login.login_again

		con.commit()
		cur.close()
		con.close()
			#request.headers['Cookie']
	response = Response(body = page,
	content_type = "text/html",
	charset = "utf8",
	status = "200 OK")

	return response(environment, start_response)
Exemplo n.º 29
0
Arquivo: api.py Projeto: wulfnb/zingo
    def __call__(self, environ, start_response):
        request = Request(environ)
        response = self.handle_request(request)

        return response(environ, start_response)
Exemplo n.º 30
0
 def wsgi_app(self, environ, start_response):
     request = Request(environ)
     response = self.handle_request(request)
     return response(environ, start_response)