当前位置: 首页>>代码示例>>Python>>正文


Python util.request_uri函数代码示例

本文整理汇总了Python中wsgiref.util.request_uri函数的典型用法代码示例。如果您正苦于以下问题:Python request_uri函数的具体用法?Python request_uri怎么用?Python request_uri使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了request_uri函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: _open

    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
        self._cookie_jar.extract_from_werkzeug(response, environ)
        self.status_code = response.status_code
        # Automatically follow redirects
        if 301 <= self.status_code <= 302:
            logger.debug("Redirect to %s", response.headers['Location'])
            after_browser_activity.send(self)
            self._open(response.headers['Location'])
            return
        # redirects report the original referrer
        self._referrer = request_uri(environ)
        self.status = response.status
        self.headers = response.headers
        # TODO: unicodify
        self.response = response.data
        self._sync_document()

        # TODO: what does a http-equiv redirect report for referrer?
        if 'meta[http-equiv=refresh]' in self.document:
            refresh = self.document['meta[http-equiv=refresh]'][0]
            if 'content' in refresh.attrib:
                parts = refresh.get('content').split(';url=', 1)
                if len(parts) == 2:
                    logger.debug("HTTP-EQUIV Redirect to %s", parts[1])
                    after_browser_activity.send(self)
                    self._open(parts[1])
                    return

        open_ended = time()
        request_time = request_ended - request_started
        logger.info("Fetched %s in %0.3fsec + %0.3fsec browser overhead",
                    url, request_time,
                    open_ended - open_started - request_time)
        after_browser_activity.send(self)
开发者ID:jek,项目名称:alfajor,代码行数:57,代码来源:wsgi.py

示例2: target

def target(environ):
    wiki_id = shift_path_info(environ)
    full_incoming_request = request_uri(environ)
    if wiki_id not in TARGET_WIKIS:
        raise BadTargetError(fronturl=request_uri(environ), target=wiki_id)
    original_page = join(TARGET_WIKIS[wiki_id].rstrip('/')+'/', environ['PATH_INFO'].lstrip('/'))
    #relative_to_wrapped = relativize(, full_incoming_request)
    wrapped_wiki_base = full_incoming_request[:-len(environ['PATH_INFO'])]
    return wiki_id, TARGET_WIKIS[wiki_id], TARGET_WIKI_OPENERS.get(wiki_id), original_page, wrapped_wiki_base
开发者ID:pombredanne,项目名称:akara,代码行数:9,代码来源:moinrest.py

示例3: application

def application(environ, start_response):
    # get request path and request params
    request = urlparse(request_uri(environ))
    query_dict = parse_qs(request.query)

    for key, value in query_dict.items():
        if len(value) == 1:
            query_dict[key] = value[0]

    # map request handler to request path
    urlpatterns = (
        ('/data/results(/)?$', run_resultstimeseries_query),
        ('/data/slaves(/)?$', run_slaves_query),
        ('/data/platform(/)?$', run_platform_query),
        ('/data/results/flot/day(/)?$',run_results_day_flot_query)
        )

    # dispatch request to request handler
    for pattern, request_handler in urlpatterns:
        if re.match(pattern, request.path, re.I):
            response_body = request_handler(query_dict)
            break
    else:
        # error handling
        return handler404(start_response)

    status = "200 OK"
    response_headers = [("Content-Type", "application/json"),
                        ("Content-Length", str(len(response_body)))]
    start_response(status, response_headers)
    return response_body
开发者ID:thegyro,项目名称:ouija,代码行数:31,代码来源:server.py

示例4: __call__

	def __call__(self, environ, start_response):
		#print environ
		print start_response
		uri = urlparse(request_uri(environ))
		print uri
		q = parse_qs(uri.query)
		if uri.path == '/query':
			return self.query(start_response, q)
		if uri.path == '/':
			start_response(OK, [('Content-type', HTML)])
			return FileWrapper(open(self.root + '/data/index.html', 'r'))
		uris = uri.path.split('/')[1:]
		print uris
		if uris[0] == 'data' and len(uris) == 2:
			f = self.root + '/data/' + uris[1]
			if not os.path.isfile(f):
				start_response(NOT_FOUND, PLAIN)
				return [uris[1] + " doesn't exist"]
			r, ext = os.path.splitext(f)
			start_response(OK, [('Content-type', MIME[ext[1:]])])
			return FileWrapper(open(f, 'r'))
		if uris[0] == 'track':
			return self.track(start_response, uris[1], uris[2])
		# The returned object is going to be printed
		start_response(OK, [('Content-type', PLAIN)])
		return ["Hello iTunes"]
开发者ID:athoune,项目名称:ShareMyTunes,代码行数:26,代码来源:server.py

示例5: get_file

def get_file(environ, start_response):
    '''
    GETting the collection resource itself returns a simple file listing.
    
    GETting a subsidiary resource returns the file
    '''
    print >> sys.stderr, 'GRIPPO', environ['PATH_INFO']
    if environ['PATH_INFO'] == '/':
        #Get index
        start_response(status_response(httplib.OK), [("Content-Type", "text/plain")])
        return '\n'.join(os.listdir(BASE)) + '\n'
    resource_fname = shift_path_info(environ)
    #Not needed because the shift_path_info will ignore anything after the '/' and they'll probably get a 404
    #'..' will not be expanded by os.path.join
    #if "/" in resource_fname:
    #    start_response(status_response(httplib.BAD_REQUEST), [("Content-Type", "text/plain")])
    #    return 'You must not include forward slashes in your request (%s)'%resource_fname
    resource_path = os.path.join(BASE, resource_fname)
    print >> sys.stderr, 'Getting the file at: ', resource_fname
    try:
        f = open(resource_path, 'rb')
        #FIXME: do it chunk by chunk
        rbody = f.read()
        #FIXME: work out content type mappings (perhaps by file extension)
        start_response(status_response(httplib.OK), [("Content-Type", "text/plain")])
        return rbody
    except IOError:
        rbody = four_oh_four.substitute(fronturl=request_uri(environ), backurl=resource_fname)
        start_response(status_response(httplib.NOT_FOUND), [("Content-Type", "text/html")])
        return rbody
开发者ID:dpla,项目名称:akara,代码行数:30,代码来源:collection.py

示例6: _get_page

 def _get_page(self, environ):
     objectRequested = util.request_uri(environ).split("/")[-1];
     if(objectRequested == ""):
         objectRequested = "androclick.html";
     response, mime = WebResources.getWebResource(objectRequested);
     response_headers = [('Content-type', mime)];
     return response, response_headers;
开发者ID:TinyBoxDev,项目名称:androclick-server,代码行数:7,代码来源:__init__.py

示例7: application

def application(environ, start_response):
    # get request path and request params
    request = urlparse(request_uri(environ))
    query_dict = parse_qs(request.query)

    for key, value in query_dict.items():
        if len(value) == 1:
            query_dict[key] = value[0]


    # get post data
    body = ''  # b'' for consistency on Python 3.0
    try:
        length = int(environ.get('CONTENT_LENGTH', '0'))
    except ValueError:
        length = 0

    if length != 0:
        body = environ['wsgi.input'].read(length)

    # map request handler to request path
    urlpatterns = (
        ('/data/alert(/)?$', run_alert_query),
        ('/data/submit$', run_submit_data),
        ('/data/updatestatus$', run_updatestatus_data),
        ('/data/submitduplicate$', run_submitduplicate_data),
        ('/data/submitbug$', run_submitbug_data),
        ('/data/submittbpl$', run_submittbpl_data),
        ('/data/alertsbyrev$', run_alertsbyrev_query),
        ('/data/mergedalerts$', run_mergedalerts_query),
        ('/data/mergedids$', run_mergedids_query),
        ('/data/getvalues$', run_values_query),
        )

    # dispatch request to request handler
    for pattern, request_handler in urlpatterns:
        if re.match(pattern, request.path, re.I):
            response_body = request_handler(query_dict, body)
            break
    else:
        # When running outside of Apache, we need to handle serving
        # static files as well. This can be removed when we move to Flask.
        # need to strip off leading '/' for relative path
        static_path = request.path[1:]
        if os.path.exists(static_path):
            with open(static_path, 'r') as f:
                response_body = f.read()
            status = "200 OK"
            response_headers = [("Content-Type", "html"),
                                ("Content-Length", str(len(response_body)))]
            start_response(status, response_headers)
            return response_body
        else:
            return handler404(start_response)

    status = "200 OK"
    response_headers = [("Content-Type", "application/json"),
                        ("Content-Length", str(len(response_body)))]
    start_response(status, response_headers)
    return response_body
开发者ID:pbaisla,项目名称:alert_manager,代码行数:60,代码来源:server.py

示例8: serve

    def serve(environ, start_response):

        root = root_url.lstrip('/')

        tail, get = (util.request_uri(environ).split('?') + [''])[:2]
        tail = tail[len(util.application_uri(environ)):]

        result = []

        content_type = 'text/plain'
        status = '200 OK'
        if tail.startswith(root):

            tail = tail[len(root):]

            get = parse_qs(get)
            method = environ['REQUEST_METHOD']

            text, post = '', {}
            if method == 'POST':
                text = environ['wsgi.input'].\
                    read(int(environ.get('CONTENT_LENGTH', 0)))
                post = parse_qs(text)

            response = server.process_request(
                Request(tail, text, get, post, {}))

            content_type = response.content_type
            status = get_http_response_code(response)
            result.append(response.text)

        headers = [('Content-type', content_type)]
        start_response(status, headers)

        return result
开发者ID:gustavo-gomez,项目名称:freezing-tyrion,代码行数:35,代码来源:_wsgi.py

示例9: application

def application(environ, start_response):

    method = environ['REQUEST_METHOD'].lower()
    ctype = 'text/html; charset=utf-8'
    filename = 'index.htm'
    response_body = open(filename).read()
    path =  urlparse(request_uri(environ))
    t = Template(response_body)
    post_body = ''
    if method == 'get':
        if path.path.startswith('/list'):
            docid = path.query.split('=')[1]
            docid = int(docid)
            response_body = get_doc(docid).get_data()
        else:
            response_body = t.render(ms=None,isreturn=0)
    elif method == 'post':
        try:
            lens = int(environ.get('CONTENT_LENGTH', 0))
        except:
            lens = 0
        if lens:
            post_body = environ['wsgi.input'].read(lens)
            post_body = urllib.unquote_plus(post_body)[4:]
            post_body = post_body.decode('utf-8')
            num, docs = get_back(post_body)
        response_body = t.render(ms=docs,isreturn=1, num=num)

    status = '200 OK'
    response_headers = [('Content-Type', ctype), ('Content-Length', str(len(response_body)))]
    if type(response_body) is unicode:
        response_body = response_body.encode('utf-8')
    start_response(status, response_headers)
    return [response_body]
开发者ID:pendulm,项目名称:track,代码行数:34,代码来源:web.py

示例10: serve

    def serve(environ, start_response):

        root = root_url.lstrip("/")

        tail, get = (util.request_uri(environ).split("?") + [""])[:2]
        tail = tail[len(util.application_uri(environ)) :]

        result = []

        content_type = "text/plain"
        status = "200 OK"
        if tail.lstrip("/").startswith(root):

            tail = tail[len(root) :]

            get = parse_qs(get)
            method = environ["REQUEST_METHOD"]

            text, post = "", {}
            if method == "POST":
                text = environ["wsgi.input"].read(int(environ.get("CONTENT_LENGTH", 0)))
                post = parse_qs(text)

            response = server.process_request(Request(tail, text, get, post, {}))

            content_type = response.content_type
            status = get_http_response_code(response)
            result.append(response.text)

        headers = [("Content-type", content_type)]
        start_response(status, headers)

        return result
开发者ID:Kjir,项目名称:pyws,代码行数:33,代码来源:_wsgi.py

示例11: notFound

def notFound(environ, start_response):

    ret = "%s not found" % util.request_uri(environ)

    start_response("404 Not Found", [("Content-type", "text/plain"), ("Content-length", str(len(ret)))])

    return ret
开发者ID:shomah4a,项目名称:wsgilib,代码行数:7,代码来源:responses.py

示例12: application

def application(environ, start_response):
    status = '200 OK'
    responce_headers = [('Content-type', 'text/html; charset=utf-8')]
    path = urlparse(request_uri(environ)).path


    method = environ['REQUEST_METHOD'].lower()
    if method == 'get':
        filename = '../template/index.html'

    elif method == 'post':
        filename = '../template/post.html'
        post_html = open(filename).read()
        t = Template(post_html)

        post_body = ''
        try:
            lens = int(environ.get('CONTENT_LENGTH', 0))
        except:
            lens = 0
        if not lens:
            post_body = environ['wsgi.input'].read(lens)

        template = t.substitute(cooked=post_body)

    if not locals().has_key('template'):
        f = open(filename)
        template = f.read()

    start_response(status, responce_headers)
    return [template]
开发者ID:pendulm,项目名称:track,代码行数:31,代码来源:app.py

示例13: exception

 def exception(self, environ, start_response):
     import traceback
     from pprint import pformat
     exc_type, exc_value, tb = sys.exc_info()
     tblines = traceback.format_exception(exc_type, exc_value, tb)
     tbstr = "\n".join(tblines)
     # render the error
     title = tblines[-1]
     body = html.Body([
         html.Div([html.H1(self.exception_heading),
                   html.P([self.exception_description]),
                   html.H2("Traceback"),
                   html.Pre([tbstr]),
                   html.H2("Variables"),
                   html.Pre(["request_uri: %s\nos.getcwd(): %s" % (request_uri(environ), os.getcwd())]),
                   html.H2("environ"),
                   html.Pre([pformat(environ)]),
                   html.H2("sys.path"),
                   html.Pre([pformat(sys.path)]),
                   html.H2("os.environ"),
                   html.Pre([pformat(dict(os.environ))])
     ])])
     msg = self._transform(title, body, environ)
     return self._return_response(msg, start_response,
                                  status="500 Internal Server Error",
                                  contenttype="text/html")
开发者ID:staffanm,项目名称:ferenda,代码行数:26,代码来源:wsgiapp.py

示例14: _render

def _render(f, template_file, environ, start_response, *args, **kwds):

    # call our original function with original args
    try:
        results = f(environ, start_response)

        template_name, ext = template_file.split(".")
        contenttype = "text/html"
        if len(ext) > 1 and (ext[1] in extensions):
            contenttype = extensions[ext[1]]

        hdf = neo_util.HDF()
        _set(hdf, '', results)
        hdf.setValue('style', stylesheet_uri)

        # shove the results into the template
        clearsilver = neo_cs.CS(hdf)
        clearsilver.parseFile(os.path.join('templates', template_name + '.cs'))

        # XXX where is our error handling?
        start_response("200 OK", [('Content-Type', contenttype)])
        return [clearsilver.render()]
    except DataNotFound:
        start_response("404 Not Found", [('Content-Type', 'text/plain')])
        return ['404 Error, Content not found']
    except HTTP303, e:
        url = str(e.value)
        if not url.startswith(('http', '/')):
            url = request_uri(environ) + url
        start_response("302 Found", [('Location', url)])
        return ['Redirect to url']
开发者ID:cdent,项目名称:simper,代码行数:31,代码来源:simper.py

示例15: webHandler

def webHandler(environ, start_response):
	retStr = ""
	status = '200 OK'
	headers = [('Content-type', 'text/plain')]
	start_response(status, headers)

	urlString = request_uri(environ, include_query=0)
	if urlString != "http://" + str(ip) + ":" + str(port) + "/":  # Parses off end of URL if present

		splitObj = str.split(urlString, "/")

		command = splitObj[3]

		if command == "rebootForgeLand":
			retStr = "Rebooting NOW!"
			os.system("reboot")

		if command == "time":
			t = dateTimeObj()
			retStr = timeStringOutput(t.hour, t.minute)

			# TODO Change to proper time input

		if command == "timeJSON":
			retStr = json.dumps(dateTimeObj().__dict__, sort_keys=True)  # Asks for timeDate object, then converts to JSON string

	return retStr
开发者ID:Jelloeater,项目名称:forgeLandWebCommand,代码行数:27,代码来源:webCommand.py


注:本文中的wsgiref.util.request_uri函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。