Python과Headless: 상호작용적이고 적응성이 강하며 가격이 합리적인 보고서를 어떻게 만드는지

본 논문에서, 나는 당신에게 머리 없는 CMS에서 데이터를 추출하고, Python 프레임워크 Dash 를 사용하여 내용 유형 보고서를 만드는 방법을 보여 드리겠습니다.

눈으로 본 것이 확실하다


나는 시각 학습자다.도표나 도표가 데이터를 수반할 때나 시각적 보조 도구가 프레젠테이션 원고의'요점'에 도착했을 때 나는 정말 고마웠다.모든 사람이 나처럼 도표를 좋아하는 것은 아니지만 데이터를 직관적으로 표현하는 것은 매우 유용하다.예를 들어, 프레젠테이션에서 이해하기 쉬운 것은 다음과 같습니다.
이러한 병렬 숫자: 101 | 443 | 102 | 320 | 82
혹은
이 차트는 다음과 같습니다.

구분자가 있는 숫자 목록만 사용하면 이 값들 간의 비교 상황을 잘 이해할 수 없다.이 도표는 차이와 유사성을 더욱 뚜렷하게 한다.
만약 당신이 새로운 매니저나 마케팅 팀의 구성원이라면, 이 팀은 머리 없는 CMS로 콘텐츠를 제작할 것이다.팀이 제작한 내용 유형을 이해하면 그들의 현재 내용 전략을 더욱 잘 이해하는 데 도움이 될 것이다.그러나 머리 없는 CMS에서 콘텐츠 모델을 볼 때, 긴 줄의 이름과 숫자를 볼 수 있다.

프로젝트의 내용 유형을 평가하기 위해서는 전체 내용 유형 목록을 스캔하고 그 값을 마음속으로 비교해야 합니다.시각적 보조가 없다면 프로젝트에서 어떤 주제가 유행하는지 판단하기 어렵다.그 밖에 분석을 마치면 팀의 다른 구성원들과 당신의 발견을 쉽게 공유할 수 없다.시각 보고서로 그들에게 너의 분석이 정확하다고 믿게 하는 것이 훨씬 쉽다.
그러나 프로젝트에 비즈니스 보고 도구를 통합할 시간이나 자원이 없으면 어떻게 해야 합니까?다행히도, 웹 분석 프로그램, 예를 들어Dash를 구축하는 데 사용할 소스 프레임워크와 라이브러리가 있다.

대시가 뭐예요?


대시는 유행하는 Plotly 그래픽 라이브러리를 바탕으로 구축된 프레임워크로 인터랙티브 시각 응용 프로그램을 구축하고 브라우저에 보여줄 수 있습니다.Dash 응용 프로그램은 백그라운드에서 JavaScript 라이브러리를 사용하지만, 완전히 Python으로 작성되어 JavaScript에 익숙해질 필요가 없습니다.
Python에 대해 알고 있다면, Dash는headless CMS 데이터에서 보고서를 작성하기에 매우 적합합니다. 여러 가지 well-documented 도형 형식을 지원하고, 원본 버전은 완전히 무료이기 때문입니다.

헤더 없는 CMS에서 보고서 작성 방법


Kentico Kontent headless CMS, 및 open source Kontent Python SDK를 사용하여 컨텐츠 보고서를 작성합니다.
우리의 예시 장면에서, 우리는 커피숍 사이트에 대한 세 개의 보고서를 만들고, 그것들을 옵션 카드 보고서에 모을 것이다.
Dash
우리의 보고서에서 우리는 다음과 같은 것을 보여주고 싶다.
  • 프로젝트에 어떤 유형의 내용이 존재하는가
  • 기사의 대상 고객
  • 게시 일정을 표시합니다.
  • 이 보고서들은 우리가 이전에 발표한 글을 둘러싼'누구, 무엇, 언제'전략을 더욱 깊이 있게 이해할 것이다.

    응용 프로그램 설정


    우선, Dash, SDK 및 종속성 설치가 필요합니다. 에서 이 작업을 수행하는 것이 좋습니다.터미널 실행 중:
  • pip install dash
  • pip install kontent_delivery
  • pip install pandas
  • 또는 pip install -r /path/to/requirements.txt를 사용하여 이 virtual environment를 다운로드하고 설치할 수 있습니다.
    연습이 끝나면 다음과 같은 파일 구조가 나타납니다.
    kontent-dash-blog (root)/
        reports/
            article_timeline.py
            content_types.py
            personas.py
        report_dashboard.py
        requirements.txt
    

    요구txt Dash 및 Kontent 초기화


    요구 사항이 설치되면 다음이 필요합니다.
  • Dash
  • 실행을 위한 플라스크 프로그램 설정
  • 사용 Kontent SDK 제공 클라이언트 초기화
  • 세 가지 보고서를 구축하는 방법을 설정합니다
  • Report dashboard라는 파일에서 이 작업을 수행합니다.py를 만들고 프로젝트 루트 디렉터리에 생성합니다.
    import dash
    import flask
    from kontent_delivery.client import DeliveryClient
    # report methods
    from reports.content_types import build_types_chart
    from reports.personas import build_personas_pie
    from reports.article_timeline import build_post_timeline
    
    external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']
    
    # dash
    server = flask.Flask(__name__)
    app = dash.Dash(server=server, external_stylesheets=external_stylesheets)
    
    # kontent
    client = DeliveryClient("your_Kontent_Project_ID")
    
    # custom methods to create reports
    bar = build_types_chart(client)
    pie = build_personas_pie(client)
    timeline = build_post_timeline(client)
    

    Kontent 프로젝트 ID 보고서 1: 컨텐츠 유형에 대한 막대 차트 표시


    이 차트에서 Kontent API를 호출하여 주어진 유형의 컨텐츠 유형을 계산합니다.파일 내용 형식을 만들 것입니다.디렉토리의py를 보고합니다.
    import plotly.express as px
    
    def build_types_chart(client):
        type_response = client.get_content_types()
        item_response = client.get_content_items()
    
        types = {}
    
        # add Kontent type counts to a dictionary
        for content_type in type_response.types:
            types[content_type.codename] = 0
    
        # increment content type count per item of respective type
        for item in item_response.items:
            types[item.content_type] += 1 
    
        data = {"content types":types.keys(), "count": types.values()}
    
        fig = px.bar(data, x="content types", y="count")
    
        return fig
    
    build types chart 방법에서는 내용 유형의 코드 이름에 따라 키 값 쌍을 만들고 이 유형의 발표 항목의 수량을 계산합니다.이 데이터를 사용하면 Plotly Express를 사용하여 막대 그래프를 만들고 Dash 애플리케이션으로 되돌려줍니다.

    보고서 2: 글의 인물 캐릭터를 보여주는 떡그림


    우리의 두 번째 도표에서 우리는 우리의 문장 내용 목표 인물 역할의 백분율을 보여주고 싶다.가령 우리가 알 수 있듯이 글의 내용 유형은personas라는 를 사용했다.
    taxonomy group
    파일 역할을 만들겠습니다.디렉토리의py를 보고합니다.
    from kontent_delivery.builders.filter_builder import Filter
    import plotly.express as px
    
    def build_personas_pie(client):
        # only return "article" content items
        item_response = client.get_content_items(
            Filter("system.type", "[eq]", "article")
        )
    
        # get the taxonomy group that articles use
        personas_response = client.get_taxonomy("personas")
        chart_personas = {}
    
        # identify personas to be counted
        def get_taxonomy_terms(terms):
            for persona in terms:
                chart_personas[persona.name] = 0
                if persona.terms:
                    get_taxonomy_terms(persona.terms)
    
    
        get_taxonomy_terms(personas_response.terms)
    
        # increment persona count per item
        for item in item_response.items:
            for persona in item.elements.personas.value:
                chart_personas[persona.name] += 1 
    
        data = {"personas":chart_personas.keys(), "count": chart_personas.values()}
    
        fig = px.pie(data, names="personas", values="count",
                    title='Assigned article personas')
        return fig
    
    build personas pie 방법에서 모든 글의 내용 항목을 추출합니다.그런 다음 Personas taxonomy 그룹에 존재하는 분류 용어의 이름과 특정 용어로 표시된 항목의 수에 따라 키 값 쌍을 만듭니다.이 데이터를 사용하여 Plotly Express를 사용하여 원형 차트를 만들고 Dash 애플리케이션으로 되돌립니다.

    보고서 3: 게시 일자의 타임라인을 표시합니다.


    이 글들이 언제 발표될지에 대한 정보는 우리의 내용 전략이 이전에 무엇인지, 또는 시간에 따라 어떻게 변화하는지에 대한 배경 정보를 더 많이 제공할 수 있다.기사에 게시 날짜 요소가 있다고 가정하면 타임라인을 만들 수 있습니다.

    파일 글의 타임라인을 만들 것입니다.디렉토리의py를 보고합니다.
    from kontent_delivery.builders.filter_builder import Filter
    import pandas as pd
    import plotly.express as px
    
    def build_post_timeline(client):
        # only return "article" content items
        item_response = client.get_content_items(
            Filter("system.type", "[eq]", "article")
        )
    
        # setup two arrays for Plotly scatter
        chart_items = []
        chart_post_date = []
    
        # populate arrays with respective item name and post date
        for item in item_response.items:
            chart_items.append(item.name)
            chart_post_date.append(item.elements.post_date.value)
    
        df = pd.DataFrame(dict(item=chart_items, post_date=chart_post_date))
    
        # use column names of df for the different parameters x, y, ...
        fig = px.scatter(df, x="post_date", y="item",
                        title="Article post timeline",
                        labels={"Post Date":"Date item posted"} # customize axis label
                        )
    
        return fig
    
    다른 방법과 마찬가지로 Kontent에서 글 항목을 검색하지만, 이 예에서는 두 개의 그룹을 하나의 사전으로 변환해서 전달하는 추가 절차를 사용합니다.이것은 단지 Plotly 문서의 pandas DataFrame 와 일치하기 위해서입니다.
    basic dot plot example

    모든 컨텐츠를 하나의 탭 보고서로 묶기


    모든 시각 보조 도구를 보고서에 통합하고 Dash로 상호작용을 추가할 때가 되었다.리포트 대시보드를 만들었습니다.py 파일은 Kontent 클라이언트와 차트 구성 방법을 추가합니다. 이제 상호 작용이 있는 레이아웃을 추가합니다.
    # ... other imports from before
    # add these for components:
    import dash_html_components as html
    import dash_core_components as dcc
    from dash.dependencies import Input, Output
    
    external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']
    
    # dash
    server = flask.Flask(__name__)
    app = dash.Dash(server=server, external_stylesheets=external_stylesheets)
    
    # kontent
    client = DeliveryClient(config.project_id, options=config.delivery_options)
    
    bar = build_types_chart(client)
    pie = build_personas_pie(client)
    timeline = build_post_timeline(client)
    
    # -- end of "Dash and Kontent Initialization" code --
    
    # -- start of "Tying it all together..." code --
    
    # adding the dash layout
    app.layout = html.Div([
        # dash tabs component that wraps individual tabs
        dcc.Tabs(id='tabs-example', value='tab-1', children=[
            dcc.Tab(label='Content Types', value='tab-1'),
            dcc.Tab(label='Article Personas', value='tab-2'),
            dcc.Tab(label='Article Post Timeline', value='tab-3'),
        ]),
        # div used as a canvas to show reports
        html.Div(id='tabs-example-content')
    ])
    
    # onclick events that call our chart building methods
    @app.callback(Output('tabs-example-content', 'children'),
                  Input('tabs-example', 'value'))
    def render_content(tab):
        if tab == 'tab-1':
            return html.Div([
                dcc.Graph(figure=bar)
            ])
        elif tab == 'tab-2':
            return html.Div([
                 dcc.Graph(figure=pie)
            ])
        elif tab == 'tab-3':
            return html.Div([
                 dcc.Graph(figure=timeline)
            ])
    
    # run the application when report_dashboard.py is called
    if __name__ == '__main__':
        app.run_server(debug=True)
    
    보고서의 마지막 코드 파일에서 우리는 를 사용하여 간단한 이중 구역 레이아웃을 만들었다.첫 번째 div에는 대시 "Tab"구성 요소가 포함되어 있으며 그래프 사이를 전환하는 데 사용되고 두 번째 div는 캔버스로 우리가 생성한 그래프를 표시합니다.
    Dash's core HTML components
    배치에 따라 우리는 를 사용하여 다른 도형을 생성하는데 어떤 옵션을 클릭하느냐에 따라 달라진다.Dash 핵심 구성 요소에 대한 자세한 내용은 차트 및 탭을 참조하십시오Dash callbacks.
    터미널에서 report_dashboard.py 를 실행하고 새로 만든 보고서 프로그램에 로컬 호스트 서버를 시작하는 Dash를 볼 수 있습니다.터미널의 링크를 따라가라, 봐라!사용자 정의 대화식 보고서를 무료로 만들었습니다.
    Dash documentation here 또는 live hosted example를 볼 수 있습니다.

    GitHub의 전체 소스 코드 결론


    본 논문에서, 우리는 Dash가 무엇인지, 그리고 그것을headless CMS 데이터에서 상호작용 보고서를 만드는 방법에 대해 토론했다.이제 Python 지식과 Dash 같은 개원 프레임워크가 생겼으니, 머리 없는 CMS 보고서를 놓칠 필요가 없다는 것을 알게 되었다.
    대시와 헤드리스의 샘플을 더 원하십니까?이것 을 보고 모듈화된 내용도를 만드세요.
    당신은 문장 중의 견본에 대해 의견이 있습니까?Dash + Kontent app .

    좋은 웹페이지 즐겨찾기