Teamcenter_SOA开发:使用查询构建器查询数据

Posted huangym1

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Teamcenter_SOA开发:使用查询构建器查询数据相关的知识,希望对你有一定的参考价值。

Teamcenter中的查询构建器可以查询对象信息,今天使用Item Name这个查询来查询Teamcenter中的对象,并打印出对象的信息。搭建环境参见Teamcenter_SOA开发:使用SOA登录Teamcenter - huangym1 - 博客园 (cnblogs.com)

 //tcnx_projectexe.h
 #pragma once
 // Mandatory UF Includes
 #include <uf.h>
 #include <uf_object_types.h>
 #include <uf_ugmgr.h>
 #include <uf_part.h>
 #include <uf_disp.h>
 #include <uf_modl.h>
 #include <uf_obj.h>
 #include <uf_assem.h>
 
 // Internal+External Includes
 #include <NXOpen/Annotations.hxx>
 #include <NXOpen/Assemblies_Component.hxx>
 #include <NXOpen/Assemblies_ComponentAssembly.hxx>
 #include <NXOpen/Body.hxx>
 #include <NXOpen/BodyCollection.hxx>
 #include <NXOpen/Face.hxx>
 #include <NXOpen/Line.hxx>
 #include <NXOpen/NXException.hxx>
 #include <NXOpen/NXObject.hxx>
 #include <NXOpen/Part.hxx>
 #include <NXOpen/PartCollection.hxx>
 #include <NXOpen/Session.hxx>
 
 #include <NXOpen/PDM_PdmSession.hxx>
 #include <NXOpen/PDM_SoaConnectionHandle.hxx>
 #include <teamcenter/soa/client/Connection.hxx>
 #include <teamcenter/services/core/DatamanagementService.hxx>
 #include <teamcenter/soa/common/Version.hxx>
 
 // check mate
 #include <NXOpen/Validate_ValidationManager.hxx>
 #include <NXOpen/Validate_Validator.hxx>
 #include <NXOpen/Validate_ValidatorOptions.hxx>
 #include <NXOpen/Validate_Parser.hxx>
 
 // Std C++ Includes
 #include <iostream>
 #include <sstream>
 #include <stdio.h>
 #include <stdlib.h>
 
 using namespace NXOpen;
 using namespace Teamcenter::Soa::Client;
 using namespace Teamcenter::Services::Core;
 using std::string;
 using std::exception;
 using std::stringstream;
 using std::endl;
 using std::cout;
 using std::cerr;
 
 #define MAX_UGMGR_NAME_LEN 1024
 #define CREATION_DATE       1
 #define MODIFICATION_DATE   2
 static int indent_level = 0;
 
 #define CHECK( func_ ) \\
     ifail = (func_); \\
 if (ifail != 0) \\
 printf("ERROR: %s returned %d", # func_, ifail); \\
 return ifail;
 
 #define PRINT( content_ ) \\
  int ii; \\
 for (ii = 0; ii < indent_level; ii++) \\
  printf("  ");  \\
     printf content_; \\
     printf("\\n"); 
 
 
 //tcnx_projectexe.cpp
 #include "tcnx_projectexe.h"
 #include "teamcenter/clientx/AppXSession.hxx"
 #include "teamcenter/hello/HomeFolder.hxx"
 #include "teamcenter/hello/Query.hxx"
 #include <teamcenter/soa/client/model/User.hxx>
 #include <teamcenter/soa/client/RuntimeException.hxx>
 
 using namespace Teamcenter::ClientX;
 using namespace Teamcenter::Services::Core;
 using namespace Teamcenter::Soa::Common;
 using namespace Teamcenter::Soa::Client;
 using namespace Teamcenter::Soa::Client::Model;
 using namespace Teamcenter::Schemas::Soa::_2006_03::Exceptions;
 using namespace Teamcenter::Hello;
 
 
 //===================
 // Entry Point
 //===================
 #ifdef WIN32
 int _tmain(int argc, _TCHAR* argv[])
 #else
 int main(int argc, char* argv[])
 #endif
 
     try
 
 #ifdef _UFUGMGR
         int _errCode = 0;
         const char** consolePara = (const char**)(argv);
         logical is_active;
         _errCode = UF_is_ugmanager_active(&is_active);// 判断ugmanager环境是否已经初始化
         if (!is_active)
             _errCode = UF_UGMGR_initialize(argc, consolePara);// 初始化ugmanager环境
 
         //do_it();
         //_errCode = invokePdmServer();
 
         _errCode = UF_UGMGR_terminate();
         return _errCode;
 #else
         if (argc > 1)
             if (strcmp(argv[1], "-help") == 0 || strcmp(argv[1], "-h") == 0)
                 cout << "usage: Hello [-host http://server:port/tc] " << endl;
                 return 0;
             
         
 
         std::string serverHost = "http://plmdev:7001/tc";
         if (argc > 2 && strcmp(argv[1], "-host") == 0)
             serverHost = argv[2];
 
         string _username, _password;
         std::vector<std::string> _tempStr;
         for (int idx = 0; idx < argc; idx++)
             _tempStr.push_back(argv[idx]);
             if (string(argv[idx]).find("-u=") != std::string::npos)
                 _username = string(argv[idx]).substr(string(argv[idx]).find_first_of("=") + 1);
             
             else if (string(argv[idx]).find("-p=") != std::string::npos)
                 _password = string(argv[idx]).substr(string(argv[idx]).find_first_of("=") + 1);
             
         
 
         AppXSession     session(serverHost, _username, _password);
         HomeFolder  home;
         Query       query;
 
         try
             User* user = session.login();
             if (!user)
                 return 0;
 
             home.listHomeFolder(user);
             query.queryItems();
 
             session.logout();
         
         catch (Teamcenter::Soa::Client::RuntimeException& e)
             cout << e.getMessage() << endl;
             cout << "The application will terminate." << endl;
         
         return 0;
 #endif
 
     
     catch (const NXException& e1)
         cerr << "NXException: " << e1.ErrorCode() << endl;
         cerr << e1.Message() << endl;
     
     catch (const exception& e2)
         cerr << "Exception: " << e2.what() << endl;
     
     catch (...)
         cerr << "Unknown Exception: " << endl;
     
 
 //Query.hpp
 #ifndef TEAMCENTER_HELLO_QUERY_HXX
 #define TEAMCENTER_HELLO_QUERY_HXX
 
 namespace Teamcenter
 
     namespace Hello
     
         class Query;
         class  Query
         
         public:
 
             void queryItems();
         ;
     
  //end namespace
 #endif
 
 //Query.cpp
 #include "Query.hxx"
 #include "../clientx/AppXSession.hxx"
 
 #include <teamcenter/schemas/soa/_2006_03/exceptions/ServiceException.hxx>
 #include <teamcenter/services/query/SavedqueryService.hxx>
 #include <teamcenter/services/core/DatamanagementService.hxx>
 #include <teamcenter/soa/client/model/ImanQuery.hxx>
 #include <teamcenter/soa/client/NotLoadedException.hxx>
 
 #include <iostream>
 #include <vector>
 
 using namespace std;
 using namespace Teamcenter::ClientX;
 using namespace Teamcenter::Hello;
 using namespace Teamcenter::Schemas::Soa::_2006_03::Exceptions;
 using namespace Teamcenter::Services::Query;
 using namespace Teamcenter::Services::Core;
 using namespace Teamcenter::Soa::Common;
 using namespace Teamcenter::Soa::Client;
 using namespace Teamcenter::Soa::Client::Model;
 
 
 void Query::queryItems()
 
     ImanQuery *query;
     SavedqueryService* queryService = SavedqueryService::getService(AppXSession::getConnection());
     DatamanagementService* dmService = DatamanagementService::getService(AppXSession::getConnection());
 
     try
     
         SavedqueryService::GetSavedQueriesResponse savedQueries = queryService->getSavedQueries();
 
         if (savedQueries.queries.size() == 0)
             cout << "There are no saved queries in the system." << endl;
             return;
         
         for (size_t i = 0; i < savedQueries.queries.size(); i++)
         
             if (savedQueries.queries[i].name == "Item Name")
             
                 query = savedQueries.queries[i].query;
                 break;
             
         
     
     catch (ServiceException& e)
     
         cout << "GetSavedQueries service request failed." << endl;
         cout << e.getMessage() << endl;
         return;
     
     if (query == nullptr)
         cout << "There is not an \'Item Name\' query." << endl;
         return;
     
 
     try
     
         // Search for all Items, returning a maximum of 25 objects
         vector<Teamcenter::Services::Query::_2008_06::Savedquery::QueryInput> savedQueryInputs;
         vector< ModelObject* > limitList;
         vector< string > entries;
         vector< string > values;
         entries.push_back("Item Name");
         values.push_back("*");
         Teamcenter::Services::Query::_2008_06::Savedquery::QueryInput savedQueryInput;
         savedQueryInput.query = query;
         savedQueryInput.maxNumToReturn = 300;
         savedQueryInput.limitList = limitList;
         savedQueryInput.entries = entries;
         savedQueryInput.values = values;
         savedQueryInput.resultsType = 0;
         savedQueryInputs.push_back(savedQueryInput);
 
         SavedqueryService::SavedQueriesResponse queryResponse = queryService->executeSavedQueries(savedQueryInputs);
         SavedqueryService::QueryResults found = queryResponse.arrayOfResults[0];
 
         cout << "" << endl;
         cout << "Found Items:" << endl;
 
         // Page through the results 10 at a time
         for (size_t i = 0; i < found.objectUIDS.size(); i += 10)
         
             size_t pageSize = (i + 10 < found.objectUIDS.size()) ? 10 : found.objectUIDS.size() - i;
 
             vector<string> uids;
             for (size_t j = 0; j < pageSize; j++)
                 uids.push_back(found.objectUIDS[i + j]);
             
             ServiceData sd = dmService->loadObjects(uids);
             vector<ModelObject* > foundObjs = sd.getPlainObjs();
             AppXSession::printObjects(foundObjs);
         
     
     catch (ServiceException& e)
         cout << "ExecuteSavedQuery service request failed." << endl;
         cout << e.getMessage() << endl;
         return;
     
 

 

 程序调试运行查询GIF动图:

 

 

黄河远上白云间,一片孤城万仞山。
羌笛何须怨杨柳,春风不度玉门关。

 

诗人初到凉州,面对黄河、边城的辽阔景象,又耳听着《折杨柳》曲,有感而发,写成了这首表现戍守边疆的士兵思念家乡情怀的诗作。

  诗的前两句描绘了西北边地广漠壮阔的风光。首句抓住自下(游)向上(游)、由近及远眺望黄河的特殊感受,描绘出“黄河远上白云间”的动人画面:汹涌澎湃波浪滔滔的黄河竟像一条丝带迤逦飞上云端。写得真是神思飞跃,气象开阔。诗人的另一名句“黄河入海流”,其观察角度与此正好相反,是自上而下的目送;而李白的“黄河之水天上来”,虽也写观望上游,但视线运动却又由远及近,与此句不同。“黄河入海流”和“黄河之水天上来”,同是着意渲染黄河一泻千里的气派,表现的是动态美。而“黄河远上白云间”,方向与河的流向相反,意在突出其源远流长的闲远仪态,表现的是一种静态美。同时展示了边地广漠壮阔的风光,不愧为千古奇句。

python测试开发django-117.bootstrapTable结合Paginator分页器查显示表格

前言

bootstrap 提供了table表格插件,可以快速帮我们实现分页功能。这样就不用在前端页面上写分页逻辑,只需关注后端给对应数据就行。
bootstrap-table提供两种分页方式,client和server,即客户端和服务端分页;

  • client分页:后台一次性返回所有数据,前台翻页时不再请求后台(数据量很大的时候会导致查询很慢)。
  • server分页:后台根据前台每次翻页时传递的参数,可以结合Paginator分页器查询每个页码对应的数据,每次只返回对应页面的数据

bootstrap-table

下载所需要的包

Bootstrap 中文网:http://www.bootcss.com/
Bootstrap Table 官网:https://bootstrap-table.com/
JQuery 官网:https://jquery.com/

放置static文件中,目录结构如下

模板中头部引用

# 作者-上海悠悠 QQ交流群:717225969
# blog地址 https://www.cnblogs.com/yoyoketang/

<head>
 {% load static %}
 <title>bootstrap-table</title>
 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
 <meta name="description" content="" />
 <meta name="keywords" content="" />
 <link rel="stylesheet" type="text/css" href="/static/bootstarp/css/bootstrap.min.css" >
 <link rel="stylesheet" type="text/css" href="/static/bootstrap-table/dist/bootstrap-table.min.css" >

 <script type="text/javascript" src="/static/bootstarp/jquery/jquery-3.6.0.min.js"></script>
 <script type="text/javascript" src="/static/bootstarp/js/bootstrap.min.js"></script>
 <script type="text/javascript" src="/static/bootstrap-table/dist/bootstrap-table.min.js"></script>
 <script type="text/javascript" src="/static/bootstrap-table/dist/locale/bootstrap-table-zh-CN.min.js"></script>

</head>

bootstrapTable实现数据加载

script 中bootstrapTable 几个摘要参数
url: 访问数据的接口,需返回json对象,如:{“total”: 2,“rows”: [{“id”: 0,“name”: “Item 0”,“price”: “$0”},]
columns: table表格中显示的字段和名称
queryParams:查询的时候,提交查询参数

<body>
<div class="container">
    <h1>bootstrapTable实例</h1>
    <hr/>

    <div id="toolbar" class="btn-group">
        <button id="btn_add" type="button" class="btn btn-default">
            <span class="glyphicon glyphicon-plus" aria-hidden="true"></span>新增
        </button>
        <button id="btn_edit" type="button" class="btn btn-default">
            <span class="glyphicon glyphicon-pencil" aria-hidden="true"></span>修改
        </button>
        <button id="btn_delete" type="button" class="btn btn-default">
            <span class="glyphicon glyphicon-remove" aria-hidden="true"></span>删除
        </button>
    </div>

    <table id="table" class="table table-striped"></table>
</div>
</body>
<script>
    var url = '/teacher/info';
    var columns = [
        {
            checkbox: true,
            visible: true                  //是否显示复选框
        },
        {
            field: 'id',
            title: 'ID'
        }, {
            field: 'name',
            title: '姓名'
        }, {
            field: 'age',
            title: '年龄'
        },
         {
            field: 'tel',
            title: '电话'
        }
    ];
    $("#table").bootstrapTable({
        toolbar: '#toolbar',                //自定义工具按钮
        url: url,                           //请求后台的URL(*)
        method: 'get',                      //请求方式(*)
        cache: false,                       //是否使用缓存,默认为true,所以一般情况下需要设置一下这个属性(*)
        pagination: true,                   //是否显示分页(*)
        pageSize: 10,                       //每页的记录行数(*)
        pageList: [10, 20, 50, 100, 'All'], //可供选择的每页的行数(*)
        sidePagination: "server",           //分页方式:client客户端分页,server服务端分页(*)
        pageNumber: 1,                      //初始化加载第一页,默认第一页
        //search: true,                       //是否显示表格搜索
        showColumns: true,                  //是否显示所有的列
        showRefresh: true,                  //是否显示刷新按钮
        minimumCountColumns: 2,             //最少允许的列数
        //height: 500,                      //行高,如果没有设置height属性,表格自动根据记录条数决定表格高度
        showToggle: true,                   //是否显示详细视图和列表视图的切换按钮
        columns: columns,                   //列参数
        //detailView: true,                  //是否显示父子表
        //得到查询的参数,会在url后面拼接,如:?rows=5&page=2&sortOrder=asc&search_kw=&_=1564105760651
        queryParams: function (params) {
            //这里的键的名字和控制器的变量名必须一直,这边改动,控制器也需要改成一样的
            var query_params = {
                page: (params.offset / params.limit) + 1,   //页码
                size: params.limit,    //页面大小
                //查询框中的参数传递给后台
                //search_kw: $('#search-keyword').val(), // 请求时向服务端传递的参数
            };
            return query_params;
        },

    });
    //得到查询的参数


</script>
</html>

视图

查询结果必须是json格式:{“total”: 2,“rows”: [{},{}]},其中total和rows名称必须保持一致,前端才能加载到数据

from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage
from django.db.models import Q
from django.forms.models import model_to_dict
# 作者-上海悠悠 QQ交流群:717225969
# blog地址 https://www.cnblogs.com/yoyoketang/


def teacherpage(request):
    return render(request, 'boot_table.html')

def teacherInfo(request):
    """
    查询结果必须是json格式:{"total": 2,"rows": [{},{}]}
    """
    if request.method == "GET":
        # search_kw = request.GET.get('search_kw', None)
        # 获取分页参数用于查询对应页面数据,page为第几页,size为每页数据条数
        page_num = request.GET.get('page',  1)
        size = request.GET.get('size', 10)
        # 查询全部
        teachers = Teacher.objects.all()
        # 使用分页器返回查询的页数和size
        paginator = Paginator(teachers, per_page=size)
        page_object = paginator.page(page_num)

        # 总数
        total = teachers.count()
        # 查询list of dict
        rows = [model_to_dict(i) for i in page_object]
        # print(rows)
        return JsonResponse({'total': total, 'rows': rows})

页面展示效果

默认每页查询10条数据

可以修改每页显示的条数

queryParams 查询

queryParams查询对应的参数

  • params.limit 是每页的条数,一般对应size参数
  • params.offset 是起始位置的数目,对应的page需要计算得到(params.offset / params.limit) + 1
  • search_kw 对应搜索框内容,需设置.bootstrapTable属性 search: true

toolbar 工具

toolbar 对应table表格上的新增/修改/删除

<div id="toolbar" class="btn-group">
        <button id="btn_add" type="button" class="btn btn-default">
            <span class="glyphicon glyphicon-plus" aria-hidden="true"></span>新增
        </button>
        <button id="btn_edit" type="button" class="btn btn-default">
            <span class="glyphicon glyphicon-pencil" aria-hidden="true"></span>修改
        </button>
        <button id="btn_delete" type="button" class="btn btn-default">
            <span class="glyphicon glyphicon-remove" aria-hidden="true"></span>删除
        </button>
    </div>

此部分后端接口还没实现

参考教程:https://www.cnblogs.com/landeanfen/p/4976838.html
bootstrap-table官方文档:https://examples.bootstrap-table.com/
bootstrap-table API在线查看效果:https://live.bootstrap-table.com/
bootstrap table 方法 详细教程: https://www.itxst.com/bootstrap-table-methods/tutorial.html

以上是关于Teamcenter_SOA开发:使用查询构建器查询数据的主要内容,如果未能解决你的问题,请参考以下文章

从 6 个表构建一个 mysql 查询以减少 php 的使用

使用 Laravel 查询构建器方法 whereIn() 和子查询

如何使用 (where:) 构建 GraphQL 查询

Qt平台下使用QJson解析和构建JSON字符串

Vuejs2.0构建一个彩票查询WebAPP

Laravel 查询构建器 - 从另一个表中选择前 1 行