上下文对象

简介

获取请求级环境信息

例如 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:str):
    return {'msg': msg, 'ip': ctx.request.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:
    app: Application
    request: Request
    response: Response
    box: Dict
    def __init__(self, app: 'Application') -> None: ...
    def __call__(self) -> Any: ...


class Request:
    environ: Dict
    env: Dict
    host: str
    protocol: str
    homedomain: str
    homepath: str
    home: str
    ip: str
    method: str
    path: str
    query: str
    fullpath: str
    body_data: Optional[bytes]
    def __init__(self, encoding: str) -> None: ...
    def load(self, env) -> None: ...
    def set_alias(self, realname, queryname) -> None: ...
    def get_content_type(self) -> str: ...
    def is_json(self) -> bool: ...
    def is_form(self) -> bool: ...
    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]: ...
    def get_auth_bearer(self) -> Optional[str]: ...
    def get_input(self, key: str) -> Optional[Union[ParamStr, Jsonizable]]: ...
    def get_uploaded_files(self, key: str) -> List[MultipartFile]: ...


class Response:
    def __init__(self, encoding: str) -> None: ...
    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: Union[HttpStatus, ResponseStatus]) -> None: ...
    def get_status(self) -> Union[HttpStatus, ResponseStatus]: ...
    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) -> str: ...
    def get_headernames(self) -> List[str]: ...
    def clear(self) -> None: ...
    def send_access_allow(self, allow_headers: List[str]=None) -> None: ...
    def send_allow_methods(self, methods: List[str]) -> None: ...
    def send_redirect(self, location: str) -> None: ...
    def send_content_type(self, mimekey='html', encoding: str='') -> None: ...