def __build_list(self, key, target_type=list, val=[]):
        if key in self.request.parameters.keys():
            ori_list = self.request.parameters[key]
        else:
            ori_list = val

        if target_type == List[int]:
            try:
                return [int(p) for p in ori_list]
            except:
                raise HttpError(400, None, f"One of the parameter[{key}] is not int. ")
        elif target_type == List[float]:
            try:
                return [float(p) for p in ori_list]
            except:
                raise HttpError(400, None, f"One of the parameter[{key}] is not float. ")
        elif target_type == List[bool]:
            return [p.lower() not in ("0", "false", "") for p in ori_list]
        elif target_type in (List[dict], List[Dict]):
            try:
                return [json.loads(p) for p in ori_list]
            except:
                raise HttpError(400, None, f"One of the parameter[{key}] is not JSON string. ")
        elif target_type == List[Parameter]:
            return [Parameter(name=key, default=p, required=False) for p in ori_list]
        else:
            return ori_list
 def __build_multipart(self, key, val=MultipartFile()):
     name = val.name if val.name is not None and val.name != "" else key
     if val._required and name not in self.request.parameter.keys():
         raise HttpError(400, "Missing Parameter", f"Parameter[{name}] is required.")
     if name in self.request.parameter.keys():
         v = self.request.parameter[key]
         if isinstance(v, MultipartFile):
             return v
         else:
             raise HttpError(400, None, f"Parameter[{name}] should be a file.")
     else:
         return val
Ejemplo n.º 3
0
 def __build_json_body(self):
     if "content-type" not in self.request._headers_keys_in_lowcase.keys() or \
             not self.request._headers_keys_in_lowcase["content-type"].lower().startswith("application/json"):
         raise HttpError(
             400,
             'The content type of this request must be "application/json"')
     return JSONBody(self.request.json)
Ejemplo n.º 4
0
 def __build_path_value(self, key, val=PathValue()):
     name = val.name if val.name is not None and val.name != "" else key
     if name in self.request.path_values:
         return PathValue(name=name, _value=self.request.path_values[name])
     else:
         raise HttpError(500,
                         "path name[%s] not in your url mapping!" % name)
Ejemplo n.º 5
0
    def _res_(self, path, res_pre, res_dir):
        fpath = os.path.join(res_dir, path.replace(res_pre, ""))
        _logger.debug("static file. %s :: %s" % (path, fpath))
        if not os.path.exists(fpath):
            raise HttpError(404, "")
        fname, fext = os.path.splitext(fpath)
        ext = fext.lower()
        if ext in (".html", ".htm", ".xhtml"):
            content_type = "text/html"
        elif ext == ".xml":
            content_type = "text/xml"
        elif ext == ".css":
            content_type = "text/css"
        elif ext in (".jpg", ".jpeg"):
            content_type = "image/jpeg"
        elif ext == ".png":
            content_type = "image/png"
        elif ext == ".webp":
            content_type = "image/webp"
        elif ext == ".js":
            content_type = "text/javascript"
        elif ext == ".pdf":
            content_type = "application/pdf"
        elif ext == ".mp4":
            content_type = "video/mpeg4"
        elif ext == ".mp3":
            content_type = "audio/mp3"
        else:
            content_type = "application/octet-stream"

        return StaticFile(fpath, content_type)
 def __build_dict(self, key, val={}):
     if key in self.request.parameter.keys():
         try:
             return json.loads(self.request.parameter[key])
         except:
             raise HttpError(400, None, f"Parameter[{key}] should be a JSON string.")
     else:
         return val
Ejemplo n.º 7
0
 def __build_int(self, key, val=0):
     if key in self.request.parameter.keys():
         try:
             return int(self.request.parameter[key])
         except:
             raise HttpError(400, "Parameter[%s] should be an int. " % key)
     else:
         return val
 def __build_int(self, key, val=None):
     if key in self.request.parameter.keys():
         try:
             return int(self.request.parameter[key])
         except:
             raise HttpError(400, None, f"Parameter[{key}] should be an int. ")
     else:
         return val
Ejemplo n.º 9
0
 def __build_reg_group(self, val: RegGroup = RegGroup(group=0)):
     if val.group >= len(self.request.reg_groups):
         raise HttpError(
             400,
             f"RegGroup required an element at {val.group}, but the reg length is only {len(self.request.reg_groups)}"
         )
     return RegGroup(group=val.group,
                     _value=self.request.reg_groups[val.group])
Ejemplo n.º 10
0
    def __get_params_(self, arg, arg_type, val=None, type_check=True):
        if val is not None:
            kws = {"val": val}
        else:
            kws = {}

        if arg_type == Request:
            param = self.request
        elif arg_type == Session:
            param = self.request.get_session(True)
        elif arg_type == Response:
            param = self.response
        elif arg_type == Headers:
            param = Headers(self.request.headers)
        elif arg_type == RegGroups:
            param = RegGroups(self.request.reg_groups)
        elif arg_type == Header:
            param = self.__build_header(arg, **kws)
        elif inspect.isclass(arg_type) and issubclass(arg_type,
                                                      cookies.BaseCookie):
            param = self.request.cookies
        elif arg_type == Cookie:
            param = self.__build_cookie(arg, **kws)
        elif arg_type == MultipartFile:
            param = self.__build_multipart(arg, **kws)
        elif arg_type == Parameter:
            param = self.__build_param(arg, **kws)
        elif arg_type == PathValue:
            param = self.__build_path_value(arg, **kws)
        elif arg_type == Parameters:
            param = self.__build_params(arg, **kws)
        elif arg_type == RegGroup:
            param = self.__build_reg_group(**kws)
        elif arg_type == JSONBody:
            param = self.__build_json_body()
        elif arg_type == str:
            param = self.__build_str(arg, **kws)
        elif arg_type == bool:
            param = self.__build_bool(arg, **kws)
        elif arg_type == int:
            param = self.__build_int(arg, **kws)
        elif arg_type == float:
            param = self.__build_float(arg, **kws)
        elif arg_type in (list, List, List[str], List[Parameter], List[int],
                          List[float], List[bool], List[dict], List[Dict]):
            param = self.__build_list(arg, target_type=arg_type, **kws)
        elif arg_type == ModelDict:
            param = self.__build_model_dict()
        elif arg_type in (dict, Dict):
            param = self.__build_dict(arg, **kws)
        elif type_check:
            raise HttpError(
                400,
                f"Parameter[{arg}] with Type {arg_type} is not supported yet.")
        else:
            param = val
        return param
Ejemplo n.º 11
0
 def __build_params(self, key, val=Parameters()):
     name = val.name if val.name is not None and val.name != "" else key
     if val._required and name not in self.request.parameters:
         raise HttpError(400, "Parameter[%s] is required." % name)
     if name in self.request.parameters:
         v = self.request.parameters[name]
         return Parameters(name=name, default=v, required=val._required)
     else:
         return val
 def __build_param(self, key, val=Parameter()):
     name = val.name if val.name is not None and val.name != "" else key
     if val._required and name not in self.request.parameter:
         raise HttpError(400, "Missing Parameter", f"Parameter[{name}] is required.")
     if name in self.request.parameter:
         v = self.request.parameter[name]
         return Parameter(name=name, default=v, required=val._required)
     else:
         return val
 def __build_header(self, key, val=Header()):
     name = val.name if val.name is not None and val.name != "" else key
     if val._required and name not in self.request.headers:
         raise HttpError(400, "Missing Header", f"Header[{name}] is required.")
     if name in self.request.headers:
         v = self.request.headers[name]
         return Header(name=name, default=v, required=val._required)
     else:
         return val
Ejemplo n.º 14
0
 def __prepare_args(self):
     args = _get_args_(self.__controller)
     arg_vals = []
     for arg in args:
         if arg not in self.request.parameter.keys():
             raise HttpError(400, "Parameter[%s] is required]" % arg)
         param = Parameter(name=arg,
                           default=self.request.parameter[arg],
                           required=True)
         arg_vals.append(param)
     return arg_vals
 def __build_cookie(self, key, val=None):
     name = val.name if val.name is not None and val.name != "" else key
     if val._required and name not in self.request.cookies:
         raise HttpError(400, "Missing Cookie", f"Cookie[{name}] is required.")
     if name in self.request.cookies:
         morsel = self.request.cookies[name]
         cookie = Cookie()
         cookie.set(morsel.key, morsel.value, morsel.coded_value)
         cookie.update(morsel)
         return cookie
     else:
         return val
Ejemplo n.º 16
0
 def __build_param(self, key, val=Parameter()):
     name = val.name if val.name is not None and val.name != "" else key
     if not isinstance(name, unicode):
         """
         " Python 2.7, change str => unicode, or it will fail to reconize the key that is unicode;
         """
         name = name.decode("utf-8")
     if val._required and name not in self.request.parameter:
         raise HttpError(400, "Parameter[%s] is required." % name)
     if name in self.request.parameter:
         v = self.request.parameter[name]
         return Parameter(name=name, default=v, required=val._required)
     else:
         return val
    def __prepare_args(self):
        args = get_function_args(self.__controller.func)
        arg_vals = []
        if len(args) > 0:
            ctr_obj = self.__controller.ctrl_object
            if ctr_obj is not None:
                arg_vals.append(self.__controller.ctrl_object)
                args = args[1:]
        for arg, arg_type_anno in args:
            if arg not in self.request.parameter.keys() \
                    and arg_type_anno not in (Request, Session, Response, RegGroups, RegGroup, Headers, cookies.BaseCookie, cookies.SimpleCookie, Cookies, PathValue, JSONBody, ModelDict):
                raise HttpError(400, "Missing Paramter", f"Parameter[{arg}] is required! ")
            param = self.__get_params_(arg, arg_type_anno)
            arg_vals.append(param)

        return arg_vals
Ejemplo n.º 18
0
def my_ctrl3():
    raise HttpError(400, "Parameter Error!", "Test Parameter Error!")