def push(job_id: str, result: Result): resp = None if result.task.task_name == "sim": print(f"posting data to {result.url}/outputs/api/") if result.task.status == "SUCCESS": result.task.outputs = write(job_id, result.task.outputs) resp = httpx.put( f"{result.url}/outputs/api/", json=dict(job_id=job_id, **result.task.dict()), headers=result.headers, ) elif result.task.task_name == "parse": print(f"posting data to {result.url}/inputs/api/") resp = httpx.put( f"{result.url}/inputs/api/", json=dict(job_id=job_id, **result.task.dict()), headers=result.headers, ) elif result.task.task_name == "defaults": print(f"posting data to {result.url}/model-config/api/") resp = httpx.put( f"{result.url}/model-config/api/", json=dict(job_id=job_id, **result.task.dict()), headers=result.headers, ) if resp is not None and resp.status_code == 400: print(resp.text) resp.raise_for_status() elif resp is not None: resp.raise_for_status() else: raise ValueError( f"resp is None for: {job_id} with name {result.task.task_name}" )
def set_bulb_on(self, value): logging.info("Bulb value: %s", value) self.accessory_state = value if value == 1: # On self.set_hue(self.hue) value = True if value == 1 else False httpx.put(f"http://127.0.0.1:8000/things/{self.thing_id}/properties/state", json={"state": value}) self.set_hue(self.hue)
def set_hue(self, value): logging.info("Bulb hue value: %s", value) if self.accessory_state == 1: self.hue = value converter = Converter() rgb_tuple = self.hsv_to_rgb( self.hue, self.saturation, self.brightness) if len(rgb_tuple) == 3: xy = converter.rgb_to_xy(rgb_tuple[0], rgb_tuple[1], rgb_tuple[2]) httpx.put(f"http://127.0.0.1:8000/things/{self.thing_id}/properties/color", json={"color": {"x": xy[0], "y": xy[1]}}) else: self.hue = value
def file_upload(repo: Optional[str], package: Optional[str], version: str, filename: str): username, header = get_auth_header_and_username() if not username: return if not repo: repo = repositories.select_from_available_repo(subject=username) if not package: package = packages_core.select_from_available_packages( subject=username, repo=repo) file_path: str = filename if os.path.isabs(file_path): filename = os.path.basename(file_path) url = get_url(f"/content/{username}/{repo}/{package}/{version}/{filename}") try: with open(file_path, "br") as file: data = file.read() headers = { "x-bintray-publish": "1", "content-type": "application/octet-stream", "x-bintray-override": "1", } headers.update(header) password = typer.prompt("Password", hide_input=True) response = httpx.put( url=url, data=data, headers=headers, auth=httpx.BasicAuth(username=username, password=password), ) response_handler(response=response, return_with_out_model=True) except Exception as e: print_error(f"{e.args[0]}")
def post(self, request): img = request.data.get('img') if not img: return Response({'msg': '内容不能为空!'}, status=status.HTTP_400_BAD_REQUEST) base64_data = base64.b64encode(img.read()) # base64编码 img_str = str(base64_data, 'utf-8') datetime_str = str(datetime.now()) date = datetime_str[:10] time = datetime_str[11:] mime = img.name.split('.')[-1] url = 'https://api.github.com/repos/fduhole/web/contents/{date}/{time}.{mime}'.format( date=date, time=time, mime=mime) headers = {'Authorization': 'token {}'.format(settings.GITHUB_TOKEN)} body = { 'content': img_str, 'message': 'upload image by user {}'.format(request.user.username), 'branch': 'img' } r = httpx.put(url, headers=headers, json=body) if r.status_code == 201: url = 'https://cdn.jsdelivr.net/gh/fduhole/web@img/{date}/{time}.{mime}'.format( date=date, time=time, mime=mime) return Response({'url': url, 'msg': '图片上传成功!'}) else: return Response(r.json(), status=status.HTTP_400_BAD_REQUEST)
async def test_http_methods(client): async with respx.mock: url = "https://foo.bar" route = respx.get(url, path="/") % 404 respx.post(url, path="/").respond(200) respx.post(url, path="/").respond(201) respx.put(url, path="/").respond(202) respx.patch(url, path="/").respond(500) respx.delete(url, path="/").respond(204) respx.head(url, path="/").respond(405) respx.options(url, path="/").respond(status_code=501) respx.request("GET", url, path="/baz/").respond(status_code=204) url += "/" response = httpx.get(url) assert response.status_code == 404 response = await client.get(url) assert response.status_code == 404 response = httpx.get(url + "baz/") assert response.status_code == 204 response = await client.get(url + "baz/") assert response.status_code == 204 response = httpx.post(url) assert response.status_code == 201 response = await client.post(url) assert response.status_code == 201 response = httpx.put(url) assert response.status_code == 202 response = await client.put(url) assert response.status_code == 202 response = httpx.patch(url) assert response.status_code == 500 response = await client.patch(url) assert response.status_code == 500 response = httpx.delete(url) assert response.status_code == 204 response = await client.delete(url) assert response.status_code == 204 response = httpx.head(url) assert response.status_code == 405 response = await client.head(url) assert response.status_code == 405 response = httpx.options(url) assert response.status_code == 501 response = await client.options(url) assert response.status_code == 501 assert route.called is True assert respx.calls.call_count == 8 * 2
async def api_create_mentor(mentor): admin_headers = await api_admin_auth_headers() httpx.post(api_url + '/accounts', headers=admin_headers, json={ 'password': mentor['password'], 'account': { 'role': mentor['role'], 'login_name': mentor['login_name'], 'email': mentor['email'], 'phone': mentor['phone'] } }) mentor_headers = api_auth_header(await api_access_token(mentor['login_name'], mentor['password'])) myuser = httpx.get(api_url + '/myuser', headers=mentor_headers).json() httpx.put(api_url + '/users/' + myuser['user']['id'], headers=mentor_headers, json={ 'display_name': mentor['display_name'], 'birth_year': mentor['birth_year'], 'role': mentor['role'], 'account_id': myuser['account']['id'], 'id': myuser['user']['id'], 'active': True }) httpx.put(api_url + '/mentors/' + myuser['mentor']['id'], headers=admin_headers, json={ 'birth_year': mentor['birth_year'], 'display_name': mentor['display_name'], 'gender': mentor['gender'], 'languages': mentor['languages'], 'region': mentor['region'], 'skills': mentor['skills'], 'story': mentor['story'], 'communication_channels': mentor['communication_channels'], 'account_id': myuser['account']['id'], 'user_id': myuser['user']['id'], 'id': myuser['mentor']['id'] })
def change_password(current_password: str, new_password: str): username, headers = get_auth_header_and_username() if not username: return url = get_url(f"/user/profile/security/change-password") response = httpx.put( url=url, auth=httpx.BasicAuth(username=username, password=current_password), json=UserUpdatePasswordBodyModel(new_password=new_password).dict(), ) response_handler(response=response, return_model=UserUpdatePasswordResponseModel)
def sync_detailed( *, client: Client, json_body: PwdChange, ) -> Response[Union[ApiResponse, None]]: kwargs = _get_kwargs( client=client, json_body=json_body, ) response = httpx.put(**kwargs, ) return _build_response(response=response)
def sync_detailed( *, client: Client, exercise_id: str, ) -> Response[None]: kwargs = _get_kwargs( client=client, exercise_id=exercise_id, ) response = httpx.put(**kwargs, ) return _build_response(response=response)
def sync_detailed( *, client: AuthenticatedClient, name: str, ) -> Response[Union[None, ErrorMessage, ErrorMessage, HTTPValidationError]]: kwargs = _get_kwargs( client=client, name=name, ) response = httpx.put(**kwargs, ) return _build_response(response=response)
def put_rubric( json_body: PutRubricAssignmentData, *, client: "AuthenticatedClient", assignment_id: "int", extra_parameters: Mapping[str, str] = None, ) -> Union[List[RubricRowBaseAsJSON], ]: """Add or update rubric of an assignment.""" url = "{}/api/v1/assignments/{assignmentId}/rubrics/".format( client.base_url, assignmentId=assignment_id) headers: Dict[str, Any] = client.get_headers() params: Dict[str, Any] = { "no_course_in_assignment": "true", "no_role_name": "true", "no_assignment_in_case": "true", "extended": "true", } if extra_parameters: params.update(extra_parameters) json_json_body = maybe_to_dict(json_body) response = httpx.put( url=url, headers=headers, json=json_json_body, params=params, ) if response_code_matches(response.status_code, 200): return [ RubricRowBaseAsJSON.from_dict(item) for item in cast(List[Dict[str, Any]], response.json()) ] if response_code_matches(response.status_code, 400): raise BaseError.from_dict(cast(Dict[str, Any], response.json())) if response_code_matches(response.status_code, 409): raise BaseError.from_dict(cast(Dict[str, Any], response.json())) if response_code_matches(response.status_code, 401): raise BaseError.from_dict(cast(Dict[str, Any], response.json())) if response_code_matches(response.status_code, 403): raise BaseError.from_dict(cast(Dict[str, Any], response.json())) if response_code_matches(response.status_code, "5XX"): raise BaseError.from_dict(cast(Dict[str, Any], response.json())) else: raise ApiResponseError(response=response)
def sync_detailed( *, client: AuthenticatedClient, id: int, json_body: DockerImageBuild, ) -> Response[DockerImageBuild]: kwargs = _get_kwargs( client=client, id=id, json_body=json_body, ) response = httpx.put(**kwargs, ) return _build_response(response=response)
def sync_detailed( *, client: Client, username: str, json_body: Admin, ) -> Response[Union[ApiResponse, None]]: kwargs = _get_kwargs( client=client, username=username, json_body=json_body, ) response = httpx.put(**kwargs, ) return _build_response(response=response)
def sync_detailed( *, client: Client, json_body: User, mode: Union[Unset, QuotaUpdateMode] = UNSET, ) -> Response[Union[ApiResponse, None]]: kwargs = _get_kwargs( client=client, json_body=json_body, mode=mode, ) response = httpx.put(**kwargs, ) return _build_response(response=response)
def sync_detailed( *, client: AuthenticatedClient, id: int, json_body: Pipeline, ) -> Response[Pipeline]: kwargs = _get_kwargs( client=client, id=id, json_body=json_body, ) response = httpx.put(**kwargs, ) return _build_response(response=response)
def sync_detailed( *, client: AuthenticatedClient, id: int, json_body: ECSServiceDeploy, ) -> Response[ECSServiceDeploy]: kwargs = _get_kwargs( client=client, id=id, json_body=json_body, ) response = httpx.put(**kwargs, ) return _build_response(response=response)
def sync_detailed( *, client: Client, id: str, json_body: RenderedRiff, ) -> Response[None]: kwargs = _get_kwargs( client=client, id=id, json_body=json_body, ) response = httpx.put(**kwargs, ) return _build_response(response=response)
def new_record(name, content, msgs, record_type='A'): data = {'type': record_type, 'name': name, 'content': content} if msgs and not multi: option = int(input("choose the option: ")) if len(msgs) > 1 else 0 msg = msgs[option] old_msg = eval(req_msg) msg = httpx.put(f'{base_url}/{msg["id"]}', headers=headers, json=data).json()['result'] print('Changed to') logger.info(f"CHANGED | {old_msg} -> {eval(req_msg)}") else: msg = httpx.post(base_url, headers=headers, json=data).json()['result'] logger.info(f"NEW | {eval(req_msg)}") print('New record:') print(eval(req_msg))
async def test_http_methods(client): async with respx.HTTPXMock() as httpx_mock: url = "https://foo.bar/" m = httpx_mock.get(url, status_code=404) httpx_mock.post(url, status_code=201) httpx_mock.put(url, status_code=202) httpx_mock.patch(url, status_code=500) httpx_mock.delete(url, status_code=204) httpx_mock.head(url, status_code=405) httpx_mock.options(url, status_code=501) response = httpx.get(url) assert response.status_code == 404 response = await client.get(url) assert response.status_code == 404 response = httpx.post(url) assert response.status_code == 201 response = await client.post(url) assert response.status_code == 201 response = httpx.put(url) assert response.status_code == 202 response = await client.put(url) assert response.status_code == 202 response = httpx.patch(url) assert response.status_code == 500 response = await client.patch(url) assert response.status_code == 500 response = httpx.delete(url) assert response.status_code == 204 response = await client.delete(url) assert response.status_code == 204 response = httpx.head(url) assert response.status_code == 405 response = await client.head(url) assert response.status_code == 405 response = httpx.options(url) assert response.status_code == 501 response = await client.options(url) assert response.status_code == 501 assert m.called is True assert httpx_mock.stats.call_count == 7 * 2
def put(self, data: typing.Any = None, endpoint: str = "") -> httpx.Response: r = httpx.put( url=f"{self.url}{endpoint}", auth=self.auth, data=data, headers={"content-type": "application/json"}, timeout=self.timeout, ) if self.debug: print(f"PUT {r.url}") print(json.dumps(r.json(), indent=4, sort_keys=True)) if r.is_error: r.raise_for_status() return r
def BanUser(UserID: str) -> bool: try: r = httpx.put( 'https://discord.com/api/{}/guilds/{}/bans/{}'.format(api, guild, UserID), proxies=getProxyDict(), headers=headers ) if r.status_code in [200, 201, 204]: util.log('[!]', 'Banned {}{}'.format(Fore.LIGHTCYAN_EX, UserID)) elif r.status_code == 429: util.log('[!]', 'Ratelimited for {}{}'.format(Fore.LIGHTCYAN_EX, r.json()['retry_after'])) NukeFunctions.BanUser(UserID) return(True) except Exception as e: print(e) return(NukeFunctions.BanUser(UserID))
def put_enroll_link( json_body: PutEnrollLinkCourseData, *, client: "AuthenticatedClient", course_id: "int", extra_parameters: Mapping[str, str] = None, ) -> Union[CourseRegistrationLinkAsJSON, ]: """Create or edit an enroll link.""" url = "{}/api/v1/courses/{courseId}/registration_links/".format( client.base_url, courseId=course_id) headers: Dict[str, Any] = client.get_headers() params: Dict[str, Any] = { "no_course_in_assignment": "true", "no_role_name": "true", "no_assignment_in_case": "true", "extended": "true", } if extra_parameters: params.update(extra_parameters) json_json_body = maybe_to_dict(json_body) response = httpx.put( url=url, headers=headers, json=json_json_body, params=params, ) if response_code_matches(response.status_code, 200): return CourseRegistrationLinkAsJSON.from_dict( cast(Dict[str, Any], response.json())) if response_code_matches(response.status_code, 400): raise BaseError.from_dict(cast(Dict[str, Any], response.json())) if response_code_matches(response.status_code, 409): raise BaseError.from_dict(cast(Dict[str, Any], response.json())) if response_code_matches(response.status_code, 401): raise BaseError.from_dict(cast(Dict[str, Any], response.json())) if response_code_matches(response.status_code, 403): raise BaseError.from_dict(cast(Dict[str, Any], response.json())) if response_code_matches(response.status_code, "5XX"): raise BaseError.from_dict(cast(Dict[str, Any], response.json())) else: raise ApiResponseError(response=response)
def sync_detailed( *, client: Client, username: str, json_body: User, disconnect: Union[Unset, UpdateUserDisconnect] = UNSET, ) -> Response[Union[ApiResponse, None]]: kwargs = _get_kwargs( client=client, username=username, json_body=json_body, disconnect=disconnect, ) response = httpx.put(**kwargs, ) return _build_response(response=response)
def sync_detailed( *, client: Client, id: str, json_body: Tag, x_fields: Union[Unset, str] = UNSET, ) -> Response[Tag]: kwargs = _get_kwargs( client=client, id=id, json_body=json_body, x_fields=x_fields, ) response = httpx.put(**kwargs, ) return _build_response(response=response)
def retrieve_connector_class_protected_keys(connector_class: str, config: dict) -> None: response = httpx.put( f"{url}/connector-plugins/{connector_class}/config/validate", json=config, ) if response.is_error: logger.warning( 'Couldn\'t retrieve connector class validation for "{}": {}', connector_class, response, ) return data = response.json() protected_keys[connector_class] = { config["value"]["name"] for config in data["configs"] if config["definition"]["type"] == "PASSWORD" }
def edit_product(self, product: ProductEdit) -> Optional[Product]: """ Edit an existent product. Args: - product: the parameters for edit a product. Raises: ProductNotFound: when no product was found for the uuid provided. CodeAlreadyRegistered: when the code used to register the product is already in use by another persisted product. UnknownNetworkError: when any unknown network error happens. Returns: - the API response for an edit operation. """ self._check_authentication() response = put( f"{self.endpoint}/products/{product.uuid}", json={"code": product.code, "summary": product.summary}, headers={"Authorization": f"Bearer {self.get_access_token()}"}, ) if response.status_code == 404: raise ProductNotFound( f"Product with uuid {product.uuid} not found." ) if response.status_code == 409: raise CodeAlreadyRegistered( f"{product.code} is already in use by another product." ) if response.status_code != 200: raise UnknownNetworkError( f"Failed to edit a product, network error: " f"(status: {response.status_code} - data: {response.content})." ) return Product(**response.json())
def restart_rasa_server_with_new_model(self, model_path, local_model_path): success = None data = dict( model_file=local_model_path ) url = f"{self.config_handler.get_rasa_server_url()}/model" try: r = httpx.put(url, data=json.dumps(data)).status_code if r == 204: logger.info(f"Successfully restarted rasa server") self.message_handler.set_key(self.config_handler.get_server_identifier(), model_path, message_type='str') self.message_handler.set_key(self.config_handler.get_rasa_model_minio_key(), model_path, message_type='str') self.message_handler.set_key(self.config_handler.get_rasa_model_key(), local_model_path, message_type='str') success = True else: logger.info(f"Restarting was not successfull. Ended with status code: {r.status_code}") except (httpx.ConnectError, httpx.ConnectTimeout) as e: logger.info(f"Couldnt reach rasa server url {url} with new model stored under: {local_model_path}") logger.info(str(e)) finally: return success
async def api_create_mentee_account(mentee): httpx.post(api_url + '/accounts', json={ 'password': mentee['password'], 'account': { 'role': mentee['role'], 'login_name': mentee['login_name'], 'email': mentee['email'] } }) access_token = await api_access_token(mentee['login_name'], mentee['password']) auth_header = api_auth_header(access_token) r = httpx.get(api_url + '/myuser', headers=auth_header) my_user = r.json() r = httpx.put(api_url + '/users/' + my_user['user']['id'], headers=auth_header, json={ 'display_name': mentee['display_name'], 'role': mentee['role'], 'account_id': my_user['account']['id'], 'id': my_user['user']['id'] })
#!/usr/bin/env python # -*- encoding: utf-8 -*- ''' @File : 1_request_method.py @Time : 2021-02-23 @Author : EvilRecluse @Contact : https://github.com/RecluseXU @Desc : 常用的请求方法GET, POST, PUT, DELETE, HEAD, OPTIONS ''' # here put the import lib import httpx # 常用的请求方法GET, POST, PUT, DELETE, HEAD, OPTIONS r = httpx.get('https://httpbin.org/get') r = httpx.post('https://httpbin.org/post', data={'key': 'value'}) r = httpx.put('https://httpbin.org/put', data={'key': 'value'}) r = httpx.delete('https://httpbin.org/delete') r = httpx.head('https://httpbin.org/get') r = httpx.options('https://httpbin.org/get') # 设置headers headers = {'user-agent': 'my-app/0.0.1'} r = httpx.get('http://httpbin.org/headers', headers=headers) print(r.json())