def _add_request_attributes(span, environ): span.set_attribute("component", "http") span.set_attribute("http.method", environ["REQUEST_METHOD"]) host = environ.get("HTTP_HOST") if not host: host = environ["SERVER_NAME"] port = environ["SERVER_PORT"] scheme = environ["wsgi.url_scheme"] if (scheme == "http" and port != "80" or scheme == "https" and port != "443"): host += ":" + port # NOTE: Nonstandard span.set_attribute("http.host", host) url = environ.get("REQUEST_URI") or environ.get("RAW_URI") if url: if url[0] == "/": # We assume that no scheme-relative URLs will be in url here. # After all, if a request is made to http://myserver//foo, we may get # //foo which looks like scheme-relative but isn't. url = environ["wsgi.url_scheme"] + "://" + host + url elif not url.startswith(environ["wsgi.url_scheme"] + ":"): # Something fishy is in RAW_URL. Let's fall back to request_uri() url = wsgiref_util.request_uri(environ) else: url = wsgiref_util.request_uri(environ) span.set_attribute("http.url", url)
def app(environ, respond): print("request_uri=", util.request_uri(environ)) if util.request_uri(environ).endswith("/request?cmd=reboot"): print("### reboot") os.system("sudo reboot") respond('200 OK', [('Content-Type', 'application/json; charset=utf-8')]) return [json.dumps({'message':'reboot requested'}).encode("utf-8")] if util.request_uri(environ).endswith("/request?cmd=shutdown"): print("### shutdown") os.system("sudo shutdown -h now") respond('200 OK', [('Content-Type', 'application/json; charset=utf-8')]) return [json.dumps({'message':'shutdown requested'}).encode("utf-8")] if util.request_uri(environ).endswith("/request?cmd=upgrade"): print("### upgrade") respond('200 OK', [('Content-Type', 'application/json; charset=utf-8')]) os.system("git pull origin master") os.system("cd config && git pull origin master && cd ..") os.system("sudo reboot") return [json.dumps({'message':'upgrade requested'}).encode("utf-8")] name = environ['PATH_INFO'][1:] if name in filenames: fn = filenames[name] else: fn = filenames["index.html"] type = mimetypes.guess_type(fn)[0] if os.path.exists(fn): respond('200 OK', [('Content-Type', type)]) return util.FileWrapper(open(fn, "rb")) else: respond('404 Not Found', [('Content-Type', 'text/plain')]) return [b'not found']
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)
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
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) if len(environ['PATH_INFO']) > 0: wrapped_wiki_base = full_incoming_request[:-len(environ['PATH_INFO'])] else: wrapped_wiki_base = full_incoming_request return wiki_id, TARGET_WIKIS[wiki_id], TARGET_WIKI_OPENERS.get( wiki_id), original_page, wrapped_wiki_base
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
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"]
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
def __call__(self, environ, start_response): request_line = environ['REQUEST_METHOD'] + ' ' + request_uri(environ) print(request_line, file=sys.stderr) if 'CONTENT_TYPE' in environ: print('Content-Type:', environ['CONTENT_TYPE'], file=sys.stderr) for k, v in environ.items(): if k.startswith('HTTP_'): print(k[5:].lower().replace('_', '-') + ': ' + v, file=sys.stderr) if 'wsgi.input' in environ: body = environ['wsgi.input'] old_body_read = body.read def read(*args): result = old_body_read(*args) print(result.decode('iso-8859-1', 'replace'), file=sys.stderr) return result body.read = read def inner_start_response(status, headers, exc_info=None): print(file=sys.stderr) print(status, file=sys.stderr) print(Headers(headers), file=sys.stderr) print(file=sys.stderr) if exc_info is None: return start_response(status, headers) else: return start_response(status, headers, exc_info) for data in self._app(environ, inner_start_response): sys.stderr.write(data.decode('iso-8859-1', 'replace')) yield data print(file=sys.stderr)
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;
def application(self, environ, start_response): path = request_uri(environ) try: path_info = urlparse(path) if not (path_info.scheme and path_info.netloc and path_info.path): return self.manage_response_wsgi("", self.INTERNAL_SERVER_ERROR, start_response) except Exception: return self.manage_response_wsgi("", self.INTERNAL_SERVER_ERROR, start_response) headers = dict((k.replace("HTTP_", ""), v) for (k, v) in environ.items() if re.match('^HTTP_.*', k)) try: request_body_size = int(environ.get('CONTENT_LENGTH', 0)) except ValueError: request_body_size = 0 raw_request = environ["wsgi.input"].read(request_body_size) if environ['REQUEST_METHOD'] == 'GET': return self.do_GET(path_info.path, headers, start_response) elif environ['REQUEST_METHOD'] == 'POST': return self.do_POST(path_info.path, raw_request, headers, start_response) elif environ['REQUEST_METHOD'] == 'DELETE': return self.do_DELETE(path_info.path, headers, start_response) else: return self.manage_response_wsgi("", self.NOT_FOUND, start_response)
def app(self, environ: Dict, start_response: Any) -> Iterable[ByteString]: """ Create a WSGI app which serves the metrics from a registry. :param environ: :param start_response: :return: """ url = urlparse(request_uri(environ)) if url.path == '/health': start_response(self.collector.status, [('Content-Type', 'application/json')]) return [b'{}'] if url.path.startswith('/metric'): params = parse_qs(environ.get('QUERY_STRING', '')) r = REGISTRY encoder, content_type = choose_encoder(environ.get('HTTP_ACCEPT')) if 'name[]' in params: r = r.restricted_registry(params['name[]']) output = encoder(r) status = str('200 OK') headers = [(str('Content-type'), content_type)] start_response(status, headers) return [output] start_response('404 Not Found', [('Content-Type', 'application/json')]) return [b'{}']
def get_ui_url(environ): full_url = request_uri(environ) index = full_url.rfind(environ.get('SCRIPT_NAME', '')) if index == -1: raise ValueError('Cannot strip the script URL from full URL "%s"' % full_url) return full_url[:index] + "/ipa/ui"
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 path_info.startswith('/exec'): from subprocess import Popen, PIPE, STDOUT import urllib query = environ.get('QUERY_STRING') args = [] cwd = '.' for var in query.split('&'): split = var.split('=') if split[0] == 'args': args = urllib.unquote_plus(split[1]).split(' ') if split[0] == 'cwd': cwd = split[1] print cwd print args proc = Popen(args, stdout=PIPE, stderr=STDOUT, cwd=cwd) proc.wait() headers = [('Date', rfc822.formatdate(time.time())), ('Content-Type', 'text/plain')] start_response("200 OK", headers) return proc.stdout.readlines() if not self._is_under_root(full_path): return self.not_found(environ, start_response) if path.isdir(full_path): if full_path[-1] <> '/' 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) >= rfc822.parsedate(last_modified)): return self.not_modified(environ, start_response, headers) if_none = environ.get('HTTP_IF_NONE_MATCH') if if_none and (if_none == '*' or etag in if_none): return self.not_modified(environ, start_response, headers) file_like = self._file_like(full_path) headers.append(('Content-Type', content_type)) start_response("200 OK", headers) if environ['REQUEST_METHOD'] == 'GET': return self._body(full_path, environ, file_like) else: return [''] except (IOError, OSError), e: print e return self.not_found(environ, start_response)
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
def route_request(env, start_response): node = env['DFS_NODE_CLASS'] uri = request_uri(env).rstrip('/') path = urlparse(uri).path try: command, deserialize, serialize = node.HANDLERS[path] except KeyError: start_response( '404 Not Found', [('Content-type', 'text/plain')], ) return [b''] args = deserialize( env['wsgi.input'], int(env.get('CONTENT_LENGTH', 0) or 0), env['REMOTE_ADDR'], ) try: resp = command(node, *args) except CommandError as e: start_response( '400 Bad Request', [('Content-type', 'text/plain')], ) return [str(e).encode('utf-8')] start_response( '200 OK', [('Content-type', 'application/octet-stream')], ) return [serialize(resp)]
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")
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
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
def handle_request(self, environ, request_body): """ Entry method for every HTTP request. It calls correspondig method according to method or raises exception if request is mallformed. """ try: #separate path and resource uri = request_uri(environ) uri = urlparse(uri) path_parts = uri.path.split('/') method = environ['REQUEST_METHOD'] if method == 'POST': return self._handle_post_request(path_parts, request_body) elif method == 'GET': return self._handle_get_request(path_parts) else: raise ServerError() except JSONWSPError as exception: return self._handle_jsonwsp_error(exception) except NotFoundError as exception: return self._handle_not_found_error(exception) except ServerError as exception: return self._handle_server_error(exception.string) except: return self._handle_server_error("Unexpected error: %s" % sys.exc_info()[0])
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]
def addMessage(self, environ, start_response): ''' メッセージを追加する ''' # POST データを取得 inpt = environ['wsgi.input'] length = int(environ.get('CONTENT_LENGTH', 0)) # 取得したデータをパースして辞書オブジェクトに変換 query = dict(cgi.parse_qsl(inpt.read(length))) # POST メッセージを保存 msg = { 'name': query['name'], 'title': query['title'], 'body': query['body'], 'date': datetime.datetime.now() } self.messages.append(msg) # リダイレクトを行う start_response('303 See Other', [('Content-type', 'text/plain'), ('Location', util.request_uri(environ))]) return ''
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']
def full_dispatch_request_dynatrace(wrapped, instance, args, kwargs): try: env = flask.request.environ method = env.get("REQUEST_METHOD", "GET") url = env.get("REQUEST_URI") or env.get("RAW_URI") or env.get( "werkzeug.request").url or request_uri(env) host = env.get( "SERVER_NAME") or socket.gethostname() or "localhost" app_name = flask.current_app.name dt_headers = None if os.environ.get("AUTODYNATRACE_CAPTURE_HEADERS", False): dt_headers = dict(flask.request.headers) wappinfo = sdk.create_web_application_info( "{}".format(host), "Flask ({})".format(app_name), "/") except Exception as e: logger.debug("dynatrace - could not instrument: {}".format(e)) return wrapped(*args, **kwargs) with sdk.trace_incoming_web_request(wappinfo, url, method, headers=dt_headers): logger.debug( "dynatrace - full_dispatch_request_dynatrace: {}".format(url)) return wrapped(*args, **kwargs)
def get_request_info(environ: EnvironType) -> ContextType: """Extract logging context friendly request and server information. Extract all values related to server and to the specific request, such as `SERVER_NAME`, `SERVER_PORT`, `PATH_INFO`, `QUERY_STRING`. The names in the resulting dictionary are the same, but converted to lowercase and prefixed with "request_". In addition to these values, two calculated values are also added - `request_uri` and `request_application_uri`. These values are calculated using `wsgiref.util` functions `request_uri` (with `include_query=True`) and `application_uri`. :param environ: WSGI environ (as it is passed to WSGI application). :return: A logging context friendly mapping of request and server information. """ request_info = { "request_method": unicode(environ["REQUEST_METHOD"]), "request_script_name": unicode(environ["SCRIPT_NAME"]), "request_path_info": unicode(environ["PATH_INFO"]), "request_query_string": unicode(environ.get("QUERY_STRING", "")), "request_server_name": unicode(environ["SERVER_NAME"]), "request_server_port": unicode(environ["SERVER_PORT"]), "request_server_protocol": unicode(environ["SERVER_PROTOCOL"]), "request_content_type": unicode(environ.get("CONTENT_TYPE", "")), "request_content_length": unicode(environ.get("CONTENT_LENGTH", "")), "request_uri": unicode(util.request_uri(environ, include_query=True)), "request_application_uri": unicode(util.application_uri(environ)), } return request_info
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
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]
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
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")
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
def __init__(self, env, start_response): start_response('200 OK', self.HEADERS) self.last_heartbeat = None self.env = env self.response = env self.signer = Signer() self.initialized = False self.queue = Queue() try: query = urlparse.parse_qs( urlparse.urlparse( wsgiref_utils.request_uri(env) ).query ) if 'key' not in query: return taskstore_id = self.signer.unsign(query['key'][0]) self.store = TaskStore.objects.get(pk=int(taskstore_id)) try: self.head = query['head'][0] except (KeyError, IndexError): self.head = self.store.repository.head() # Subscribe to the event stream self.subscription = get_announcements_subscription( self.store, **{ 'local_sync.{username}': self.handle_local_sync, 'changed_task.{username}': self.handle_changed_task, 'log_message.{username}': self.handle_log_message, '{username}': self.handle_personal_announcement, settings.ANNOUNCEMENTS_CHANNEL: ( self.handle_public_announcement ), } ) self.subscription_thread = self.subscription.run_in_thread( sleep_time=1 ) # Kick-off a sync just to be sure kwargs = { 'async': True, 'function': ( 'views.Status.iterator' ) } self.store.sync(msg='Iterator initialization', **kwargs) # Let the client know the head has changed if they've asked # for a different head than the one we're on: if self.head != self.store.repository.head(): for task_id in self.store.get_changed_task_ids(self.head): self.add_message('task_changed', task_id) self.initialized = True except Exception as e: logger.exception("Error starting event stream: %s", str(e))
def _search_render_facets(self, facets, queryparams, environ): facetgroups = [] commondata = self.repos[0].commondata searchurl = request_uri(environ, include_query=False) for facetresult in ('type', 'creator', 'issued'): if facetresult in facets: if facetresult in queryparams: # the user has selected a value for this # particular facet, we should not display all # buckets (but offer a link to reset the value) qpcopy = dict(queryparams) del qpcopy[facetresult] href = "%s?%s" % (searchurl, urlencode(qpcopy)) val = queryparams[facetresult] if facetresult == "creator": val = self.repos[0].lookup_label(val) elif facetresult == "type": val = self.repolabels.get(val, val) lbl = "%s: %s" % (self.facetlabels.get( facetresult, facetresult), val) facetgroups.append( html.LI([ lbl, html.A( "\xa0", **{ 'href': href, 'class': 'glyphicon glyphicon-remove' }) ])) else: facetgroup = [] for bucket in facets[facetresult]['buckets']: if facetresult == 'type': lbl = self.repolabels.get(bucket['key'], bucket['key']) key = bucket['key'] elif facetresult == 'creator': k = URIRef(bucket['key']) pred = SKOS.altLabel if commondata.value( k, SKOS.altLabel) else FOAF.name lbl = commondata.value(k, pred) key = bucket['key'] elif facetresult == "issued": lbl = bucket["key_as_string"] key = lbl qpcopy = dict(queryparams) qpcopy[facetresult] = key href = "%s?%s" % (searchurl, urlencode(qpcopy)) facetgroup.append( html.LI([ html.A("%s" % (lbl), **{'href': href}), html.Span([str(bucket['doc_count'])], **{'class': 'badge pull-right'}) ])) lbl = self.facetlabels.get(facetresult, facetresult) facetgroups.append( html.LI([html.P([lbl]), html.UL(facetgroup)])) return html.Div(facetgroups, **{'class': 'facets'})
def simple_app(environ, start_response): uri = request_uri(environ) # 获取 client 请求的地址 URI location = uri[:4] + 's' + uri[4:] # 将 http 替换成 https status = '301 Moved Permanently' # 设置 Status Code headers = [ ('Content-length', '0'), ('Location', location) ] # 设置 headers start_response(status, headers) return b''
def __call__(self, environ, start_response): relative_path = urllib.url2pathname(environ['PATH_INFO']) full_path = os.path.join(self.root, relative_path) if not (os.path.isfile(full_path) and os.access(full_path, os.R_OK)): raise HttpNotFound({'uri': request_uri(environ, 0), 'href': environ['PATH_INFO'], 'path': relative_path}) return self.serve_content(start_response, full_path)
def view_static(environ, start_response): if environ['REQUEST_METHOD'].lower() == 'get': uri = request_uri(environ, include_query=False).replace( application_uri(environ), '') start_response('200 OK,', [('Content-Type', f'text/{uri.split(".")[1]}')]) with open(uri, 'rt') as response: return response.read()
def __init__(self, env, start_response): start_response("200 OK", self.HEADERS) self.last_heartbeat = None self.env = env self.response = env self.signer = Signer() self.initialized = False self.queue = Queue() client = get_lock_redis() pickled_data = pickle.loads(client.get(f"pickle_{env['PICKLE_ID']}")) self.store = pickled_data["taskstore"] self.username = pickled_data["username"] try: logger.info( "Starting event stream for TaskStore %s for user %s", self.store.pk, self.username, ) query = urlparse.parse_qs( urlparse.urlparse(wsgiref_utils.request_uri(env)).query) try: self.head = query["head"][0] except (KeyError, IndexError): self.head = self.store.repository.head().decode("utf-8") # Subscribe to the event stream self.subscription = get_announcements_subscription( self.store, self.username, [ "local_sync.{username}", "changed_task.{username}", "log_message.{username}", "personal.{username}", settings.ANNOUNCEMENTS_CHANNEL, ], ) # Kick-off a sync just to be sure kwargs = { "asynchronous": True, "function": ("views.Status.iterator") } self.store.sync(msg="Iterator initialization", **kwargs) # Let the client know the head has changed if they've asked # for a different head than the one we're on: if self.head != self.store.repository.head().decode("utf-8"): for task_id in self.store.get_changed_task_ids(self.head): self.add_message("task_changed", task_id) self.initialized = True except Exception as e: logger.exception("Error starting event stream: %s", str(e))
def __call__(self, environ, start_response): ''' レスポンス ''' pathinfo = environ.get('PATH_INFO', '') abs = os.path.join(self.localRoot, '.' + pathinfo) # ない if not os.path.exists(abs): handler = self.handlers.get(404, responses.notFound) return handler(environ, start_response) try: # ディレクトリ if os.path.isdir(abs): if abs[-1] != '/': return responses.seeOther(environ, start_response, util.request_uri(environ)+'/') else: items = os.listdir(abs) # index を探してみる for index in self.indexFiles: indexFile = os.path.join(abs, index) # あった if index in items and os.path.isfile(indexFile): now = environ['PATH_INFO'] environ['PATH_INFO'] = os.path.join(now, index) return self.publishFile(environ, start_response) # 一覧表示 return self.listContents(environ, start_response) else: # ファイル return self.publishFile(environ, start_response) except IOError, e: handler = self.handlers.get(403, responses.forbidden) return handler(environ, start_response)
def error(environment, start_response, code): html = ''' <html><body> <h1>%(error)s</h1> The requested URL <i>%(url)s</i> returned a %(error)s %(description)s.<br> <img src = http://httpcats.herokuapp.com/%(error)s.jpg /> </body></html>''' start_response('%s %s' % (code, description[code]), [('content-type', 'text/html')]) return [html % {'url': util.request_uri(environment), 'error': code, 'description': description[code]}]
def listMessages(self, environ, start_response): ''' 一覧表示 ''' fp = StringIO.StringIO() # ヘッダを出力 fp.write(r'''<html> <head><title>Message Board</title> <meta http-equiv="Content-type" content="text/html; charset=utf-8"> </head> <body> ''') # メッセージ数分繰り返し for msg in reversed(self.messages): esc = saxutils.escape tmp = {} # 入力を全てエスケープして出力 for key, value in msg.iteritems(): value = str(value) tmp[key] = str(esc(unicode(value, 'utf-8', 'ignore'))) # メッセージの内容を書き出す fp.write('''<dl> <dt>title</dt> <dd>%(title)s</dd> <dt>name</dt> <dd>%(name)s</dd> <dt>date</dt> <dd>%(date)s</dd> <dt>message</dt> <dd>%(body)s</dd> </dl><hr />''' % tmp) # 書込み用フォームを出力 fp.write('''<form action="%s" method="POST" AcceptEncoding="utf-8"> <dl> <dt>name</dt> <dd><input type="text" name="name"/></dd> <dt>title</dt> <dd><input type="text" name="title"/></dd> <dt>body</dt> <dd><textarea name="body"></textarea></dd> </dl> <input type="submit" name="save" value="Post" /> </form> </body></html>''' % util.request_uri(environ)) # シーク位置を先頭にしておく fp.seek(0) start_response('200 OK', [('Content-type', 'text/html; charset=utf-8')]) return fp
def parse_environment(env): request = Request() request.request_uri = util.request_uri(env, True) for k, v in env.items(): request.__dict__.setdefault(k.lower(), v) request.query_parameters = Request.parse_parameters( request.query_string) return request
def __call__(self, environ, start_response): wsgi = Wsgi(environ) method = wsgi.method() uri = Uri.parse(request_uri(environ, True)) headers = wsgi.headers() if 'Content-Length' in headers and headers['Content-Length'] != '': body = Body(environ['wsgi.input'], int(headers['Content-Length'])) else: body = Body(environ['wsgi.input'], 0) request = Request(method, uri, headers, body) context = Context() context.env = environ context.request = request # Prepare our root controller controller = self.root_controller() # Fetch the response given our request response = controller.handle(context) controller.release() if not isinstance(response, Response): raise AttributeError( 'Value returned from root controller not a response: ' + str(response)) # Convert the headers headers2 = [] has_length = False content_length = 0 for name, value in response.headers(): if name == 'Content-Length': content_length = int(value) has_length = True headers2 += [(name, value)] # Obtain the body body = response.body() if hasattr(body, 'read'): content = body.read() elif isinstance(body, str): content = body.encode('ascii') else: content = body request.release() # If Content-Length is not set, set it if not has_length: headers2 += [('Content-Length', str(len(content)))] # Return print("HEADER", headers2) start_response(response.status(), headers2) response.release() return [content]
def app(environ, start_response): if request_uri(environ).endswith('/bug'): response = [this_is_a_bug] else: response = [ '{0}: {1}\n'.format(key, value).encode('utf-8') for key, value in environ.items() ] start_response('200 OK', [('Content-type', 'text/plain; charset=utf-8')]) return response
def is_valid(self): url = request_uri(self.environ) filename = self.regex.search(url) if filename: for app in self.apps: path = '{0}/{1}'.format(app, filename.group(0)) if os.path.exists(path): self.path = path return True return False
def execute_route(example, route, environ, start_response): for part in example: if 'routes' in part and route in part['routes']: url = request_uri(environ) result = part['routes'][route](url) # XXX todo: set headers generic response = Response(content_type='application/json', body=result['body']) return response(environ, start_response) raise ValueError('No route to: %s' % environ['PATH_INFO'])
def _add_request_attributes(span, environ): span.set_attribute("component", "http") span.set_attribute("http.method", environ["REQUEST_METHOD"]) host = environ.get("HTTP_HOST") or environ["SERVER_NAME"] span.set_attribute("http.host", host) url = (environ.get("REQUEST_URI") or environ.get("RAW_URI") or wsgiref_util.request_uri(environ, include_query=False)) span.set_attribute("http.url", url)
def __call__(self, environ, start_response): """Respond to a request when called in the usual WSGI way.""" 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] <> '/' 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) try: sz = int(environ['CONTENT_LENGTH']) except: sz = 0 if environ['REQUEST_METHOD'] == 'PUT' and sz > 0: for putglob in self.puttable: if fnmatch(path_info, putglob): data = environ['wsgi.input'].read(sz) try: with open(full_path, "wb") as f: f.write(data) return self.success_no_content(environ, start_response) except: print sys.exc_info()[1] return self.server_error(environ, start_response) if environ['REQUEST_METHOD'] not in ('GET', 'HEAD'): headers = [('Allow', 'GET, HEAD')] return self.method_not_allowed(environ, start_response, headers) 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) >= rfc822.parsedate(last_modified)): return self.not_modified(environ, start_response, headers) if_none = environ.get('HTTP_IF_NONE_MATCH') if if_none and (if_none == '*' or etag in if_none): return self.not_modified(environ, start_response, headers) file_like = self._file_like(full_path) headers.append(('Content-Type', content_type)) start_response("200 OK", headers) if environ['REQUEST_METHOD'] == 'GET': return self._body(full_path, environ, file_like) else: return [''] except (IOError, OSError), e: print e return self.not_found(environ, start_response)
def redirect(request, path, code=302, message=None): """Redirect client to another path in the application.""" response = request.response response.set_status(code, message) env2 = dict(request.environ) t = path.split('?', 2) env2['PATH_INFO'] = t[0] if len(t) > 1: env2['QUERY_STRING'] = t[1] response.set_header('Location', request_uri(env2)) return []
def get_wsgi_headers(self, environ): headers = self.headers location = headers.get("location") if location and not location.startswith("http"): headers["location"] = urljoin(request_uri(environ), location) if not headers.get("Content-Length") and not headers.get("Transfer_Encode"): headers["Content-Length"] = len(self.body) headers.setdefault("Content-Type", self.DEFAULT_CTYPE) return headers.to_wsgi_list()
def return_http_request_404(self,environ, start_response): ''' 404 Not Found用メソッド input : environ,start_response output: TEXT(404 Not Found) raise : none ''' start_response(Controller.HTTP_STS_404, Controller.HTTP_RESPONSE_HEADER_TEXT) return '%s is not found' % util.request_uri(environ)
def __call__(self, environ, start_response): path_info = environ['PATH_INFO'] script_name = environ['SCRIPT_NAME'] request_method = environ['REQUEST_METHOD'] for regex, method_list, controller in self.mappings: match = regex.match(path_info) if not match: continue if request_method not in method_list: raise HttpMethodNotAllowed({'uri': request_uri(environ, 0), 'method': request_method}) environ['PATH_INFO'] = '' environ['SCRIPT_NAME'] = script_name + path_info request = Request(environ) response = Response() args = match.groups() body = controller(request, response, *args) or '' start_response(*response.start_response_args(body)) return body raise HttpNotFound({'uri': request_uri(environ, 0)})
def get_resource(): key = shift_path_info(environ) content1, metadata = drv.get_resource(key) if content1 is None: #404 error start_response('404 Not Found', [('content-type', 'text/html')]) response = four_oh_four.substitute(url=request_uri(environ)) return response start_response('200 OK', [('content-type', str(metadata[CONTENT_TYPE]))]) return content1.encode('utf-8')
def test_app(environ, start_response): response_headers = [('content-type', 'text/plain')] for name, value in environ.items(): if name.startswith('HTTP_'): header_name = name[len('HTTP_'):].lower().replace('_', '-') if header_name.startswith('header'): response_headers.append((header_name, 'echo: ' + value)) start_response('200 OK', response_headers) response_string = '\n'.join(['Uri: %s' % wsgi_util.request_uri(environ), 'Method: %s' % environ['REQUEST_METHOD'], message]) return [str.encode(response_string)]
def application(environ, start_response): status = '200 OK' responce_headers = [('Content-type', 'text/html; charset=utf-8')] path = urlparse(request_uri(environ)).path print urlparse(request_uri(environ)).path if path.startswith('/pub'): if os.path.isfile(BASEDIR + path): filename = BASEDIR + path mime = path.rsplit('.', 1)[1] responce_headers = [('Content-type', 'text/' + MIMETYPE.get(mime, 'plain'))] else: template = status = '404 Not Found' else: filename = BASEDIR + '/template/index.html' if not locals().has_key('template'): f = open(filename) template = f.read() start_response(status, responce_headers) return [template]