globals.Request

Here are the examples of the python api globals.Request taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

3 Examples 7

Example 1

Project: sonospy Source File: compileapp.py
Function: call
    def __call__(self, plugin=None, function='index', args=[], vars={},
                 target=None,ajax=False,ajax_trap=False, url=None):
        import globals
        import html
        target = target or str(random.random())[2:]
        request = self.environment['request']
        if plugin and not url and not ajax:
            other_environment = copy.copy(self.environment)
            other_request = globals.Request()
            other_request.application = request.application
            other_request.controller = plugin
            other_request.function = function
            other_request.extension = request.extension
            other_request.args = List(args)
            other_request.folder = request.folder
            other_request.env = request.env
            if not ajax_trap:
                other_request.vars = request.vars
                other_request.get_vars = request.get_vars
                other_request.post_vars = request.post_vars
            else:
                other_request.vars = vars
            other_environment['request'] = other_request
            other_response = globals.Response()
            other_environment['response'] = other_response
            other_response._view_environment = other_environment
            other_request.env.http_web2py_component_location = request.env.path_info
            other_request.env.http_web2py_component_element = target
            other_response.view = '%s/%s.%s' % (plugin,function,other_request.extension)
            page = run_controller_in(plugin, function,
                                     other_environment)
            if isinstance(page, dict):
                other_response._vars = page
                for key in page:
                    other_response._view_environment[key] = page[key]
                run_view_in(other_response._view_environment)
                page = other_response.body.getvalue()
            script = ''
            if ajax_trap:
                script += "web2py_trap_form('%s','%s');" % \
                    (html.URL(request.application,plugin,function,args=args,vars=vars),target)
            #for (name,value) in other_response.headers:
            #    if name == 'web2py-component-command':
            #        script += value
            return html.TAG[''](html.DIV(html.XML(page),_id=target),html.SCRIPT(script))
        else:
            url = url or html.URL(r=request,c=plugin,f=function,args=args,vars=vars)
            return html.TAG[''](html.SCRIPT('web2py_component("%s","%s")' % (url,target)),
                                html.DIV('loading...',_id=target))

Example 2

Project: sonospy Source File: main.py
def wsgibase(environ, responder):
    """
    this is the gluon wsgi application. the first function called when a page
    is requested (static or dynamic). it can be called by paste.httpserver
    or by apache mod_wsgi.

      - fills request with info
      - the environment variables, replacing '.' with '_'
      - adds web2py path and version info
      - compensates for fcgi missing path_info and query_string
      - validates the path in url

    The url path must be either:

    1. for static pages:

      - /<application>/static/<file>

    2. for dynamic pages:

      - /<application>[/<controller>[/<function>[/<sub>]]][.<extension>]
      - (sub may go several levels deep, currently 3 levels are supported:
         sub1/sub2/sub3)

    The naming conventions are:

      - application, controller, function and extension may only contain
        [a-zA-Z0-9_]
      - file and sub may also contain '-', '=', '.' and '/'
    """

    if rewrite.params.routes_in:
        environ = rewrite.filter_in(environ)

    request = Request()
    response = Response()
    session = Session()
    try:
        try:

            # ##################################################
            # parse the environment variables
            # ##################################################

            for (key, value) in environ.items():
                request.env[key.lower().replace('.', '_')] = value
            request.env.web2py_path = web2py_path
            request.env.web2py_version = web2py_version
            request.env.update(settings)

            # ##################################################
            # validate the path in url
            # ##################################################

            if not request.env.path_info and request.env.request_uri:
                # for fcgi, decode path_info and query_string
                items = request.env.request_uri.split('?')
                request.env.path_info = items[0]
                if len(items) > 1:
                    request.env.query_string = items[1]
                else:
                    request.env.query_string = ''
            path = request.env.path_info.replace('\\', '/')

            # ##################################################
            # serve if a static file
            # ##################################################

            match = regex_static.match(regex_space.sub('_', path))
            if match and match.group('x'):
                static_file = os.path.join(request.env.web2py_path,
                                           'applications', match.group('b'),
                                           'static', match.group('x'))
                if request.env.get('query_string', '')[:10] == 'attachment':
                    response.headers['Content-Disposition'] = 'attachment'
                response.stream(static_file, request=request)

            # ##################################################
            # parse application, controller and function
            # ##################################################

            path = re.sub('%20', ' ', path)
            match = regex_url.match(path)
            if not match or match.group('c') == 'static':
                raise HTTP(400,
                           rewrite.params.error_message,
                           web2py_error='invalid path')

            request.application = \
                regex_space.sub('_', match.group('a') or 'init')
            request.controller = \
                regex_space.sub('_', match.group('c') or 'default')
            request.function = \
                regex_space.sub('_', match.group('f') or 'index')
            group_e = match.group('e')
            raw_extension = group_e and regex_space.sub('_',group_e) or None
            request.extension = raw_extension or 'html'
            request.raw_args = match.group('r')
            request.args = List([])
            if request.application in rewrite.params.routes_apps_raw:
                # application is responsible for parsing args
                request.args = None  
            elif request.raw_args:
                match = regex_args.match(request.raw_args)
                if match:
                    group_s = match.group('s')
                    request.args = \
                        List((group_s and group_s.split('/')) or [])
                else:
                    raise HTTP(400,
                               rewrite.params.error_message,
                               web2py_error='invalid path')
            request.client = get_client(request.env)
            request.folder = os.path.join(request.env.web2py_path,
                    'applications', request.application) + '/'

            # ##################################################
            # access the requested application
            # ##################################################

            if not os.path.exists(request.folder):
                if request.application=='init':
                    request.application = 'welcome'
                    redirect(URL(r=request))
                elif rewrite.params.error_handler:
                    redirect(URL(rewrite.params.error_handler['application'],
                                 rewrite.params.error_handler['controller'],
                                 rewrite.params.error_handler['function'],
                                 args=request.application))
                else:
                    raise HTTP(400,
                               rewrite.params.error_message,
                               web2py_error='invalid application')
            request.url = URL(r=request,args=request.args,
                                   extension=raw_extension)

            # ##################################################
            # build missing folder
            # ##################################################

            if not request.env.web2py_runtime_gae:
                for subfolder in ['models','views','controllers', 'databases',
                                  'modules','cron','errors','sessions',
                                  'languages','static','private','uploads']:
                    path =  os.path.join(request.folder,subfolder)
                    if not os.path.exists(path):
                        os.mkdir(path)

            # ##################################################
            # get the GET and POST data
            # ##################################################

            parse_get_post_vars(request, environ)

            # ##################################################
            # expose wsgi hooks for convenience
            # ##################################################

            request.wsgi.environ = environ_aux(environ,request)
            request.wsgi.start_response = lambda status='200', headers=[], \
                exec_info=None, response=response: \
                start_response_aux(status, headers, exec_info, response)
            request.wsgi.middleware = lambda *a: middleware_aux(request,response,*a)

            # ##################################################
            # load cookies
            # ##################################################

            if request.env.http_cookie:
                try:
                    request.cookies.load(request.env.http_cookie)
                except Cookie.CookieError, e:
                    pass # invalid cookies

            # ##################################################
            # try load session or create new session file
            # ##################################################

            session.connect(request, response)

            # ##################################################
            # set no-cache headers
            # ##################################################

            response.headers['Content-Type'] = contenttype('.'+request.extension)
            response.headers['Cache-Control'] = \
                'no-store, no-cache, must-revalidate, post-check=0, pre-check=0'
            response.headers['Expires'] = \
                time.strftime('%a, %d %b %Y %H:%M:%S GMT', time.gmtime())
            response.headers['Pragma'] = 'no-cache'

            # ##################################################
            # run controller
            # ##################################################

            serve_controller(request, response, session)

        except HTTP, http_response:

            if request.body:
                request.body.close()

            # ##################################################
            # on success, try store session in database
            # ##################################################
            session._try_store_in_db(request, response)

            # ##################################################
            # on success, commit database
            # ##################################################

            if response._custom_commit:
                response._custom_commit()
            else:
                BaseAdapter.close_all_instances(BaseAdapter.commit)

            # ##################################################
            # if session not in db try store session on filesystem
            # this must be done after trying to commit database!
            # ##################################################

            session._try_store_on_disk(request, response)

            # ##################################################
            # store cookies in headers
            # ##################################################

            if session._forget:
                del response.cookies[response.session_id_name]
            elif session._secure:
                response.cookies[response.session_id_name]['secure'] = True
            if len(response.cookies)>0: 
                http_response.headers['Set-Cookie'] = \
                    [str(cookie)[11:] for cookie in response.cookies.values()]
            ticket=None

        except RestrictedError, e:

            if request.body:
                request.body.close()

            # ##################################################
            # on application error, rollback database
            # ##################################################

            ticket = e.log(request) or 'unknown'
            if response._custom_rollback:
                response._custom_rollback()
            else:
                BaseAdapter.close_all_instances(BaseAdapter.rollback)

            http_response = \
                HTTP(500,
                     rewrite.params.error_message_ticket % dict(ticket=ticket),
                     web2py_error='ticket %s' % ticket)

    except:

        if request.body:
            request.body.close()

        # ##################################################
        # on application error, rollback database
        # ##################################################

        try:
            if response._custom_rollback:
                response._custom_rollback()
            else:
                BaseAdapter.close_all_instances(BaseAdapter.rollback)
        except:
            pass
        e = RestrictedError('Framework', '', '', locals())
        ticket = e.log(request) or 'unrecoverable'
        http_response = \
            HTTP(500,
                 rewrite.params.error_message_ticket % dict(ticket=ticket),
                 web2py_error='ticket %s' % ticket)
    session._unlock(response)
    http_response = rewrite.try_redirect_on_error(http_response,request,ticket)
    return http_response.to(responder)

Example 3

Project: sonospy Source File: shell.py
Function: env
def env(
    a,
    import_models=False,
    c=None,
    f=None,
    dir='',
    ):
    """
    Return web2py execution environment for application (a), controller (c),
    function (f).
    If import_models is True the exec all application models into the
    environment.
    """

    request = Request()
    response = Response()
    session = Session()
    request.application = a

    # Populate the dummy environment with sensible defaults.

    if not dir:
        request.folder = os.path.join('applications', a)
    else:
        request.folder = dir
    request.controller = c or 'default'
    request.function = f or 'index'
    response.view = '%s/%s.html' % (request.controller,
                                    request.function)
    request.env.path_info = '/%s/%s/%s' % (a, c, f)
    request.env.http_host = '127.0.0.1:8000'
    request.env.remote_addr = '127.0.0.1'

    # Monkey patch so credentials checks pass.

    def check_credentials(request, other_application='admin'):
        return True

    fileutils.check_credentials = check_credentials

    environment = build_environment(request, response, session)

    if import_models:
        try:
            run_models_in(environment)
        except RestrictedError, e:
            sys.stderr.write(e.traceback+'\n')
            sys.exit(1)
    return environment