def get(self, request):
        """
        List all assets.

         route /assets
         return List all assets available for tenant.
         description This method internally calls method list_assets of AssetsClient class.
                        This class is available as dependency in assetmanagement-<version-here>-py3-none-any.whl

         apiEndpoint : GET /api/assetmanagement/v3/assets of asset management service.

         apiNote List all assets available for the authenticated user.
         throws MindsphereError if an error occurs while attempting to invoke the sdk call.

        """
        logger.info("assets/assets invoked.")
        client = sdk_util.build_sdk_client(self.__class__.__name__, request)
        if request.method == "GET":
            try:
                request_object = data_generator.generate_list_assets_input()
                asset = client.list_assets(request_object)
                logger.info("Getting response successfully for  getallasset" + json.dumps(asset.to_dict()))
            except exceptions.MindsphereError as err:
                logger.error("Getting eeror for getallasset " + err)
                return HttpResponse(
                    err,
                    content_type="application/json",
                    status=status.HTTP_500_INTERNAL_SERVER_ERROR,
                )
            return HttpResponse(
                json.dumps(asset.to_dict()), content_type="application/json", status=status.HTTP_200_OK
            )
    def get(self, request, **kwargs):
        """

         route <str:id>/aspects
         return List of all aspects for provided asset id.
         param id : Unique identifier of an asset. (passed in keyword arguments.)
         description This method internally calls method list_asset_aspects of StructureClient class.
                     This class is available as dependency in assetmanagement-<version-here>-py3-none-any.whl

         apiEndpoint : GET /api/assetmanagement/v3/assets/{id}/aspects of asset management service.

         apiNote Get all static and dynamic aspects of a given asset.
         throws Error if an error occurs while attempting to invoke the sdk call.

        """
        logger.info("assets/<str:id>/aspects invoked.")
        client = sdk_util.build_sdk_client(self.__class__.__name__, request)
        if request.method == "GET":
            try:
                request_object = GetRootAssetRequest(if_none_match=None)
                asset = client.get_root_asset(request_object)
                asset = serialization_filter.sanitize_for_serialization(asset)
                resonse = json.dumps(asset)
                logger.info(resonse)
            except exceptions.MindsphereError as err:
                logger.error(err)
                return HttpResponse(
                    err,
                    content_type="application/json",
                    status=status.HTTP_500_INTERNAL_SERVER_ERROR,
                )
            return HttpResponse(
                resonse, content_type="application/json", status=status.HTTP_200_OK
            )
    def get(self, request, **kwargs):
        """
        filtering asset which of given filter_value type.

         route filterassetsoftype
         return List all assets available for tenant with provided filter.

         param filter_value - specify the value  to look for while filtering assets.
         description This method internally calls method get_assets_starts_with of AssetsClient class.
                     Assets which are of provided type (filter_value)  will be returned.
                     This class is available as dependency in assetmanagement-<version-here>-py3-none-any.whl

         apiEndpoint : GET /api/assetmanagement/v3/assets of asset management service.

         apiNote List all assets available for the authenticated user.
         throws MindsphereError if an error occurs while attempting to invoke the sdk call.
        """
        logger.info("assets/filterassetsoftype invoked.")
        client = sdk_util.build_sdk_client(self.__class__.__name__, request)
        if request.method == "GET":
            try:
                response = client.get_assets_of_type(request.GET.get("filterValue", None))
                logger.info("Getting response successfully for filterassetsoftype" + json.dumps(response.to_dict))
            except exceptions.MindsphereError as err:
                logger.error("Getting error for filterassetsoftype " + err)
                return HttpResponse(
                    err,
                    content_type="application/json",
                    status=status.HTTP_500_INTERNAL_SERVER_ERROR,
                )
            return HttpResponse(
                json.dumps(response.to_dict), content_type="application/json", status=status.HTTP_200_OK
            )
Ejemplo n.º 4
0
 def remove_track(self, inactive_id):
     try:
         del self.face_tracks[inactive_id]
         self.n_active_tracks -= 1
     except KeyError:
         logger.error("track id {} does not exist in current track".format(
             inactive_id))
    def get(self, request, **kwargs):
        """
        filter asset types which contains

        route filterassettypecontains
        return List all asset types available for tenant with provided filter(asset types whose name contains provided
               filterValue).

        param filterValue - specify the value for fieldType(name) to look for while filtering asset types..
        description This method internally calls method get_asset_types_contains of AssettypeClient
                     class. This class is available as dependency in assetmanagement-<version-here>-py3-none-any.whl.
        apiEndpoint : GET /api/assetmanagement/v3/assettypes of asset management service.

        apiNote List all asset types.
        throws MindsphereError if an error occurs while attempting to invoke the sdk call.
        """
        logger.info("assets/filterassettypecontains invoked.")
        client = sdk_util.build_sdk_client(self.__class__.__name__, request)
        if request.method == "GET":
            try:
                response = client.get_asset_types_contains(field_type=data_generator.FieldTypeEnum.NAME,
                                                           filter_value=request.GET.get("filterValue", None))
                logger.info(
                    "Getting response successfully for create filterassettypecontains " + json.dumps(response.to_dict))
            except exceptions.MindsphereError as err:
                logger.error("Getting error for create filterassettypecontains " + err)
                return HttpResponse(
                    err,
                    content_type="application/json",
                    status=status.HTTP_500_INTERNAL_SERVER_ERROR,
                )
            return HttpResponse(
                json.dumps(response.to_dict), content_type="application/json", status=status.HTTP_200_OK
            )
    def get(self, request, **kwargs):
        """
         Create aspect type.

         route assets/aspects
         param tenantName - Name of the tenant for which you want to create aspect type. Passed in request.
         return Created aspect type information object.
         description This method internally calls method save_aspect_type of AspecttypeClient class.
                        This class is available as dependency in assetmanagement-<version-here>-py3-none-any.whl

         apiEndpoint : PUT /api/assetmanagement/v3/aspecttypes/{id} of asset management service.

         apiNote Create or Update an aspect type
         throws MindsphereError if an error occurs while attempting to invoke the sdk call.

        """
        logger.info("assets/aspects invoked.")
        client = sdk_util.build_sdk_client(self.__class__.__name__, request)
        if request.method == "GET":
            try:
                request_object = data_generator.generate_aspect_input(
                    tenant=request.GET.get("tenantName", None)
                )
                aspect = client.save_aspect_type(request_object)
                logger.info("Getting response successfully for create aspects " + json.dumps(aspect.to_dict))
            except exceptions.MindsphereError as err:
                logger.error("Getting error for create aspects " + err)
                return HttpResponse(
                    err,
                    content_type="application/json",
                    status=status.HTTP_500_INTERNAL_SERVER_ERROR,
                )
            return HttpResponse(
                json.dumps(aspect.to_dict), content_type="application/json", status=status.HTTP_200_OK
            )
Ejemplo n.º 7
0
async def send_message(
    chat_id: int,
    text: str,
    parse_mode: typing.Union[str, None] = None,
    disable_web_page_preview: typing.Union[bool, None] = None,
    disable_notification: typing.Union[bool, None] = None,
    reply_to_message_id: typing.Union[int, None] = None,
    reply_markup: typing.Union[InlineKeyboardMarkup, ReplyKeyboardMarkup,
                               ReplyKeyboardRemove, ForceReply, None] = None
) -> typing.Union[Message, None]:
    try:
        res = await bot.send_message(chat_id, text, parse_mode,
                                     disable_web_page_preview,
                                     disable_notification, reply_to_message_id)

        if reply_markup and res:
            await bot.edit_message_reply_markup(chat_id,
                                                res.message_id,
                                                reply_markup=reply_markup)

    except (BotKicked, BotBlocked, ChatNotFound):
        await User.all().filter(chat_id=chat_id).delete()

    except Exception as err:
        logger.error(f'Error on send message: {err}',
                     exc_info=True,
                     stack_info=True)
    else:
        return res
Ejemplo n.º 8
0
async def delete_message(chat_id: int, message_id: int):
    try:
        await bot.delete_message(chat_id, message_id)
    except Exception as err:
        logger.error(f'Error on delete message: {err}',
                     exc_info=True,
                     stack_info=True)
Ejemplo n.º 9
0
async def edit_message_text(
        text: str,
        chat_id: typing.Union[int, str, None] = None,
        message_id: typing.Union[int, None] = None,
        inline_message_id: typing.Union[str, None] = None,
        parse_mode: typing.Union[str, None] = None,
        disable_web_page_preview: typing.Union[str, None] = None,
        reply_markup: typing.Union[InlineKeyboardMarkup, None] = None) -> bool:
    try:
        res = await bot.edit_message_text(text, chat_id, message_id,
                                          inline_message_id, parse_mode,
                                          disable_web_page_preview,
                                          reply_markup)

        if reply_markup and res:
            await bot.edit_message_reply_markup(chat_id,
                                                res.message_id,
                                                reply_markup=reply_markup)

    except MessageNotModified:
        pass

    except (BotKicked, BotBlocked, ChatNotFound):
        await User.all().filter(chat_id=chat_id).delete()

    except Exception as err:
        logger.error(f'Error on edit_message_text: {err}',
                     exc_info=True,
                     stack_info=True)
        return False

    else:
        return res
def build_sdk_client(class_name, request):

    if TOKEN_CIRCULAR_GROUP[TOKEN_SELECTOR] == TOKEN_CIRCULAR_GROUP[1]:
        if request.META.get('HTTP_AUTHORIZATION') is None:
            logger.error(
                'To work with technical token,'
                ' application should receieve authorization header.',
                request.get_full_path())
            raise exceptions.MindsphereError(
                'To work with technical token,'
                ' application should receieve authorization header.',
                request.get_full_path())
        else:
            credentials = UserToken(
                authorization=str(request.META.get('HTTP_AUTHORIZATION'))[7::])
            logger.info('Using User Token for ' + request.get_full_path())
    elif TOKEN_CIRCULAR_GROUP[TOKEN_SELECTOR] == TOKEN_CIRCULAR_GROUP[0]:
        credentials = AppCredentials()
    else:
        logger.error('Unpredicted use case, used token type not available',
                     request.get_full_path())
        raise exceptions.MindsphereError(
            'Unpredicted use case, used token type not available',
            request.get_full_path())
    if _is_locally_hosted(request):
        config = RestClientConfig()
    else:
        config = RestClientConfig()
    class_name = class_name[0:class_name.rindex('View')]
    klass = globals()[class_name]
    instance = klass(config, credentials)
    return instance
Ejemplo n.º 11
0
 def get(self, request):
     """
     List all assets.
     """
     if sdk_util.TOKEN_CIRCULAR_GROUP[sdk_util.TOKEN_SELECTOR] == sdk_util.TOKEN_CIRCULAR_GROUP[0] \
             and request.META.get('HTTP_AUTHORIZATION') is not None:
         token_type = "User Token"
         credentials = UserToken(
             authorization=request.META.get('HTTP_AUTHORIZATION'))
     elif sdk_util.TOKEN_CIRCULAR_GROUP[
             sdk_util.TOKEN_SELECTOR] == sdk_util.TOKEN_CIRCULAR_GROUP[1]:
         token_type = "App Creds"
         credentials = AppCredentials()
     else:
         logger.error('To work with technical token,'
                      ' application should receieve authorization header.')
         raise exceptions.MindsphereError(
             'To work with technical token,'
             ' application should receieve authorization header.')
     if sdk_util._is_locally_hosted(request):
         config = RestClientConfig(PROXY_HOST, PROXY_PORT)
     else:
         config = RestClientConfig()
     try:
         token = token_service.fetch_token(config, credentials)
         payload = commonutil._decode_jwt(token)
         # payload = jwt.decode(token, "secret", verify=False, algorithms=["RS256"])
     except Exception as e:
         return HttpResponse(token_type + "::" + str(e),
                             content_type='application/json',
                             status=status.HTTP_500_INTERNAL_SERVER_ERROR)
     return HttpResponse("Decoded " + token_type + "::" + "\n" +
                         str(payload),
                         content_type='application/json',
                         status=status.HTTP_200_OK)
    def get(self, request, **kwargs):
        """

         route <str:id>/aspects
         return List of all aspects for provided asset id.
         param id : Unique identifier of an asset. (passed in keyword arguments.)
         description This method internally calls method list_asset_aspects of StructureClient class.
                     This class is available as dependency in assetmanagement-<version-here>-py3-none-any.whl

         apiEndpoint : GET /api/assetmanagement/v3/assets/{id}/aspects of asset management service.

         apiNote Get all static and dynamic aspects of a given asset.
         throws Error if an error occurs while attempting to invoke the sdk call.

        """
        logger.info("assets/<str:id>/aspects invoked.")
        client = sdk_util.build_sdk_client(self.__class__.__name__, request)
        if request.method == "GET":
            try:
                did = kwargs.get("id", "")
                logger.info("AssetId is " + did)
                request_object = data_generator.generate_aspects_of_asset_request(id=did)
                aspects_of_asset = client.list_asset_aspects(request_object)
                logger.info(
                    "Getting response successfully for  list of aspects with id" + json.dumps(aspects_of_asset.to_dict))
            except exceptions.MindsphereError as err:
                logger.error("Getting error for listofaspect with assetId " + err)
                return HttpResponse(
                    err,
                    content_type="application/json",
                    status=status.HTTP_500_INTERNAL_SERVER_ERROR,
                )
            return HttpResponse(
                json.dumps(aspects_of_asset.to_dict), content_type="application/json", status=status.HTTP_200_OK
            )
Ejemplo n.º 13
0
    def orf_prodigal_train(self):
        """Runs PRODIGAL to find open reading frames using a training file from complete genomes references."""
        training_file = os.path.join(self.training_file)

        if os.path.exists(training_file):
            quality = " -t {} ".format(training_file)
            filename = os.path.basename(self.input_file)
            stdout = "2> /dev/null"
            cmd = "prodigal -q -m -a {trans_file} -i {input_file} -o  {output_file} -d {nuc_file} -s {potential_genes} {quality} {stdout}" \
               .format(
              trans_file=os.path.join(self.working_directory, "{}.temp.contig.fsa".format(filename)),
              input_file=self.input_file,
              output_file=os.path.join(self.working_directory, "{}.temp.draft".format(filename)),
              quality=quality,
              stdout=stdout,
              nuc_file= os.path.join(self.working_directory,  "{}.temp.contigToORF.fsa".format(filename)),
              potential_genes= os.path.join(self.working_directory,  "{}.temp.potentialGenes".format(filename))
             )
            # logger.debug(cmd)
            os.system(cmd)

            if self.clean == True:
                os.remove(
                    os.path.join(self.working_directory,
                                 "{}.temp.draft".format(filename)))
        else:
            logger.error("Missing training file: {} ".format(training_file))
            exit()
def service_name(url=None):
    try:
        parts = url.split('/')
        if 'responses' in parts:
            return 'SDX_STORE'
        elif 'sequence' in parts:
            return 'SDX_SEQUENCE'
    except AttributeError as e:
        logger.error(e)
    def get(self, request, **kwargs):
        """

         route iotbulk/retrievetimeseries/<str:entityid>/<str:propertyname>/<str:from>/<str:to>
         param entityId - Unique identifier of the asset (entity).
         param propertyname - Unique name of the aspect (property set name).
         param from - Beginning of the time range to read (exclusive). ‘from’ time must be less than ‘to’ time.
                      Range between ‘from’ and ‘to’ time must be less than 90 days.
         param to -   End of the time range to retrieve (inclusive).

         return Retrieve time series data for a single asset (entity) and aspect (property set).
                Returns data for the specified time range.

         description :  This method internally calls method retrieve_timeseries of ReadOperationsClient class.
                            This class is available as dependency in iottsbulk-<version-here>-py3-none-any.whl.

          apiEndpoint : GET /api/iottsbulk/v3/timeseries/{entity}/{propertySetName} of iot bulk service.
                      service.
         apiNote Retrieve time series data.
         throws MindsphereError if an error occurs while attempting to invoke the sdk call.


        """
        logger.info("iotbulk/retrievetimeseries/<str:entityid>/<str:propertyname>/<str:from>/<str:to> invoked")
        client = sdk_util.build_sdk_client(self.__class__.__name__, request)
        if request.method == "GET":
            try:
                entity_id = kwargs.get("entityid", "")
                property_name = kwargs.get("propertyname", "")
                _from = kwargs.get("from", "")
                to = kwargs.get("to", "")
                logger.info(
                    "Request params are- enitityID:" + entity_id + " propertyName: " + property_name + " from:" + _from + " to:" + to)
                retrieveTimeseriesRequest = RetrieveTimeseriesRequest()
                retrieveTimeseriesRequest.entity = entity_id
                retrieveTimeseriesRequest.property_set_name = property_name
                retrieveTimeseriesRequest._from = _from
                retrieveTimeseriesRequest.to = to
                response = client.retrieve_timeseries(retrieveTimeseriesRequest)
                logger.info("Getting response successfully for retrievetimeseries "+response)
            except exceptions.MindsphereError as err:
                logger.error("getting error for retrievetimeseries " + err)
                return HttpResponse(
                    err,
                    content_type="application/json",
                    status=status.HTTP_500_INTERNAL_SERVER_ERROR,
                )
            return HttpResponse(
                json.dumps(response.to_dict()), content_type="application/json", status=status.HTTP_200_OK
            )
    def get(self, request):
        """

        route iotbulk/importjobpost

        return Created import job object(JobStatus) information.

        description This method internally calls method create_import_job of BulkImportOperationsClient class.
                    This class is available as dependency in iottsbulk-<version-here>-py3-none-any.whl.

        apiEndpoint : POST /api/iottsbulk/v3/importJobs of iot bulk service.
                       service.
        apiNote Create bulk import job for importing time series data.
        throws MindsphereError if an error occurs while attempting to invoke the sdk call.

        """
        logger.info("iotbulk/importjobpost invoked.")
        client = sdk_util.build_sdk_client(self.__class__.__name__, request)
        if request.method == "GET":
            try:
                createImportJobRequest = CreateImportJobRequest()
                bulkImportInput = BulkImportInput()
                data = Data()
                data.entity = "5908ae5c5e4f4e18b0be58cd21ee675f"
                data.property_set_name = "test_2020_11_11"

                fileInfo = FileInfo()
                fileInfo.file_path = "test11.json"
                fileInfo._from = "2020-12-16T04:30:00.01Z"
                fileInfo.to = "2020-12-16T04:35:00.30Z"
                fileInfoList = [fileInfo]

                data.timeseries_files = fileInfoList
                dataList = [data]

                bulkImportInput.data = dataList
                createImportJobRequest.bulk_import_input = bulkImportInput
                response = client.create_import_job(createImportJobRequest)
                logger.info("Getting response successfully for importjobpost " + response)
            except exceptions.MindsphereError as err:
                logger.error("getting error for importjobpost " + err)
                return HttpResponse(
                    err,
                    content_type="application/json",
                    status=status.HTTP_500_INTERNAL_SERVER_ERROR,
                )
            return HttpResponse(
                json.dumps(response.to_dict()), content_type="application/json", status=status.HTTP_200_OK
            )
Ejemplo n.º 17
0
def query_kmers(temp_l, t, fasta, o, batch_size):
    """Finds kmers in variant sequences"""
    ### The fasta being referenced is "nucleotide_prevalence_all.fasta"
    list_size = math.ceil(len(temp_l) / (math.ceil(len(temp_l) / batch_size)))
    temp_l = (split_list(temp_l, list_size))
    # print("Total # of indexes:", len(temp_l))

    f = {}
    r = {}
    for i, l in enumerate(temp_l):
        try:

            logger.info('PROCESS {t}.{i}: Adding kmers'.format(t=t, i=i))
            A = ahocorasick.Automaton()
            for k in l:
                A.add_word(k, k)
            logger.info('PROCESS {t}.{i}: Making automaton'.format(t=t, i=i))
            A.make_automaton()

            seq_num = 0
            for entry in SeqIO.parse(fasta, "fasta"):
                seq_num += 1
                if seq_num % 25000 == 0:
                    logger.info(
                        'PROCESS {t}.{i}: Done querying {n} sequences'.format(
                            t=t, n=seq_num, i=i))

                prev_id = entry.id.split(":")[1].split("|")[0]
                pathogens = id_path[
                    prev_id]  # get a list of pathogens that prev sequence is found in
                for tup in A.iter(str(entry.seq)):
                    kmer = tup[1]
                    rev_kmer = str(Seq.Seq(kmer).reverse_complement())
                    if kmer not in f:
                        f[kmer] = []
                    if rev_kmer not in r:
                        r[rev_kmer] = []
                    for p in pathogens:
                        if p not in f[kmer]:
                            f[kmer].append(p)
                        if p not in r[rev_kmer]:
                            r[rev_kmer].append(p)

            logger.info('PROCESS {t}.{i}: Done'.format(t=t, i=i))

        except Exception as e:
            logger.error(e)

    o.put((t, f, r))
Ejemplo n.º 18
0
async def answer_callback_query(
        callback_query_id: str,
        text: typing.Union[str, None] = None,
        show_alert: typing.Union[bool, None] = None,
        url: typing.Union[str, None] = None,
        cache_time: typing.Union[int, None] = None) -> bool:
    try:
        res = await bot.answer_callback_query(callback_query_id, text,
                                              show_alert, url, cache_time)
    except Exception as err:
        logger.error(f'Error on send answer_callback_query: {err}',
                     exc_info=True,
                     stack_info=True)
        return False
    else:
        return res
Ejemplo n.º 19
0
 def warpper(*args, **kwargs):
     try:
         data = func(*args, **kwargs)
     except CheckCodeException:
         return {'data': "教务系统请求失败", 'status_code': 400}
     except IdentityException as reqe:
         return {'data': str(reqe), 'status_code': 400}
     except LoginException as reqe:
         return {'data': str(reqe), 'status_code': 400}
     except SchoolException as reqe:
         return {'data': str(reqe), 'status_code': 400}
     except Exception as reqe:
         logger.error("请求出错 %s %s", func.__name__, reqe, exc_info=True)
         return {'data': "教务系统请求失败", 'status_code': 400}
     else:
         return {'data': data, 'status_code': 200}
Ejemplo n.º 20
0
    def results(self,
                blast_results,
                query_id,
                perfect,
                strict,
                loose,
                exclude_nudge=True):
        """
        Sort results to perfect, strict, loose paradigm

        Parameters
        ----------

        Args:
            blast_results (dict): dictionary containing perfect, strict anf loose hits
            query_id (str): blast record query
            perfect (dict): dictionary containing perfect hits
            strict (dict): dictionary containing strict hits
            loose (dict): dictionary containing loose hits

        Returns:
            blast_results (dict): dictionary of sorted results
        """

        nudged = False
        if len(perfect) == 0 and len(strict) == 0 and len(loose) > 0:
            if exclude_nudge is True:
                nudged, loose = self.nudge_loose_to_strict(loose)

            if nudged is True and self.loose is False:
                blast_results[query_id] = loose
            elif self.loose is True:
                blast_results[query_id] = loose

        elif len(perfect) == 0:
            if len(strict) > 0:
                # TODO:: add try catch here
                try:
                    nudged, strict = self.nudge_strict_to_perfect(strict)
                    blast_results[query_id] = strict
                except Exception as e:
                    logger.error(e)
        else:
            if len(perfect) > 0:
                blast_results[query_id] = perfect

        return blast_results
    def get(self, request, **kwargs):
        """
        Create asset.

         route assets/assets/<str:typeid>
         param typeid - Id of the assettype from which you want to create an
                             Asset. - passed as path variables
         param parentid    - Desired parentId of the asset. - passed in request.
         note Asset creation requires typeid and parentid to be provided in
                request body hence this two values cannot be empty. Values of this
                variables are passed as provided by user hence non existent/Incorrect
                values will result in MindsphereError.

         return Created asset on successful execution.

         description This method internally generates dynamic request
                       body for asset and calls method add_asset
                       AssetsClient.This class is available as part of dependency :
                       assetmanagement-sdk-<version-here>.jar.
                       
         apiEndpoint : POST /api/assetmanagement/v3/assets of assetmanagement service
         throws MindsphereError if an error occurs while attempting to invoke the
               sdk call.

        """
        logger.info("assets/assets/<str:typeid> invoked.")
        client = sdk_util.build_sdk_client(self.__class__.__name__, request)
        if request.method == "GET":
            try:
                logger.info("Request param is - typeID:" + kwargs.get("typeid", ""))
                root = client.get_root_asset(data_generator.generate_root_asset_input())
                request_object = data_generator.generate_asset_input(
                    type_id=kwargs.get("typeid", ""),
                    parent_id=request.GET.get("parentid", None),
                )
                asset = client.add_asset(request_object)
                logger.info("Getting response successfully " + json.dumps(asset.to_dict))
            except exceptions.MindsphereError as err:
                logger.error("Error occured " + err)
                return HttpResponse(
                    err,
                    content_type="application/json",
                    status=status.HTTP_500_INTERNAL_SERVER_ERROR,
                )
            return HttpResponse(
                json.dumps(asset.to_dict), content_type="application/json", status=status.HTTP_200_OK
            )
def response_ok(response, service_url=None):
    service = service_name(service_url)

    if response is None:
        logger.error("No response from service")
        return False
    elif response.status_code == 200:
        logger.info("Returned from service",
                    request_url=response.url,
                    status=response.status_code,
                    service=service)
        return True
    else:
        logger.error("Returned from service",
                     request_url=response.url,
                     status=response.status_code,
                     service=service)
        return False
    def get(self, request, **kwargs):
        """

         route assets/assetlocation/<str:id>/<str:ifmatch>
         param assetId : Unique identifier of an asset.

         return 'Location updated successfully' on successful execution.
         description This method internally calls method save_asset_location of LocationsClient class.
                     This class is available as dependency in assetmanagement-<version-here>-py3-none-any.whl.
                     If the given asset has own location, this endpoint will update that location.  If the given asset has4
                     no location, this endpoint will create a new location and update the given asset.
                     If the given asset has inherited location, this endpoint will create a new location and update the
                     given asset.

         apiEndpoint : PUT /api/assetmanagement/v3/assets/{id}/location of asset management service.

         apiNote   Create or Update location assigned to given asset.
                   If the given asset has own location, this endpoint will update that location.
                   If the given asset has no location, this endpoint will create a new location and update the given asset.
         throws MindsphereError if an error occurs while attempting to invoke the sdk call.

        """
        logger.info("assets/assetlocation/<str:id>/<str:ifmatch> invoked.")
        client = sdk_util.build_sdk_client(self.__class__.__name__, request)
        if request.method == "GET":

            try:
                ifmatch = kwargs.get("ifmatch", "")
                did = kwargs.get("id", "")
                logger.info("Request params are - Id: " + did + " and ifmatch:" + ifmatch)
                request_object = data_generator.generate_location_update_input(if_match=ifmatch,
                                                                               id=did)
                client.save_asset_location(request_object)
                logger.info("Location updated successfully")
            except exceptions.MindsphereError as err:
                logger.error("Getting eroor for assetlocation " + err)
                return HttpResponse(
                    err,
                    content_type="application/json",
                    status=status.HTTP_500_INTERNAL_SERVER_ERROR,
                )
            return HttpResponse(
                'Location updated successfully', content_type="application/json", status=status.HTTP_200_OK
            )
    def put(self, request, **kwargs):
        """
         Create aspect type.

         route assets/aspects
         param tenantName - Name of the tenant for which you want to create aspect type. Passed in request.
         return Created aspect type information object.
         description This method internally calls method save_aspect_type of AspecttypeClient class.
                        This class is available as dependency in assetmanagement-<version-here>-py3-none-any.whl

         apiEndpoint : PUT /api/assetmanagement/v3/aspecttypes/{id} of asset management service.

         apiNote Create or Update an aspect type
         throws MindsphereError if an error occurs while attempting to invoke the sdk call.

        """
        logger.info("put aspectt invoked.")
        client = sdk_util.build_sdk_client(self.__class__.__name__, request)
        if request.method == "PUT":
            try:
                ifmatch = kwargs.get("ifmatch", "")
                aspect_id = kwargs.get("id", "")
                requestObj = json.dumps(request.data)
                aspect = json.loads(requestObj)
                request_object = SaveAspectTypeRequest(id=aspect_id, aspecttype=aspect, if_match=ifmatch)
                response = client.save_aspect_type(request_object)
                response = serialization_filter.sanitize_for_serialization(response)
                response = json.dumps(response)
                applink = {"ApplinK": getLink()}
                response = json.loads(response)
                response.update(applink)
                print(json.dumps(response))
                logger.info("Getting response successfully " + json.dumps(response))
            except exceptions.MindsphereError as err:
                logger.error(err.message)
                status_code = err.message.status_code
                return HttpResponse(
                    json.dumps(err.message.message),
                    content_type="application/json",
                    status=status_code,
                )
            return HttpResponse(
                json.dumps(response), content_type="application/json", status=status.HTTP_200_OK
            )
    def get(self, request, **kwargs):
        """

         route assets/assetfiles/<str:id>
         return Details of uploaded file upon successful execution.
         param id : Unique identifier for an asset.
         param fileid : Unique identifier of file resource
         param ifmatch : Last known version to facilitate optimistic locking.
         note : id, ifmatch and key are passed via keyword arguments.
         param key : Keyword for the file to be assigned to an asset.
         description This method internally calls method save_asset_file_assignment of AssetsClient class.
                        This class is available as dependency in assetmanagement-<version-here>-py3-none-any.whl

         apiEndpoint : PUT /api/assetmanagement/v3/assets/{id}/fileAssignments/{key} of asset management service.
         apiNote Save a file assignment to a given asset.
         throws MindsphereError if an error occurs while attempting to invoke the sdk call.

        """
        logger.info("assets/assetfiles/<str:id> invoked.")
        client = sdk_util.build_sdk_client(self.__class__.__name__, request)
        if request.method == "GET":
            try:
                logger.info("Request param is Id:" + kwargs.get("id", ""))
                assignment = data_generator.generate_file_assignment(
                    fileid=request.GET.get("fileid", None)
                )
                request_object = data_generator.generate_save_asset_file_assignment_input(kwargs.get("id", ""),
                                                                                          request.GET.get("ifmatch",
                                                                                                          None),
                                                                                          request.GET.get("key", None),
                                                                                          assignment)
                asset = client.save_asset_file_assignment(request_object)
                logger.info("Getting response successfully for  assetfiles with id" + json.dumps(asset.to_dict))
            except exceptions.MindsphereError as err:
                logger.error("Getting error for assetfiles with id" + err)
                return HttpResponse(
                    err,
                    content_type="application/json",
                    status=status.HTTP_500_INTERNAL_SERVER_ERROR,
                )
            return HttpResponse(
                json.dumps(asset.to_dict()), content_type="application/json", status=status.HTTP_200_OK
            )
    def get(self, request, **kwargs):
        """
        Create asset type.


         route assets/assettype/<str:tenant>
         param tenant : Name of tenant for which you wish to create asset type.
         param aspectname : Name of an aspect type which you wish to associate with asset type.
         param  aspectid : Id of an aspect which you wish to associate with asset type.
         note : apsectname ans aspectid passed in request whereas tenant is passed in URL.
         return Created asset type.
         description This method internally calls method save_asset_type of AssettypeClient class.
                        This class is available as dependency in assetmanagement-<version-here>-py3-none-any.whl

         apiEndpoint : PUT /api/assetmanagement/v3/assettypes/{id} of asset management service.

         apiNote Create or Update an asset type.
         throws MindsphereError if an error occurs while attempting to invoke the sdk call.

        """
        logger.info("assets/assettype/<str:tenant> invoked.")
        client = sdk_util.build_sdk_client(self.__class__.__name__, request)
        if request.method == "GET":
            try:
                logger.info("Request param is- Tenant: " + kwargs.get("tenant", ""))
                request_object = data_generator.generate_asset_type_input(
                    tenant=kwargs.get("tenant", ""),
                    aspect_id=request.GET.get("aspectid", None),
                    aspect_name=request.GET.get("aspectname", None),
                )
                aspect = client.save_asset_type(request_object)
                logger.info("Getting response successfully for create assettype " + json.dumps(aspect.to_dict))
            except exceptions.MindsphereError as err:
                logger.error("Getting error for create assettype " + err)
                return HttpResponse(
                    err,
                    content_type="application/json",
                    status=status.HTTP_500_INTERNAL_SERVER_ERROR,
                )
            return HttpResponse(
                json.dumps(aspect.to_dict), content_type="application/json", status=status.HTTP_200_OK
            )
def remote_call(url, json=None):
    service = service_name(url)

    try:
        logger.info("Calling service", request_url=url, service=service)
        response = None

        if json:
            response = session.post(url, json=json)
        else:
            response = session.get(url)

        return response

    except MaxRetryError:
        logger.error("Max retries exceeded (5)", request_url=url)
        raise RetryableError("Max retries exceeded")
    except ConnectionError:
        logger.error("Connection error", request_url=url)
        raise RetryableError("Connection error")
    def get(self, request, **kwargs):
        """

         route assetsdeletewithconfirmation/<str:id>/<str:ifmatch>
         param id : Unique identifier for an asset.
         param ifmatch : Last known version to facilitate optimistic locking.
         return  'Asset deleted successfully.' on successful execution.
         description This method internally calls method delete_asset_with_confirmation of AssetsClient class.
                     This class is available as dependency in assetmanagement-<version-here>-py3-none-any.whl.
                     Deletes an asset and confirms deletion. It internally checks existence of the
                     asset after we receive a confirmation from server. It retries 3 times for getting the confirmation from
                     server. After deletion only users with admin role can read it, but modification is not possible anymore.
                     Deletion is not possible to delete an asset if it has children.

         apiEndpoint : DELETE /api/assetmanagement/v3/assets/{id} of asset management service.

         apiNote Deletes an asset.
         throws MindsphereError if an error occurs while attempting to invoke the sdk call.
        """
        logger.info("assets/assetsdeletewithconfirmation/<str:id>/<str:ifmatch> invoked.")
        client = sdk_util.build_sdk_client(self.__class__.__name__, request)
        if request.method == "GET":
            try:
                logger.info(
                    "RequestParam are - assetID: " + kwargs.get("id", "") + " ifmatch:" + kwargs.get("ifmatch", ""))
                request_object = data_generator.generate_delete_asset_with_confirmation_input(id=kwargs.get("id", ""),
                                                                                              if_match=
                                                                                              kwargs.get
                                                                                              ("ifmatch", ""))
                client.delete_asset_with_confirmation(request_object)
                logger.info("Asset deleted successfully with confirmation")
            except exceptions.MindsphereError as err:
                logger.error("Getting error while deleting asset with confirmation " + err)
                return HttpResponse(
                    err,
                    content_type="application/json",
                    status=status.HTTP_500_INTERNAL_SERVER_ERROR,
                )
            return HttpResponse(
                'Asset deleted successfully.', content_type="application/json", status=status.HTTP_200_OK
            )
Ejemplo n.º 29
0
async def edit_message_reply_markup(
        chat_id: typing.Union[int, str, None] = None,
        message_id: typing.Union[int, None] = None,
        inline_message_id: typing.Union[str, None] = None,
        reply_markup: typing.Union[InlineKeyboardMarkup, None] = None) -> bool:
    try:
        res = await bot.edit_message_reply_markup(chat_id, message_id,
                                                  inline_message_id,
                                                  reply_markup)

    except (BotKicked, BotBlocked, ChatNotFound):
        await User.all().filter(chat_id=chat_id).delete()

    except Exception as err:
        logger.error(f'Error on edit_message_reply_markup: {err}',
                     exc_info=True,
                     stack_info=True)
        return False

    else:
        return res
    def get(self, request,**kwargs):
        """
        get import job details by id

         route iotbulk/importjobget/<str:id>
         param id - Bulk import job id as obtained on job creation. (This ID is part of response after creating import job).

         note - incorrect/non-existent id will result in MindsphereError.

         return JobStatus corresponding to provided id in String format.

         description This method internally calls method retrieve_import_job of BulkImportOperationsClient class.
                        This class is available as dependency in iottsbulk-<version-here>-py3-none-any.whl.

         apiEndpoint : GET /api/iottsbulk/v3/importJobs/{id} of iot bulk service.
                       service.
         apiNote Retrieve status of bulk import job.
         throws MindsphereError if an error occurs while attempting to invoke the sdk call.

        """
        logger.info("iotbulk/importjobget/<str:id> invoked")
        client = sdk_util.build_sdk_client(self.__class__.__name__, request)
        if request.method == "GET":
            try:
                id = kwargs.get("id", "")
                logger.info("RequestParam is- Id:"+id)
                request = RetrieveImportJobRequest()
                request.id = id
                response = client.retrieve_import_job(request)
                logger.info("Getting response successfully for importjobget "+response)
            except exceptions.MindsphereError as err:
                logger.error("getting error for importjobget "+err)
                return HttpResponse(
                    err,
                    content_type="application/json",
                    status=status.HTTP_500_INTERNAL_SERVER_ERROR,
                )
            return HttpResponse(
                json.dumps(response), content_type="application/json", status=status.HTTP_200_OK
            )