def sharing_view_top(request, info_msg=''): request.session.set_expiry(SESSION_EXPIRY) error_ = check_allow_sharing_view(request) if error_ is not None: return error_ try: replace_dict = get_common_replace_dict(request) # Poclicyファイルからcommunity一覧を取得 communities = get_policy_communities().split(',') # policyセット(tableのheader部で使用) replace_dict['communities'] = communities # TAXII replace_dict['taxiis'] = Taxii.objects.all() # config replace_dict['config'] = Config.objects.get() # message replace_dict['info_msg'] = info_msg # languages replace_dict['languages'] = LANGUAGES # languages replace_dict['user'] = request.user try: # Ctirsクラスのインスタンスを作成 ctirs = Ctirs(request) # rs_communities (Vendor Source) replace_dict['rs_communities'] = ctirs.get_rs_communities() except Exception: # レンダリング return render(request, 'sharing.html', replace_dict) # レンダリング return render(request, 'sharing.html', replace_dict) except Exception: return error_page(request)
def l2_view_top(request): request.session.set_expiry(SESSION_EXPIRY) error_ = check_allow_l2_view(request) if error_ is not None: return error_ try: package_id = get_l2_view_top_package_id(request) ipv4 = get_l2_view_top_ipv4_similarity(request) domain = get_l2_view_top_domain_similarity(request) replace_dict = get_common_replace_dict(request) object_id = get_l2_view_top_object_id(request) ctirs = Ctirs(request) if len(package_id) == 0 and len(object_id) != 0: try: bundles = ctirs.get_bundle_from_object_id( object_id)['package_id_list'] package_id = bundles[0] except Exception: package_id = '' packages = ctirs.get_package_list() replace_dict['packages'] = packages replace_dict['package_id'] = package_id replace_dict['ipv4'] = ipv4 replace_dict['domain'] = domain return render(request, 'l2.html', replace_dict) except Exception: import traceback traceback.print_exc() return error_page(request)
def stix_upload(request): request.session.set_expiry(SESSION_EXPIRY) error_ = check_allow_sharing_view(request) if error_ is not None: return error_ try: # post以外はエラー if request.method != 'POST': # エラー画面 raise Exception('Invalid HTTP Method') package_name = get_sharing_upload_package_name(request) if (len(package_name) > 100): return error_page_free_format( request, 'Exceeded the max length of Package name.') community_id = get_sharing_upload_vendor_id(request) if (community_id is not None and len(community_id) > 100): return error_page_free_format( request, 'Exceeded the max length of Vendor id.') stixes = get_sharing_stix(request) # Ctirsクラスのインスタンスを作成 ctirs = Ctirs(request) ctirs.post_stix_files(community_id, package_name, stixes[0]) # レンダリング(sharingのトップページ) return sharing_view_top(request, 'Upload Success!!') except Exception: return error_page(request)
def create_language_content(request): request.session.set_expiry(SESSION_EXPIRY) # POST以外はエラー if request.method != 'POST': r = {'status': 'NG', 'message': 'Invalid HTTP method'} return JsonResponse(r, safe=False) try: content = request.POST['content'] object_ref = request.POST['object_ref'] language = request.POST['language'] selector = request.POST['selector'] language_content = { 'content': content, 'selector': selector, 'language': language, } language_contents = [language_content] # Ctirsクラスのインスタンスを作成 ctirs = Ctirs(request) # language_content 作成 ctirs.post_language_contents(object_ref, language_contents) resp = {'status': 'OK', 'message': 'Success!!'} except Exception as e: traceback.print_exc() resp = {'status': 'NG', 'message': e.message} finally: return JsonResponse(resp, safe=False)
def download_stix(request): request.session.set_expiry(SESSION_EXPIRY) error_ = check_allow_l1_view(request) if error_ is not None: return error_ try: # Ctirsクラスのインスタンスを作成 ctirs = Ctirs(request) # package_id取得 package_id = get_l1_package_id(request) # apiからcontent取得 dict_ = ctirs.get_stix_file_stix(package_id) stix_package = STIXPackage.from_dict(dict_) # XML変換した文字列をStringIO化する(その際にUNICODEに変換) output = io.StringIO() output.write(stix_package.to_xml()) filename = '%s.xml' % (package_id) # response作成 response = HttpResponse(output.getvalue(), content_type='application/xml') response['Content-Disposition'] = 'attachment; filename=%s' % ( filename) return response except Exception: # エラーページ return error_page(request)
def get_stix_comment(request): request.session.set_expiry(SESSION_EXPIRY) # GET以外はエラー) if request.method != 'GET': r = {'status': 'NG', 'message': 'Invalid HTTP method'} return JsonResponse(r, safe=False) r = check_allow_sharing_view(request) if r is not None: return r # package_id package_id = get_sharing_ajax_change_stix_comment_package_id(request) if ((package_id is None)): r = {'status': 'NG', 'message': 'Invalid parameter.'} return JsonResponse(r, safe=False) try: # Ctirsクラスのインスタンスを作成 ctirs = Ctirs(request) # package_idと一致するcommentを取得 data = ctirs.get_stix_file(package_id) if data is None: raise Exception('No data') r = {'status': 'OK', 'comment': data['comment']} except Exception as e: print('Excepton:' + str(e)) r = {'status': 'NG', 'message': str(e)} finally: return JsonResponse(r, safe=False)
def l2_view_top(request): request.session.set_expiry(SESSION_EXPIRY) error_ = check_allow_l2_view(request) if error_ is not None: return error_ try: # パラメタが指定されている場合は取得 package_id = get_l2_view_top_package_id(request) ipv4 = get_l2_view_top_ipv4_similarity(request) domain = get_l2_view_top_domain_similarity(request) replace_dict = get_common_replace_dict(request) try: # Ctirsクラスのインスタンスを作成 ctirs = Ctirs(request) # ajax呼び出し packages = ctirs.get_package_list() replace_dict['packages'] = packages replace_dict['package_id'] = package_id replace_dict['ipv4'] = ipv4 replace_dict['domain'] = domain return render(request, 'l2.html', replace_dict) except Exception: # レンダリング return render(request, 'l2.html', replace_dict) except Exception: return error_page(request)
def change_stix_comment(request): request.session.set_expiry(SESSION_EXPIRY) # GET以外はエラー if request.method != 'POST': r = {'status': 'NG', 'message': 'Invalid HTTP method'} return JsonResponse(r, safe=False) r = check_allow_sharing_view(request) if r is not None: return r # package_id取得 package_id = get_sharing_ajax_change_stix_comment_package_id(request) # stix_commment取得 stix_comment = get_sharing_ajax_change_stix_comment_stix_comment(request) if ((package_id is None) or (stix_comment is None)): r = {'status': 'NG', 'message': 'Invalid parameter.'} return JsonResponse(r, safe=False) if (len(stix_comment) > 10240): r = {'status': 'NG', 'message': 'Exceeded the max length of Comment.'} return JsonResponse(r, safe=False) try: # Ctirsクラスのインスタンスを作成 ctirs = Ctirs(request) # table表示用コメント作成 ctirs.put_stix_comment(package_id, stix_comment) display_comment = create_display_comment(stix_comment) r = { 'status': 'OK', 'message': 'Success.', 'display_comment': display_comment } except Exception as e: print('Excepton:' + str(e)) r = {'status': 'NG', 'message': str(e)} finally: return JsonResponse(r, safe=False)
def related_package_nodes(request): request.session.set_expiry(SESSION_EXPIRY) if request.method != 'POST': r = {'status': 'NG', 'message': 'Invalid HTTP method'} return JsonResponse(r, safe=False) r = check_allow_l2_view(request) if r is not None: return r base_package = get_l2_ajax_base_package(request) compared_package_ids = request.POST.getlist('check_packages[]') is_ip_similar_check = get_l2_ajax_related_campagins_similar_ip(request) is_domain_similar_check = get_l2_ajax_related_campagins_similar_domain(request) exact = True try: ctirs = Ctirs(request) ret = ctirs.get_contents_and_edges(base_package, exact, compared_package_ids, is_ip_similar_check, is_domain_similar_check) if ret is None: r = {'status': 'NG', 'message': ' /api/v1/gv/contents_and_edges has no data.'} return JsonResponse(r, safe=False) except BaseException: r = {'status': 'NG', 'message': '/api/v1/gv/contents_and_edges error.'} return JsonResponse(r, safe=False) is_redact_confirm = get_l2_ajax_too_many_nodes(request) aj = AlchemyJsonData() for content in ret['contents']: set_alchemy_nodes(aj, content) aj.set_json_node_user_language(request.user.language) for object_ref, o_ in aj._json_nodes.items(): if o_._stix2_object is not None: modified = o_._stix2_object['modified'] language_contents = ctirs.get_language_contents(object_ref, modified) if len(language_contents) > 0: modify_alchemy_node_language_content(aj, language_contents[0]) for edge in ret['edges']: start_node_id = convert_valid_node_id(edge['start_node']['node_id']) end_node_id = convert_valid_node_id(edge['end_node']['node_id']) aj.set_json_node_exact(start_node_id) aj.set_json_node_exact(end_node_id) ae = AlchemyEdge(start_node_id, end_node_id, edge['edge_type']) aj.add_json_edge(ae) ret_json = aj.get_alchemy_json(is_redact_confirm) if ret_json is None: ret_json = {'status': 'WARNING', 'message': 'Too many nodes'} return JsonResponse(ret_json, safe=False) return JsonResponse(ret_json, safe=False)
def dashboard_view_top(request): request.session.set_expiry(SESSION_EXPIRY) # 認証されていない場合はログインページヘ if not request.user.is_authenticated(): return render(request, 'cover.html') stip_user = request.user # activeユーザー以外はエラー if not stip_user.is_active: return error_page_inactive(request) try: replace_dict = get_common_replace_dict(request) replace_dict['caution_msg'] = {} # username/passwordが'admin'の場合、password変更を促すメッセージを表示 try: change_pass_flag = request.session['change_pass_flag'] except KeyError: # SSO対応 # login 画面を跳ばした場合はchange_pass_flag がない # caution_msg はなしとする change_pass_flag = False if change_pass_flag: replace_dict[ 'caution_msg'] = 'Please change your administrator password from its default one.' request.session['change_pass_flag'] = False else: change_pass_flag = False replace_dict['caution_msg'] = {} try: # Ctirsクラスのインスタンスを作成 ctirs = Ctirs(request) # count 情報を Repository System から取得する replace_dict['counts'] = ctirs.get_count_by_type() # 最新 CTI 情報を Repository System から取得する replace_dict['latest_packages'] = ctirs.get_package_list( limit=10, order_by='-created') # レンダリング return render(request, 'dashboard.html', replace_dict) except Exception: if ('caution_msg_ctirs_flag' in request.session ) and request.session['caution_msg_ctirs_flag']: # CTIRSの情報に接続できない旨通知するメッセージを表示 replace_dict[ 'caution_msg_ctirs'] = 'You missed the connection setting to CTIRS.' request.session['caution_msg_ctirs_flag'] = False # レンダリング return render(request, 'dashboard.html', replace_dict) except Exception: import traceback traceback.print_exc() # エラーページ return error_page(request, replace_dict['caution_msg'])
def create_sighting(request): request.session.set_expiry(SESSION_EXPIRY) # GET以外はエラー if request.method != 'GET': r = {'status': 'NG', 'message': 'Invalid HTTP method'} return JsonResponse(r, safe=False) try: # 引数チェック try: first_seen = stix2_str_to_datetime(get_l1_ajax_create_sighting_first_seen(request)) except BaseException: r = {'status': 'NG', 'message': 'first_seen is invalid.' % ()} return JsonResponse(r, safe=False) try: last_seen = stix2_str_to_datetime(get_l1_ajax_create_sighting_last_seen(request)) except BaseException: r = {'status': 'NG', 'message': 'last_seen is invalid.' % ()} return JsonResponse(r, safe=False) try: count = int(get_l1_ajax_create_sighting_count(request)) except BaseException: r = {'status': 'NG', 'message': 'count is invalid.' % ()} return JsonResponse(r, safe=False) observed_data_id = get_l1_ajax_create_sighting_observed_data_id(request) if len(observed_data_id) == 0: r = {'status': 'NG', 'message': 'observed_data_id is invalid.' % ()} return JsonResponse(r, safe=False) # 投稿 ctirs = Ctirs(request) r = ctirs.post_stix_v2_sighting(observed_data_id, first_seen, last_seen, count) # Data 作成 resp = {} resp['status'] = 'OK' resp['message'] = 'Success' resp['sighting_id'] = r['sighting_object_id'] resp['json'] = r['sighting_object_json'] return JsonResponse(resp, safe=False) except Exception as e: traceback.print_exc() r = {'status': 'NG', 'message': e.message} return HttpResponseServerError(r)
def delete_package(request): request.session.set_expiry(SESSION_EXPIRY) error_ = check_allow_sharing_view(request) if error_ is not None: return error_ try: # package ID取得 package_ids = get_sharing_delete_package_package_id(request).split(',') # REST API 経由で Repository Systeに削除要求 for package_id in package_ids: # Ctirsクラスのインスタンスを作成 ctirs = Ctirs(request) ctirs.delete_stix_files_id(package_id) return sharing_view_top(request, 'Delete Success!!') except Exception: import traceback traceback.print_exc() return error_page(request)
def get_raw_stix(request): request.session.set_expiry(SESSION_EXPIRY) # GET以外はエラー if request.method != 'GET': r = {'status': 'NG', 'message': 'Invalid HTTP method'} return JsonResponse(r, safe=False) r = check_allow_sharing_view(request) if r is not None: return r try: # package_id取得 package_id = get_sharing_ajax_get_raw_stix_package_id(request) # Ctirsクラスのインスタンスを作成 ctirs = Ctirs(request) # STIXファイルの中身を取得 j = ctirs.get_stix_file_stix(package_id) # STIX 2.x であるかの判定を行う v2_flag = _is_stix2_(j) if v2_flag: # 返却json r = { 'status': 'OK', 'message': 'Success.', 'stix_version': '2.0', 'contents': j } else: stix_package = STIXPackage.from_dict(j) # 返却json xml = stix_package.to_xml() if isinstance(xml, bytes): xml = xml.decode() r = { 'status': 'OK', 'message': 'Success.', 'stix_version': '1.2', 'contents': xml } except Exception as e: traceback.print_exc() r = {'status': 'NG', 'message': str(e)} finally: return JsonResponse(r, safe=False)
def get_package_l1_info(request, package_id): l1_lists_ip = [] l1_lists_domain = [] l1_lists_url = [] l1_lists_sha1 = [] l1_lists_sha256 = [] l1_lists_sha512 = [] l1_lists_md5 = [] # Ctirsクラスのインスタンスを作成 ctirs = Ctirs(request) # REST API で L1情報取得する l1_infos = ctirs.get_stix_file_l1_info(package_id) for l1_info in l1_infos: type_ = l1_info['type'] value = l1_info['value'] if type_ == 'ipv4': l1_lists_ip.append(value) elif type_ == 'domain_name': l1_lists_domain.append(value) elif type_ == 'uri': l1_lists_url.append(value) elif type_ == 'sha1': l1_lists_sha1.append(value) elif type_ == 'sha256': l1_lists_sha256.append(value) elif type_ == 'sha512': l1_lists_sha512.append(value) elif type_ == 'md5': l1_lists_md5.append(value) # 情報を連結する l1_type_list = [ ('ip', l1_lists_ip), ('domain', l1_lists_domain), ('url', l1_lists_url), ('sha1', l1_lists_sha1), ('sha256', l1_lists_sha256), ('sha512', l1_lists_sha512), ('md5', l1_lists_md5), ] return l1_type_list
def get_draw_data(request): request.session.set_expiry(SESSION_EXPIRY) # GET以外はエラー if request.method != 'GET': r = {'status': 'NG', 'message': 'Invalid HTTP method'} return JsonResponse(r, safe=False) r = check_allow_sharing_view(request) if r is not None: return r try: # package_id名取得 package_id = get_sharing_ajax_get_draw_data_package_id(request) # community名取得 community = get_sharing_ajax_get_draw_data_community(request) # Ctirsクラスのインスタンスを作成 ctirs = Ctirs(request) # GetPolicy相当呼び出し rules = get_policy(community) # REST_API から STIX の json イメージを取得 dict_ = ctirs.get_stix_file_stix(package_id) # STIX 2.x であるかの判定を行う v2_flag = _is_stix2_(dict_) r = {'status': 'OK', 'rules': rules, 'message': 'Success.'} if v2_flag: # STIX 2.x の場合 r['json'] = dict_ r['stix_version'] = '2.0' else: # STIX 1.x の場合 # json から XML イメージを返却 xml = STIXPackage.from_dict(dict_).to_xml() if isinstance(xml, bytes): xml = xml.decode() r['xml'] = xml r['stix_version'] = '1.2' except Exception as e: traceback.print_exc() r = {'status': 'NG', 'message': str(e)} finally: return JsonResponse(r, safe=False)
def related_packages(request): request.session.set_expiry(SESSION_EXPIRY) if request.method != 'GET': r = {'status': 'NG', 'message': 'Invalid HTTP method'} return JsonResponse(r, safe=False) r = check_allow_l2_view(request) if r is not None: return r try: base_package = get_l2_ajax_base_package(request) is_ip_similar_check = get_l2_ajax_related_campagins_similar_ip(request) is_domain_similar_check = get_l2_ajax_related_campagins_similar_domain(request) exact = True ctirs = Ctirs(request) packages = ctirs.get_matched_packages(base_package, exact, is_ip_similar_check, is_domain_similar_check) return JsonResponse(packages, safe=False) except BaseException: import traceback traceback.print_exc() return JsonResponse(r, safe=False)
def get_package_info(request): request.session.set_expiry(SESSION_EXPIRY) # GET以外はエラー if request.method != 'GET': r = {'status': 'NG', 'message': 'Invalid HTTP method'} return JsonResponse(r, safe=False) # activeユーザー以外はエラー if not request.user.is_active: r = {'status': 'NG', 'message': 'You account is inactive.'} return JsonResponse(r, safe=False) try: # package_id取得 package_id = get_package_id(request) # l1情報取得 l1_type_list = get_package_l1_info(request, package_id) # description 取得 try: # Ctirsクラスのインスタンスを作成 ctirs = Ctirs(request) # STIXイメージ取得 dict_ = ctirs.get_stix_file_stix(package_id) stix_package = STIXPackage.from_dict(dict_) description = stix_package.stix_header.description.value except BaseException: # エラー時は空白 description = '' # 返却データ r = {'status': 'OK', 'description': description} # l1情報追加 for l1_type in l1_type_list: type_, values = l1_type r[type_] = values except Exception as e: print('Excepton:' + str(e)) r = {'status': 'NG', 'message': str(e)} finally: return JsonResponse(r, safe=False)
def get_l1_info_data_tables(request): request.session.set_expiry(SESSION_EXPIRY) # GET以外はエラー if request.method != 'GET': r = {'status': 'NG', 'message': 'Invalid HTTP method'} return JsonResponse(r, safe=False) r = check_allow_l1_view(request) if r is not None: return r try: # ajax parameter取得 sEcho = request.GET['sEcho'] # 表示する長さ iDisplayLength = int(request.GET['iDisplayLength']) # 表示開始位置インデックス iDisplayStart = int(request.GET['iDisplayStart']) # 検索文字列 sSearch = request.GET['sSearch'] # ソートする列 sort_col = int(request.GET['iSortCol_0']) # ソート順番 (desc指定で降順) sort_dir = request.GET['sSortDir_0'] # alias設定 aliases = [] # DBから設定をロード ctim_user = request.user.gv_auth_user for alias in Aliases.objects.filter(user=ctim_user.id): # alias設定を改行コードで区切りすべてリストに追加 aliases.append(alias.alias.split('\r\n')) # 文字列に変換 aliases_str = json.dumps(aliases) # Ctirsクラスのインスタンスを作成 ctirs = Ctirs(request) # ajax呼び出し data = ctirs.get_l1_info_for_l1table(iDisplayLength, iDisplayStart, sSearch, sort_col, sort_dir, aliases_str) if data is None: raise Exception('No data') # 返却jsonからhtmlデータ作成 aaData = [] for item in data['data']: l = [] l.append(item['type']) l.append(item['value']) # pacakge name link package_name = item['package_name'] package_id = item['package_id'] url = '/L2/?package_id=%s' % (package_id) s = '<a href=\"%s\" class="l1-pacakage-name-anchor">%s</a>' % (url, package_name) l.append(s) l.append(item['title']) l.append(item['description']) l.append(item['created']) # sighting if item['stix_v2']: # V2 の場合は s = '<a class="anchor-create-sighting" observable-id="%s" observable-value="%s"><span class="glyphicon glyphicon-pencil"></span></a>' % (item['observable_id'], item['value']) l.append(s) else: l.append('') aaData.append(l) # Data 作成 resp = {} resp['iTotalRecords'] = int(data['iTotalRecords']) resp['iTotalDisplayRecords'] = int(data['iTotalDisplayRecords']) resp['sEcho'] = sEcho resp['aaData'] = aaData return JsonResponse(resp, safe=False) except Exception as e: traceback.print_exc() r = {'status': 'NG', 'message': e.message} return HttpResponseServerError(r)
def get_package_table(request): request.session.set_expiry(SESSION_EXPIRY) # GET以外はエラー if request.method != 'GET': r = {'status': 'NG', 'message': 'Invalid HTTP method'} return JsonResponse(r, safe=False) r = check_allow_sharing_view(request) if r is not None: return r try: # ajax parameter取得 sEcho = request.GET['sEcho'] # 表示する長さ iDisplayLength = int(request.GET['iDisplayLength']) # 表示開始位置インデックス iDisplayStart = int(request.GET['iDisplayStart']) # 検索文字列 sSearch = request.GET['sSearch'] # ソートする列 sort_col = int(request.GET['iSortCol_0']) # ソート順番 (desc指定で降順) sort_dir = request.GET['sSortDir_0'] # Ctirsクラスのインスタンスを作成 ctirs = Ctirs(request) # ajax呼び出し data = ctirs.get_package_list_for_sharing_table( iDisplayLength, iDisplayStart, sSearch, sort_col, sort_dir) if data is None: raise Exception('No data') aaData = [] for item in data['data']: package_id = item['package_id'] package_name = item['package_name'] version = item['version'] l = [] l.append( '<input type="checkbox" package_id="%s" class="delete-checkbox"/>' % (package_id)) l.append( '<a package_id="%s" screen_user="******" class="stix-comment-dialog">%s</a>' % (package_id, request.user, create_display_comment(item['comment']))) l.append( '<a package_id="%s" class="csv-download"><span class="glyphicon glyphicon-cloud-download"></span></a>' % (package_id)) l.append('<a package_id="%s" class="draw-package">%s</a>' % (package_id, package_name)) l.append(item['input_community']) communities = get_policy_communities().split(',') for community in communities: if version.startswith('2.'): html = 'STIX 1.x only' else: html = '<a href="#" class="review-link" package_id="%s" community="%s"><label>[Click to Review]</label></a>' % ( package_id, community) l.append(html) aaData.append(l) # Data 作成 resp = {} resp['iTotalRecords'] = int(data['iTotalRecords']) resp['iTotalDisplayRecords'] = int(data['iTotalDisplayRecords']) resp['sEcho'] = sEcho resp['aaData'] = aaData except Exception as e: traceback.print_exc() resp = {'status': 'NG', 'message': e.message} finally: return JsonResponse(resp, safe=False)
def get_stix_counts(request): request.session.set_expiry(SESSION_EXPIRY) # GET以外はエラー if request.method != 'GET': r = {'status': 'NG', 'message': 'Invalid HTTP method'} return JsonResponse(r, safe=False) # activeユーザー以外はエラー if not request.user.is_active: r = {'status': 'NG', 'message': 'You account is inactive.'} return JsonResponse(r, safe=False) try: # 引数から取得する指定日数を取得する latest_days_bar = get_dashboard_ajax_get_stix_counts_since_days_bar( request) latest_days_pie = get_dashboard_ajax_get_stix_counts_since_days_pie( request) priority_type = get_dashboard_ajax_priority_type(request) # 個別描画の場合の指定日数の設定 latest_days = latest_days_bar if priority_type != 'bar': latest_days = latest_days_pie # Ctirsクラスのインスタンスを作成 ctirs = Ctirs(request) # Repository Systemに問い合わせる j = ctirs.get_latest_stix_count_by_community(latest_days=latest_days) # 基準日決定 start_date = datetime.date.today() # 円グラフのラベル(1日ごとの日付文字列) bar_labels = [] # vendor set vendors = [] for item in j: vendors.append(item['community']) # 棒グラフのラベル取得 for i in reversed(range(latest_days)): bar_labels.append(str(start_date - datetime.timedelta(i))) # 円グラフのラベル作成 pie_labels = vendors # pie_dict初期化 pie_dict = {} for vendor in vendors: pie_dict[vendor] = 0 # 棒グラフdatasets作成 bar_datasets = [] pie_dict = {} # Communityごとに日ごとのカウントを左から(古い方から)設定する for community_dict in j: count_list = [] # 最新順に格納されているのでリバースして for count_item in reversed(community_dict['count']): count_list.append(count_item['num']) community_name = community_dict['community'] bar_data = {'label': community_name, 'data': count_list} # 円グラフ描画用の辞書作成 pie_dict[community_name] = sum(count_list) bar_datasets.append(bar_data) # 円グラフdatasets作成 pie_datasets = [] for vendor in vendors: pie_datasets.append(pie_dict[vendor]) r = {} r['status'] = 'OK' r['data'] = {} r['data']['bar_labels'] = bar_labels r['data']['pie_labels'] = pie_labels r['data']['bar_datasets'] = bar_datasets r['data']['pie_datasets'] = pie_datasets return JsonResponse(r, safe=False) except BaseException: import traceback traceback.print_exc() r = {'status': 'NG', 'message': 'Server Internal Error.'} return JsonResponse(r, safe=False)