How to use the wsgiref.util.request_uri function in wsgiref

To help you get started, we’ve selected a few wsgiref examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github tribe29 / checkmk / cmk / gui / wsgi / middleware.py View on Github external
def _add_apache_env(environ, start_response):
        if not environ.get('REQUEST_URI'):
            environ['REQUEST_URI'] = wsgiref.util.request_uri(environ)

        path_info = environ.get('PATH_INFO')
        if not path_info or path_info == '/':
            environ['PATH_INFO'] = environ['SCRIPT_NAME']

        return app(environ, start_response)
github OpenMDAO / OpenMDAO-Framework / scripts / eggsrv.py View on Github external
def dist_dir_response(self, environ, start_response, abspath):
        """When the server gets a request for a directory, return a page
        listing each distribution file in the directory, along with its md5 digest.
        """
        dpath = environ['PATH_INFO'].strip('/')
        start_response('200 OK', [('Content-Type', 'text/html')])
        out = StringIO()
        out.write('\n\n<h1>%s Distributions</h1>\n<ul>\n'%(dpath,))
        for f in os.listdir(abspath):
            fpath = os.path.join(abspath,f)
            # TODO: add pkg_resources code here to actually find all of the distributions
            #       so that files that aren't distributions won't show up
            if os.path.isfile(fpath):
                checksum = file_md5(fpath)
                lpath = os.path.join(wsgiref.util.request_uri(environ), f)
                out.write('<li><a href="%s#md5=%s">%s</a>\n'%(lpath, checksum, f))
        out.write('</li></ul>\n\n')
        return [out.getvalue()]
github open-telemetry / opentelemetry-python / ext / opentelemetry-ext-wsgi / src / opentelemetry / ext / wsgi / __init__.py View on Github external
result = {
        "component": "http",
        "http.method": environ["REQUEST_METHOD"],
        "http.server_name": environ["SERVER_NAME"],
        "http.scheme": environ["wsgi.url_scheme"],
        "host.port": int(environ["SERVER_PORT"]),
    }

    setifnotnone(result, "http.host", environ.get("HTTP_HOST"))
    target = environ.get("RAW_URI")
    if target is None:  # Note: `"" or None is None`
        target = environ.get("REQUEST_URI")
    if target is not None:
        result["http.target"] = target
    else:
        result["http.url"] = wsgiref_util.request_uri(environ)

    remote_addr = environ.get("REMOTE_ADDR")
    if remote_addr:
        result[
            "peer.ipv6" if ":" in remote_addr else "peer.ipv4"
        ] = remote_addr
    remote_host = environ.get("REMOTE_HOST")
    if remote_host and remote_host != remote_addr:
        result["peer.hostname"] = remote_host

    setifnotnone(result, "peer.port", environ.get("REMOTE_PORT"))
    flavor = environ.get("SERVER_PROTOCOL", "")
    if flavor.upper().startswith(_HTTP_VERSION_PREFIX):
        flavor = flavor[len(_HTTP_VERSION_PREFIX) :]
    if flavor:
        result["http.flavor"] = flavor
github idealistdev / alfajor / alfajor / browsers / wsgi.py View on Github external
def _open(self, url, method='GET', data=None, refer=True, content_type=None):
        before_browser_activity.send(self)
        open_started = time()
        environ = self._create_environ(url, method, data, refer, content_type)
        # keep a copy, the app may mutate the environ
        request_environ = dict(environ)

        logger.info('%s(%s) == %s', method, url, request_uri(environ))
        request_started = time()
        rv = run_wsgi_app(self._wsgi_app, environ)
        response = BaseResponse(*rv)
        # TODO:
        # response.make_sequence()  # werkzeug 0.6+
        # For now, must:
        response.response = list(response.response)
        if hasattr(rv[0], 'close'):
            rv[0].close()
        # end TODO

        # request is complete after the app_iter (rv[0]) has been fully read +
        # closed down.
        request_ended = time()

        self._request_environ = request_environ
github opentripplanner / OTPSetup / otproxy / src / otproxy.py View on Github external
def log():
        #request time, URL, API key, router selected, and
        #subrequest duration
        args = parse_qs(environ['QUERY_STRING'])
        api_key = args.get('apiKey', ['None'])[0]

        uri = wsgiref.util.request_uri(environ)
        REQUEST_LOGGER.info("%s %s %s %s %s", status, uri, api_key, router, duration)

        data = {"status" : status,
                "uri" : uri,
                "api_key" : api_key,
                "router" : router,
                "duration" : duration,
                "time" : datetime.now().isoformat(),
                }
        if 'fromPlace' in args:
            data['fromPlace'] = args['fromPlace'][0]
        if 'toPlace' in args:
            data['toPlace'] = args['toPlace'][0]
        cube.put("request", data)
    Greenlet.spawn(log)
github andrewxhill / MOL / app / mol / api / __init__.py View on Github external
logging.info('Updating SpeciesIndex.hasRangeMap for %s' % species_key_name)
            species_index.hasRangeMap = True
            db.put(species_index)

        enw = db.GeoPt(self._param('maxLat', type=float), self._param('minLon', type=float))
        ese = db.GeoPt(self._param('minLat', type=float), self._param('maxLon', type=float))
        db.put(TileSetIndex(key=db.Key.from_path('TileSetIndex', species_key_name),
                            dateLastModified=datetime.datetime.now(),
                            remoteLocation=db.Link(self._param('remoteLocation')),
                            zoom=self._param('zoom', type=int),
                            proj=self._param('proj'),
                            extentNorthWest=enw,
                            extentSouthEast=ese,
                            status=db.Category(self._param('status', required=False)),
                            type=db.Category(self._param('type', required=False))))
        location = wsgiref.util.request_uri(self.request.environ)
        self.response.headers['Location'] = location
        self.response.headers['Content-Location'] = location
        self.response.set_status(201) # Created
github OpenMDAO / OpenMDAO-Framework / scripts / findlinksrv.py View on Github external
def top_dir_response(self, environ, start_response):
        """When the server gets a '/' request, return a page listing all of
        the distributions in this server.
        """
        start_response('200 OK', [('Content-Type', 'text/html')])
        out = StringIO()
        out.write('\n\n')
        self.lock.acquire()
        file_cache = self.file_cache
        try:
            flist = sorted(find_files(self.topdir, ["*.egg","*.tar.gz"]), key=str.lower)
            for f in flist:
                checksum = file_md5(f)
                basef = os.path.basename(f)
                dirname = wsgiref.util.request_uri(environ)
                lpath = os.path.join(dirname, basef)
                file_cache[basef] = f
                out.write('<li><a href="%s#md5=%s">%s</a>\n'%(lpath, checksum, basef))
        finally:
            self.lock.release()
        out.write('\n\n')
        return [out.getvalue()]
</li>
github datawire / quark / runtime / python-threaded / quark_threaded_runtime.py View on Github external
def __call__(self, environ, start_response):
        path = environ["PATH_INFO"]
        url = util.request_uri(environ)
        try:
            request_body_size = int(environ.get('CONTENT_LENGTH', 0))
        except (ValueError):
            request_body_size = 0
        request_body = environ['wsgi.input'].read(request_body_size)

        request = _HTTPRequest(url)
        request.setMethod(environ["REQUEST_METHOD"])
        request.setBody(request_body)
        request.setHeader("Content-Type", environ["CONTENT_TYPE"])
        request.setHeader("Content-Length", request_body_size)
        for key in environ:
            if key.startswith("HTTP_"):
                request.setHeader(key[5:], environ[key])
        response = _HTTPResponse()
        try:
github ajaxorg / ace / static.py View on Github external
def __call__(self, environ, start_response):
        """Respond to a request when called in the usual WSGI way."""
        if environ['REQUEST_METHOD'] not in ('GET', 'HEAD'):
            headers = [('Allow', 'GET, HEAD')]
            return self.method_not_allowed(environ, start_response, headers)
        path_info = environ.get('PATH_INFO', '')
        full_path = self._full_path(path_info)
        if not self._is_under_root(full_path):
            return self.not_found(environ, start_response)
        if path.isdir(full_path):
            if full_path[-1] &lt;&gt; '/' or full_path == self.root:
                location = util.request_uri(environ, include_query=False) + '/'
                if environ.get('QUERY_STRING'):
                    location += '?' + environ.get('QUERY_STRING')
                headers = [('Location', location)]
                return self.moved_permanently(environ, start_response, headers)
            else:
                full_path = self._full_path(path_info + self.index_file)
        content_type = self._guess_type(full_path)
        try:
            etag, last_modified = self._conditions(full_path, environ)
            headers = [('Date', rfc822.formatdate(time.time())),
                       ('Last-Modified', last_modified),
                       ('ETag', etag)]
            if_modified = environ.get('HTTP_IF_MODIFIED_SINCE')
            if if_modified and (rfc822.parsedate(if_modified)
                                &gt;= rfc822.parsedate(last_modified)):
                return self.not_modified(environ, start_response, headers)
github AppScale / appscale / AppServer / google / appengine / tools / devappserver2 / url_handler.py View on Github external
# AppScale: Here we check to see if our secret hash is in the header which
    # authenticates that the task was created from an AppScale deployment and
    # not an unauthorized party.
    if (constants.FAKE_IS_ADMIN_HEADER in environ and
            self._secret_hash == environ[constants.FAKE_IS_ADMIN_HEADER]):
      admin = True

    if constants.FAKE_LOGGED_IN_HEADER in environ:
      email_addr = 'Fake User'

    # admin has an effect only with login: admin (not login: required).
    if requires_login and not email_addr and not (admin and admin_only):
      if auth_fail_action == appinfo.AUTH_FAIL_ACTION_REDIRECT:
        logging.debug('login required, redirecting user')
        return login.login_redirect(wsgiref.util.application_uri(environ),
                                    wsgiref.util.request_uri(environ),
                                    start_response)
      elif auth_fail_action == appinfo.AUTH_FAIL_ACTION_UNAUTHORIZED:
        logging.debug('login required, user unauthorized')
        start_response('401 Not authorized', [('Content-Type', 'text/html'),
                                              ('Cache-Control', 'no-cache')])
        return ['Login required to view page.']
    elif admin_only and not admin:
      logging.debug('admin required, user unauthorized')
      start_response('401 Not authorized', [('Content-Type', 'text/html'),
                                            ('Cache-Control', 'no-cache')])
      return ['Current logged in user %s is not '
              'authorized to view this page.'
              % email_addr]

    # Authorization check succeeded
    return None