async def normalize_context_params(is_sync: bool, params: Dict) -> None: params["sdkLanguage"] = "python" if is_sync else "python-async" if params.get("noViewport"): del params["noViewport"] params["noDefaultViewport"] = True if "defaultBrowserType" in params: del params["defaultBrowserType"] if "extraHTTPHeaders" in params: params["extraHTTPHeaders"] = serialize_headers(params["extraHTTPHeaders"]) if "recordHarPath" in params: params["recordHar"] = {"path": str(params["recordHarPath"])} if "recordHarOmitContent" in params: params["recordHar"]["omitContent"] = True del params["recordHarOmitContent"] del params["recordHarPath"] if "recordVideoDir" in params: params["recordVideo"] = {"dir": str(params["recordVideoDir"])} if "recordVideoSize" in params: params["recordVideo"]["size"] = params["recordVideoSize"] del params["recordVideoSize"] del params["recordVideoDir"] if "storageState" in params: storageState = params["storageState"] if not isinstance(storageState, dict): params["storageState"] = json.loads( (await async_readfile(storageState)).decode() )
async def new_context( self, baseURL: str = None, extraHTTPHeaders: Dict[str, str] = None, httpCredentials: HttpCredentials = None, ignoreHTTPSErrors: bool = None, proxy: ProxySettings = None, userAgent: str = None, timeout: float = None, storageState: Union[StorageState, str, Path] = None, ) -> "APIRequestContext": params = locals_to_params(locals()) if "storageState" in params: storage_state = params["storageState"] if not isinstance(storage_state, dict) and storage_state: params["storageState"] = json.loads( (await async_readfile(storage_state)).decode()) if "extraHTTPHeaders" in params: params["extraHTTPHeaders"] = serialize_headers( params["extraHTTPHeaders"]) context = cast( APIRequestContext, from_channel(await self.playwright._channel.send("newRequest", params)), ) return context
def normalize_context_params(params: Dict) -> None: if "viewport" in params and params["viewport"] == 0: del params["viewport"] params["noDefaultViewport"] = True if "defaultBrowserType" in params: del params["defaultBrowserType"] if "extraHTTPHeaders" in params: params["extraHTTPHeaders"] = serialize_headers( params["extraHTTPHeaders"]) if "recordHarPath" in params: params["recordHar"] = {"path": str(params["recordHarPath"])} if "recordHarOmitContent" in params: params["recordHar"]["omitContent"] = True del params["recordHarOmitContent"] del params["recordHarPath"] if "recordVideoDir" in params: params["recordVideo"] = {"dir": str(params["recordVideoDir"])} if "recordVideoSize" in params: params["recordVideo"]["size"] = { "width": params["recordVideoSize"][0], "height": params["recordVideoSize"][1], } del params["recordVideoSize"] del params["recordVideoDir"] if "storageState" in params: storageState = params["storageState"] if not isinstance(storageState, dict): with open(storageState, "r") as f: params["storageState"] = json.load(f)
async def normalize_context_params(is_sync: bool, params: Dict) -> None: if params.get("noViewport"): del params["noViewport"] params["noDefaultViewport"] = True if "defaultBrowserType" in params: del params["defaultBrowserType"] if "extraHTTPHeaders" in params: params["extraHTTPHeaders"] = serialize_headers( params["extraHTTPHeaders"]) if "recordHarPath" in params: params["recordHar"] = prepare_record_har_options(params) del params["recordHarPath"] if "recordVideoDir" in params: params["recordVideo"] = {"dir": str(params["recordVideoDir"])} if "recordVideoSize" in params: params["recordVideo"]["size"] = params["recordVideoSize"] del params["recordVideoSize"] del params["recordVideoDir"] if "storageState" in params: storageState = params["storageState"] if not isinstance(storageState, dict): params["storageState"] = json.loads( (await async_readfile(storageState)).decode())
async def set_extra_http_headers(self, headers: Dict[str, str]) -> None: await self._channel.send("setExtraHTTPHeaders", dict(headers=serialize_headers(headers)))
async def fetch( self, urlOrRequest: Union[str, network.Request], params: Dict[str, Union[bool, float, str]] = None, method: str = None, headers: Headers = None, data: Union[Any, bytes, str] = None, form: Dict[str, Union[bool, float, str]] = None, multipart: Dict[str, Union[bytes, bool, float, str, FilePayload]] = None, timeout: float = None, failOnStatusCode: bool = None, ignoreHTTPSErrors: bool = None, ) -> "APIResponse": request = urlOrRequest if isinstance(urlOrRequest, network.Request) else None assert request or isinstance( urlOrRequest, str), "First argument must be either URL string or Request" assert ( (1 if data else 0) + (1 if form else 0) + (1 if multipart else 0) ) <= 1, "Only one of 'data', 'form' or 'multipart' can be specified" url = request.url if request else urlOrRequest method = method or (request.method if request else "GET") # Cannot call allHeaders() here as the request may be paused inside route handler. headers_obj = headers or (request.headers if request else None) serialized_headers = serialize_headers( headers_obj) if headers_obj else None json_data = None form_data: Optional[List[NameValue]] = None multipart_data: Optional[List[FormField]] = None post_data_buffer: Optional[bytes] = None if data: if isinstance(data, str): post_data_buffer = data.encode() elif isinstance(data, bytes): post_data_buffer = data elif isinstance(data, (dict, list)): json_data = data else: raise Error(f"Unsupported 'data' type: {type(data)}") elif form: form_data = object_to_array(form) elif multipart: multipart_data = [] # Convert file-like values to ServerFilePayload structs. for name, value in multipart.items(): if is_file_payload(value): payload = cast(FilePayload, value) assert isinstance( payload["buffer"], bytes), f"Unexpected buffer type of 'data.{name}'" multipart_data.append( FormField(name=name, file=file_payload_to_json(payload))) elif isinstance(value, str): multipart_data.append(FormField(name=name, value=value)) if (post_data_buffer is None and json_data is None and form_data is None and multipart_data is None): post_data_buffer = request.post_data_buffer if request else None post_data = (base64.b64encode(post_data_buffer).decode() if post_data_buffer else None) def filter_none(input: Dict) -> Dict: return {k: v for k, v in input.items() if v is not None} result = await self._channel.send_return_as_dict( "fetch", filter_none({ "url": url, "params": object_to_array(params), "method": method, "headers": serialized_headers, "postData": post_data, "jsonData": json_data, "formData": form_data, "multipartData": multipart_data, "timeout": timeout, "failOnStatusCode": failOnStatusCode, "ignoreHTTPSErrors": ignoreHTTPSErrors, }), ) if result.get("error"): raise Error(result["error"]) return APIResponse(self, result["response"])