上下文对象

简介

如果dealer的参数类型继承自Context类,则这个参数就成为了请求级的上下文对象

获取请求级环境信息

例如 GET http://localhost:8080/api/hello/echo?a=1&b=2

env => 包含标准WSGI环境变量的dict
host => localhost:8080
protocol => http
homedomain => http://localhost:8080
homepath => /api
home,realhome => http://localhost:8080/api
ip => 127.0.0.1
method => GET
path => /hello/echo
query => a=1&b=2
fullpath => /hello/echo?a=1&b=2

add_mapping的pattern的匹配对象是path

示例

from lessweb import Application, Context

def info(ctx:Context, msg):
    return {'msg': msg, 'ip': ctx.ip}

app = Application()
app.add_get_mapping('/info', dealer=info)
app.run()

请求: curl "http://localhost:8080/info?msg=lol"
返回: {"msg": "lol", "ip": "127.0.0.1"}

完整API

class Context:
    request: Request
    response: Response
    app: Application
    view: Any
    def __call__(self): ...
    def set_param(self, realname, realvalue) -> None: ...
    def get_param(self, realname, default=None) -> Any: ...
    def set_alias(self, realname, queryname) -> None: ...
    def is_json_request(self) -> bool: ...
    def body_data(self) -> bytes: ...
    def get_input(self, queryname, default=None) -> Jsonizable: ...
    def get_inputs(self) -> Dict[str, Jsonizable]: ...

class Request:
    def contains_cookie(self, name: str) -> bool: ...
    def get_cookie(self, name: str) -> Optional[str]: ...
    def get_cookienames(self) -> List[str]: ...
    def contains_header(self, name: str) -> bool: ...
    def get_header(self, name: str) -> Optional[str]: ...  #根据http规范,多header应该合并入一个key/value,例如requests的headers就是dict。
    def get_headernames(self) -> List[str]: ...

class Response:
    def set_cookie(self, name:str, value:str, expires:int=None, path:str='/',
                   domain:str=None, secure:bool=False, httponly:bool=False) -> None: ...
    def get_cookie(self, name:str)->Optional[Cookie]: ...  # 大小写必须完全一致
    def del_cookie(self, name:str) -> None: ...
    def set_status(self, status: HttpStatus) -> None: ...
    def get_status(self) -> HttpStatus: ...
    def set_header(self, name: str, value: Union[str, int]) -> None: ...
    def get_header(self, name: str) -> Optional[str]: ...  # 大小写必须完全一致
    def del_header(self, name: str) -> None: ...
    def get_headernames(self) -> List[str]: ...
    def clear(self) -> None: ...  # Clear headers and cookies.
    def send_access_allow(self, allow_headers: List[str]=None) -> None: ...
    def send_allow_methods(self, methods: List[str]): ...
    def send_redirect(self, location: str) -> None: ...
    def send_text_html(self, encoding: str): ...