def feature_forms(context): content_length = -1 content_type = context.environ.get("CONTENT_TYPE", "application/unknown") data = context.environ.get("wsgi.input", None) params = {} files = {} try: content_length = int(context.environ.get("CONTENT_LENGTH", "0")) except ValueError: pass if content_length > 0: if content_type == "application/x-www-form-urlencoded": params = urlparse.parse_qs(data.read(content_length)) elif content_type.startswith("multipart/form-data"): index = content_type.rfind("=") + 1 boundary = content_type[index:] parser = None try: parser = multipart.MultipartParser(boundary, data) params = parser.params files = parser.files except multipart.MultipartException: crazyhorse.get_logger().error("Failed to parse multipart/form-data") pass context.request.data = ParamCollection(params) context.request.files = ParamCollection(files)
def decorator(f): if is_temp_action: if route_name not in routing.temp_routes: routing.temp_routes[route_name] = {} routing.temp_routes[route_name][method] = (module_path + '.' + controller, f.__name__) else: route.register_action_for_method(method, module_path + '.' + controller, f.__name__) crazyhorse.get_logger().debug("Registered Route {0}: {1} to {2}.{3}".format(method, route.path, module_path + '.' + controller, f.__name__)) return f
def __call__(self, section): crazyhorse.get_logger().debug("Processing CrazyHorse Configuration") features = None try: features = self.initialize_features(section["features"]) except KeyError: crazyhorse.get_logger().critical("No crazyhorse features defined in config") return features
def decorator(f): args = {"name" : name, "path" : path, "constraints" : constraints, "controller" : module_path + "." + controller, "action" : f.__name__, "method" : method } route = routing.register_route(**args) crazyhorse.get_logger().debug("Registered Route {0}: {1} to {2}.{3}".format(method, path, args["controller"], f.__name__)) return f
def import_module(pkg): module = None if "/" in pkg: pkg = pkg.replace("/", ".") try: module = importlib.import_module(pkg) except ImportError as e: crazyhorse.get_logger().warning("Unable to import module {0}: {1}".format(pkg, e.message)) return None return module
def process_orphaned_routes(self): router = routing.application_router if len(routing.temp_routes) > 0: for route_name in routing.temp_routes: try: route = router.route_with_name(route_name) for method in routing.temp_routes[route_name]: controller, action = routing.temp_routes[route_name][method] route.register_action_for_method(method, controller, action) except: temp_route = routing.temp_routes[route_name] for key in temp_route.iterkeys(): crazyhorse.get_logger().warning("Failed to register route for with name: {0} for {1}::{2}".format(route_name, temp_route[key][0], temp_route[key][1])) del routing.temp_routes
def __call__(self, section): crazyhorse.get_logger().debug("Processing Application Configuration") settings = None try: self.initialize_system(section["system"]) except KeyError: crazyhorse.get_logger().fatal("No system section defined in application config") raise exceptions.ConfigurationErrorException("No system section defined in application config") if "custom_errors" in section: self.initialize_custom_errors(section["custom_errors"]) if "settings" in section: settings = section["settings"] return settings
def initialize_application_default_view(self, config): view_path = None try: view_path = config.settings["default_view"] except KeyError: crazyhorse.get_logger().warning("No default_view specified in config. Calling MyController.view() will throw error") return parts = view_path.split(".") view_classname = parts.pop() view_module_path = ".".join(parts) crazyhorse.get_logger().debug("importing default view {0}".format(view_module_path + "." + view_classname)) view_module = __import__(view_module_path, globals(), locals(), [str(view_classname)]) view_class = getattr(view_module, view_classname) CrazyHorseController.view_class = view_class
def import_class(pkg, cls=None): module = None if "/" in pkg: pkg = pkg.replace("/", ".") if cls is None: parts = collections.deque(pkg.split(".")) cls = parts.pop() pkg = ".".join(parts) try: module = importlib.import_module(pkg) except ImportError as e: crazyhorse.get_logger().warning("Unable to import {0} from {1}: {2}".format(cls, pkg, e.message)) return None return getattr(module, cls, None)
def initialize_application_controllers(self, config): controllers_path = None try: controllers_path = config.settings["controllers"] except KeyError: crazyhorse.get_logger().fatal("No controller module defined in config") raise exceptions.ConfigurationErrorException("No controllers module defined in settings") controllers_path = controllers_path.replace(".", "/") #process controllers for any routes for file_path in glob.iglob("{0}/*.py".format(controllers_path)): if os.path.basename(file_path).startswith("__"): continue file_path = os.path.splitext(file_path)[0] module_path = file_path.replace("/", ".") crazyhorse.get_logger().debug("processing routes within controller {0}".format(module_path)) module = __import__(module_path, globals(), locals())
def __init__(self, application=None): #self.router = options["router"]() if "router" in options else None #self.authorization = options["authorization"]() if "authorization" in options else None #self.sessions = options["sessions"] if "sessions" in options else None #self.cookies = options["cookies"] if "cookies" in options else None #self.request_parser = options["request_parser"] if "request_parser" in options else None #self.views = options["views"] if "views" in options else None # fire it up! crazyhorse.get_logger().info("Initializing CrazyHorse") Configuration() return if application is not None: application_start = getattr(application, "application_start", None) if application_start: crazyhorse.get_logger().debug("Executing custom application_start") application_start()
def initialize_sections(self, config): application_section = ApplicationSection() crazyhorse_section = CrazyHorseSection() try: Configuration.APP_SETTINGS = application_section(config["application"]) except KeyError: crazyhorse.get_logger().fatal("No application section defined in config") raise exceptions.ConfigurationErrorException("No application section defined in config") try: Configuration.CRAZYHORSE_FEATURES = crazyhorse_section(config["crazyhorse"]) except KeyError: crazyhorse.get_logger().fatal("No crazyhorse section defined in config") raise exceptions.ConfigurationErrorException("No crazyhorse section defined in config") if "custom_sections" in config: for custom_section in config["custom_sections"]: self.initialize_custom_section(config, custom_section)
def initialize_custom_section(self, config, meta): name = meta["name"] pkg = meta["type"] cls = import_class(pkg) obj = None section = None crazyhorse.get_logger().debug("Processing {0} Configuration".format(cls.__name__)) if name in config: section = config[name] obj = cls() config_name = "CUSTOM_" + name.upper().replace("-", "_") if section: setattr(Configuration, config_name, obj(section)) else: setattr(Configuration, config_name, obj())
def initialize_controllers(self, section): controllers = None try: controllers = section["controllers"] except KeyError: crazyhorse.get_logger().fatal("No controller array defined in config") raise exceptions.ConfigurationErrorException("No controllers array defined in application config") for controller in controllers: controllers_path = controller.replace(".", "/") #process controllers for any routes for file_path in glob.iglob("{0}/*.py".format(controllers_path)): if os.path.basename(file_path).startswith("__"): continue file_path = os.path.splitext(file_path)[0] module_path = file_path.replace("/", ".") crazyhorse.get_logger().debug("Processing routes within controller {0}".format(module_path)) module = import_module(module_path) self.process_orphaned_routes() self.generate_route_json()
def __init__(self, application=None): # fire it up! crazyhorse.get_logger().info("Initializing CrazyHorse") crazyhorse.get_logger().debug("Processing Configuration") Configuration() if application is not None: application_start = getattr(application, "application_start", None) if application_start: crazyhorse.get_logger().debug("Executing custom application_start") application_start()
def initialize_features(self, section): result = {} if "request_body" in section: crazyhorse.get_logger().debug("Feature Enabled: Request Body") result["request_body"] = self.load_feature(section["request_body"]) if "sessions" in section: crazyhorse.get_logger().debug("Feature Enabled: Sessions") result["sessions"] = self.load_feature(section["sessions"]) if "cookies" in section: crazyhorse.get_logger().debug("Feature Enabled: Cookies") result["cookies"] = self.load_feature(section["cookies"]) if "querystrings" in section: crazyhorse.get_logger().debug("Feature Enabled: Query Strings") result["querystrings"] = self.load_feature(section["querystrings"]) return result
def initialize_default_view(self, section): view_path = None try: view_path = section["default_view"] except KeyError: crazyhorse.get_logger().warning("No default_view specified in config. Calling MyController.view() will throw error") return crazyhorse.get_logger().debug("Registering default view: {0}".format(view_path)) cls = import_class(view_path) if cls: CrazyHorseController.view_class = cls return crazyhorse.get_logger().fatal("Failed to import specified default view: {0}. Calling MyController.view() will throw error".format(view_path)) raise exceptions.ConfigurationErrorException("Failed to import specified default view")
def application_start(self): crazyhorse.get_logger().debug("application_start")
def __call__(self, environ, start_response): route = None context = None path = environ["PATH_INFO"] router = routing.application_router try: route = router.route_for_path(path) except exceptions.InvalidRoutePathException: try: route = router.route_with_name("404") except exceptions.InvalidRouteNameException: # No 404 route, we are done here start_response(ResponseStatus.NOT_FOUND, []) return [] # we have a route object, lets get busy: context = HttpContext(environ, start_response) # -------- testing stuff #print(environ) #content_length = -1 #try: # content_length = int(context.environ.get("CONTENT_LENGTH", "0")) #except ValueError: # pass # #if "wsgi.input" in environ: # print(content_length) # data = environ["wsgi.input"].read(content_length) # f = open("multipart-request.txt", "wb") # f.write(data) # #environ["wsgi.input"].seek(0) # # start_response("200 Ok", []) # return [] # -------- # apply features application_features = Configuration.CRAZYHORSE_FEATURES [application_features[x](context) for x in application_features] # TODO I think I can make this nicer # Feels a little sloppy to me # TODO design hook for authorization/authentication try: context.response.result = route(context) except exceptions.RouteExecutionException as e: crazyhorse.get_logger().error(e.message) try: route = router.route_with_name("500") context.response.result = route(context) except exceptions.InvalidRouteNameException, exceptions.RouteExecutionException: # No 500 route, or it failed, in either case we are done here start_response(ResponseStatus.SERVER_ERROR, []) return []