def __call__(self, environ, start_response): request = Request(environ) request.charset = 'utf8' http_method = request.params.get( 'X-HTTP-Method-Override', request.headers.get('X-HTTP-Method-Override', request.method)).upper() method = getattr(self, http_method, None) if method is None or not callable(method): response = Response(status=405, body="<h1>HTTP Method Not Allowed</h1>") else: args_re = getattr(method, 'url_map', None) args = [] kwargs = {} if args_re is not None: match = args_re.match(request.path_info) if match is not None: args = match.groups() kwargs = match.groupdict() else: args = request.path_info.strip('/').split('/') response = method(request, *args, **kwargs) start_response(response.status, response.headerlist) return response.app_iter
def wrapped(environ, start_response): req = Request(environ) req.charset = 'utf8' app = func(req) if app is None: app = HTTPNotFound(u'Нет такой страницы') return app(environ, start_response)
def wrapped(environ, start_response): req = Request(environ) if req.charset is None: req.charset = 'UTF-8' print req.user_agent, 'sucks' try: app = func(req) except HTTPException, app: pass
def __call__(self, environ, start_response): # create webob Request req = Request(environ) req.charset = 'utf8' client_id = db.is_authorized(environ['pysmsd.db.path'], req.params.get('name', ''), req.params.get('password', '')) if client_id != None: environ['pysmsd.client.id'] = client_id environ['pysmsd.client.name'] = req.params.get('name') return self.application(environ, start_response) else: return HTTPUnauthorizedJSON()(environ, start_response)
def __call__(self, environ, start_response): req = Request(environ) req.charset = 'utf8' try: query = self.parse_request_params(req.params) data = Api().execute(query) except AssertionError as e: data = { 'error': e.args } json_data = json.dumps(data) response = Response(json_data, content_type='application/json') return response(environ, start_response)
def __call__(self, environ, start_response): req = Request(environ) req.charset = 'utf8' try: query = self.parse_request_params(req.params) data = Api().execute(query) except AssertionError as e: data = {'error': e.args} json_data = json.dumps(data) response = Response(json_data, content_type='application/json') return response(environ, start_response)
def __call__(self, environ, start_response): # create webob Request req = Request(environ) req.charset = 'utf8' client_id = \ req.environ['pysmsd.db'].is_authorized( req.params.get('name', ''), req.params.get('password', '')) if client_id != None: environ['pysmsd.client.id'] = client_id environ['pysmsd.client.name'] = req.params.get('name') return self.application(environ, start_response) else: return HTTPUnauthorizedJSON()(environ, start_response)
def __call__(self, environ, start_response): request = Request(environ=environ) environ['spynach.locals'].register(environ, a_request, request) response = Response(body="spynach Default Page", content_type='text/html', charset='utf-8') environ['spynach.locals'].register(environ, a_response, response) if self.force_request_encoding: request.charset = self.force_request_encoding static_path = self.statics + request.path_info if os.path.exists(static_path) and os.path.isfile(static_path): response = FileApp(static_path) else: try: self.authenticator.authenticate(request) self.root._dispatch(request) self.authenticator.inject_cookie(response) except HTTPException, e: response = e self.authenticator.inject_cookie(response)
def __call__(self, environ, start_response): request = Request(environ) request.charset = 'utf8' http_method = request.params.get('X-HTTP-Method-Override', request.headers.get('X-HTTP-Method-Override', request.method)).upper() method = getattr(self, http_method, None) if method is None or not callable(method): response = Response(status=405, body="<h1>HTTP Method Not Allowed</h1>") else: args_re = getattr(method, 'url_map', None) args = [] kwargs = {} if args_re is not None: match = args_re.match(request.path_info) if match is not None: args = match.groups() kwargs = match.groupdict() else: args = request.path_info.strip('/').split('/') response = method(request, *args, **kwargs) start_response(response.status, response.headerlist) return response.app_iter
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 = db.is_authorized(req.environ['pysmsd.db.path'], 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 try: res = action(req) except: return HTTPInternalServerErrorJSON()(environ, start_response) 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)
def powapp_simple_server(environ, start_response): #print show_environ_cli(environ) output = [] powdict = {} real_action = None req = Request(environ) req.charset = pow.global_conf["DEFAULT_ENCODING"] #print "webob: req.params", req.params #print "webob: req.body", req.body #print dir(req.params) # # relevant parameters have to be defined here # (Same as for apache the declarations in the httpd.conf file # # redirect static media from the meta link static to the real source dir # advantage is: you can alway refer safely to /static/<something> inside your css o .tmpl # files and the real source can be anywhere. sometimes the real static source differs from # prod-webserver A to prod-webserver B. with this litte tirck you can leave your links unchanged. # for apache the redirection is done in http.conf alias_dict ={ "/static/css/" : "./public/css/", "/static/stylesheets/" : "./public/css/", "/static/scripts/" : "./public/js/", "/static/js/" : "./public/js/", "/static/documents/" : "./public/doc/", "/static/doc/" : "./public/doc/", "/static/ico/" : "./public/ico/", "/static/img/" : "./public/img/" } environ["SCRIPT_FILENAME"] = __file__ powdict["POW_APP_NAME"] = "atest" powdict["POW_APP_URL"] = "www.pythononwheels.org" powdict["POW_APP_DIR"] = environ.get("pow.wsgi_dir") powdict["ERROR_INFO"] = "NONE" # Get the session object from the environ session = environ['beaker.session'] #TO_DO: set the right status in the end, according to the situatio instead of setting it hard-coded here status = '200 OK' response_headers = [ #('Content-type', 'text/html; charset=utf-8') ('Content-type', 'text/html') ] if not session.has_key('user.id'): session['user.id'] = 0 #session.save() powdict["SESSION"] = session print "-- request info:" print "-- webob: req.content_type: ", req.content_type print "-- webob: ", req.method powdict["REQ_CONTENT_TYPE"] = req.content_type powdict["REQ_PARAMETERS"] = req.params powdict["REQ_BODY"] = req.body print powdict["REQ_PARAMETERS"] if MODE > MODE_NORMAL: print plist print plist.keys() plist = req.params #if plist.has_key("image"): # print "Image found: ", plist['image'].filename # ofile = file(plist['image'].filename, "wb") # infile = plist['image'].file # ofile.write( infile.read() ) # #ofile.write( plist["image"].value ) # ofile.close() # # handling static files # pinfo = environ.get("PATH_INFO") pinfo_before = pinfo ostr = "" # # check for static links and replace them when found. # found_static = False for elem in alias_dict: if string.find(pinfo, elem) != -1: found_static = True pinfo = string.replace(pinfo,elem, alias_dict[elem]) environ["PATH_INFO"] = pinfo if found_static == True: print "-- Static REQUEST --------------------------------------------------------- " non_binary = [".css", ".html",".js",".tmpl"] ctype = "UNINITIALIZED" ftype = os.path.splitext(pinfo)[1] if string.lower(ftype) in non_binary: infile = open (os.path.normpath(pinfo), "r") else: infile = open (os.path.normpath(pinfo), "rb") ostr = infile.read() infile.close() #print "file type is: ", ftype, " -> ", ctype if string.lower(ftype) == ".gif": ctype = "image/gif" elif string.lower(ftype) == ".jpg" or string.lower(ftype) ==".jpeg": ctype= "image/jpeg" elif string.lower(ftype) == ".css": ctype = "text/css" elif string.lower(ftype) == ".png": ctype = "image/png" elif string.lower(ftype) ==".js": ctype= "application/x-javascript" else: ctype = "text/html" #print "file type is: ", ftype, " responding with type-> ", ctype response_headers = [ ('Content-type', ctype ) ] start_response(status, response_headers) return [ostr] print "-- Dynamic REQUEST --------------------------------------------------------- " if MODE > MODE_INFO : print "Request: " + environ["REQUEST_METHOD"] + " " + environ["PATH_INFO"] + " " + environ["SERVER_PROTOCOL"] + " " + environ["QUERY_STRING"] print "PATH_INFO before: ", pinfo_before print "PATH_INFO after: ", pinfo if not session.has_key('counter'): session['counter'] = 0 else: session['counter'] += 1 powdict["SCRIPT_FILENAME"] = environ.get("SCRIPT_FILENAME") powdict["SCRIPT_DIR"] = os.path.dirname(environ.get("SCRIPT_FILENAME")) powdict["SCRIPT_VIEWS_DIR"] = os.path.abspath(os.path.join(os.path.dirname(environ.get("SCRIPT_FILENAME")) + "/views/")) # PATH_INFO contains the path beginning from the app-root url. # first part is the controller, # second part is the action powdict["PATH_INFO"] = environ.get("PATH_INFO") #print os.path.split(powdict["PATH_INFO"]) powdict["ENVIRON"] = pow_web_lib.show_environ( environ ) powdict["DOCUMENT_ROOT"] = environ.get("DOCUMENT_ROOT") powdict["FLASHTEXT"] = "" powdict["FLASHTYPE"] ="error" #output.append( show_environ( output, environ ) ) # # get controller and action # print "environ[\"PATH_INFO\"] = ", environ["PATH_INFO"] pathdict = pow_web_lib.get_controller_and_action(environ["PATH_INFO"]) #(controller,action) = os.path.split(pathinfo) print "(controller,action) -> ", pathdict controller = powdict["CONTROLLER"] = pathdict["controller"] action = powdict["ACTION"] = pathdict["action"] powdict["PATHDICT"]=pathdict #TO_DO: include the real, mod re based routing instead of seting it hard to user/list here. if controller == "": defroute = pow.routes["default"] #defroute = powlib.readconfig("pow.cfg","routes","default") print pow_web_lib.get_controller_and_action(defroute) pathdict = pow_web_lib.get_controller_and_action(defroute) #(controller,action) = os.path.split(pathinfo) print "(controller,action) -> ", pathdict controller = powdict["CONTROLLER"] = pathdict["controller"] action = powdict["ACTION"] = pathdict["action"] powdict["PATHDICT"]=pathdict print "Using the DEFAULT_ROUTE: ", print "(controller,action) -> ", pathdict # get rid of the first / in front of the controller. string[1:] returns the string from char1 to len(string) controller = string.capitalize(controller) + "Controller" # # route the request # #print "Loading Class:", controller aclass = powlib.load_class(controller,controller) #print "setting Action: ", action aclass.setCurrentAction(action) #output.append(action + "<br>") # checking if action is locked if aclass.is_locked(action): # locked, so set the action to the given redirection and execute that instead. # TODO: Could be aditionally coupled with a flashtext. print "Action: ", action, " locked." cont, action = aclass.get_redirection_if_locked(action) if cont != None and cont != "None" and cont != "": controller = string.capitalize(cont) + "Controller" aclass = powlib.load_class(controller,controller) aclass.setCurrentAction(action) print " -- Redirecting to: ", action # # Now really execute the action # if hasattr( aclass, action ): real_action = eval("aclass." + action) output.append(real_action(powdict).encode(pow.global_conf["DEFAULT_ENCODING"])) else: msg = "ERROR: No such class or action %s.%s " % (controller, action) output.append(msg) # # error handling wsgi see: http://www.python.org/dev/peps/pep-0333/#error-handling # start_response(status, response_headers) return output
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)
req.params req.params['name'] req.params.getall('name') for name, value in req.params.items(): print '%s: %r' % (name, value) req = Request.blank('/test?check=a&check=b&name=Bob') req.method = 'PUT' req.body = body = 'var1=value1&var2=value2&rep=1&rep=2' req.environ['CONTENT_LENGTH'] = str(len(req.body)) req.environ['CONTENT_TYPE'] = 'application/x-www-form-urlencoded' req.GET # Why post have items??? req.POST req.charset = 'utf8' req = Request.blank('/') def wsgi_app(environ, start_response): start_response('200 OK', [('Content-type', 'text/plain')]) return ['Hi!'] req.call_application(wsgi_app) res = req.get_response(wsgi_app) # add user defined attribute req.some_attr = 'blah blah blah' new_req = Request(req.environ) new_req.some_attr req.environ['webob.adhoc_attrs'] # response
req.params req.params['name'] req.params.getall('name') for name, value in req.params.items(): print '%s: %r' % (name, value) req = Request.blank('/test?check=a&check=b&name=Bob') req.method = 'PUT' req.body = body = 'var1=value1&var2=value2&rep=1&rep=2' req.environ['CONTENT_LENGTH'] = str(len(req.body)) req.environ['CONTENT_TYPE'] = 'application/x-www-form-urlencoded' req.GET # Why post have items??? req.POST req.charset = 'utf8' req = Request.blank('/') def wsgi_app(environ, start_response): start_response('200 OK', [('Content-type', 'text/plain')]) return ['Hi!'] req.call_application(wsgi_app) res = req.get_response(wsgi_app) # add user defined attribute req.some_attr = 'blah blah blah' new_req = Request(req.environ)