Python 웹 앱에서 JavaScript 보고 도구를 사용하는 방법

ActiveReportsJS는 서버 종속성이 없는 100% 클라이언트 측 보고 도구입니다. 이는 Python 애플리케이션을 포함하여 모든 웹 서버와 함께 ActiveReportsJS를 사용할 수 있음을 의미합니다. 이 기사에는 ActiveReportsJS를 Python 웹 애플리케이션과 통합하는 방법에 대한 간단하면서도 철저한 자습서가 포함되어 있습니다. 마지막으로 다음을 수행할 수 있습니다.
  • Create a Python web application serving a JSON API using the Django framework
  • Initialize the data from a CSV file
  • Configure JSON API endpoints
  • Create an ActiveReportsJS report to visualize the data from the JSON API
  • Create a static HTML page to display the report in the report viewer

  • 전제 조건



    다음 내용은 컴퓨터에 Python과 Django가 설치되어 있다고 가정합니다. 공식Django website에서 이를 수행하는 방법에 대한 정보를 찾을 수 있습니다. 장치에 ActiveReportsJS도 설치되어 있으면 가장 좋습니다. 가지고 있지 않은 경우 ActiveReportsJS website에서 얻을 수 있습니다.

    장고 애플리케이션 만들기

    For this tutorial, we will use the Django web framework. To create a new Django application, run the following commands from the terminal or the command prompt.

    django-admin startproject ReportingOnDjango
    cd ReportingOnDjango
    py manage.py startapp sales_api
    

    Then open the newly created ReportingOnDjango directory in your favorite code editor, such as Visual Studio Code. Open the settings.py file in the ReportingOnDjango folder and add the 'sales_api.apps.SalesApiConfig' item into the INSTALLED_APPS array so that it looks like the following:

    INSTALLED_APPS = [
        'sales_api.apps.SalesApiConfig',
        'django.contrib.admin',
        'django.contrib.auth',
        'django.contrib.contenttypes',
        'django.contrib.sessions',
        'django.contrib.messages',
        'django.contrib.staticfiles',
    ]
    

    JSON API용 데이터 모델 생성



    E for Excel 웹사이트에서 다운로드할 수 있는 판매 데이터 세트를 사용합니다. 100개 레코드부터 5백만 레코드까지 다양한 크기의 데이터 세트를 제공합니다. 단순화를 위해 100개의 레코드가 있는 첫 번째 데이터 세트를 사용합니다.
    데이터 세트에는 많은 필드가 있지만 이 자습서에서는 그 중 몇 개만 사용합니다. JSON API용 데이터 모델을 만들려면 sales_api/models.py의 내용을 다음으로 바꿉니다.

    from django.db import models
    
    class Sale(models.Model):
        region = models.CharField(max_length=200)
        itemType = models.CharField(max_length=200)
        unitsSold = models.IntegerField()
    

    터미널 또는 명령 프롬프트에서 다음 명령을 실행합니다.

    py manage.py makemigrations sales_api
    python manage.py migrate​
    

    애플리케이션 데이터 추가

    We will use the Sales dataset that you can download from the  E for Excel 웹사이트. 100개 레코드부터 5백만 레코드까지 다양한 크기의 데이터 세트를 제공합니다. 단순화를 위해 100개의 레코드가 있는 첫 번째 데이터 세트를 사용합니다.

    아카이브에서 애플리케이션의 루트 디렉터리로 데이터를 다운로드하고 압축을 풉니다.

    터미널 또는 명령 프롬프트에서 python manage.py 셸 명령어를 실행하여 대화형 Python 셸을 시작하고 다음 명령어를 입력합니다.

    from sales_api.models import Sale
    
    import csv
    
    with open('100 Sales Records.csv', newline='') as csvfile:
         reader = csv.reader(csvfile, delimiter=',')
         next(reader)
         for row in reader:
             Sale.objects.create(region=row[0], itemType=row[2], unitsSold=row[8])​
    

    JSON API 끝점 구성

    The easiest way to configure the JSON API endpoint that returns the list of sales is to use the Django REST Framework. You can install it by running the pip install djangorestframework command in the terminal or command prompt and then adding the 'rest_framework' item into the INSTALLED_APPS array in the ReportingOnDjango\settings.py file. 

    Add the 'serializers.py' file into the sales_api folder and replace its content with the following:

    from rest_framework import serializers
    
    from .models import Sale
    
    class SaleSerializer(serializers.HyperlinkedModelSerializer):
        class Meta:
            model = Sale
            fields = ('region', 'itemType', 'unitsSold')
    

    Then replace the content of the view.py file in the sales_api folder with the following:

    from rest_framework import viewsets
    
    from .serializers import SaleSerializer
    from .models import Sale
    
    class SaleViewSet(viewsets.ModelViewSet):
        queryset = Sale.objects.all()
        serializer_class = SaleSerializer
    

    To server static files, configure the STATIC_ROOT variable in the settings.py file:

    STATIC_ROOT = BASE_DIR / 'sales_api/static/',
    

    Finally, replace the content of the 'urls.py' file in the ReportingOnDjango folder with the following:

    from django.contrib import admin
    from django.urls import include, path
    from rest_framework import routers
    from sales_api import views
    
    router = routers.DefaultRouter()
    router.register(r'sales', views.SaleViewSet)
    
    urlpatterns = [
        path('api/', include(router.urls)),
        path('admin/', admin.site.urls),
    ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
    
    Run the server using the py manage.py runserver 8080 and open the  http://localhost:8080/api/sales URL. 위에 표시된 단계를 따르면 페이지에 판매 목록이 표시됩니다.

    ActiveReportsJS 보고서 만들기

    Let's now create a report that visualizes the data from the JSON API.

    In the  Standalone Report Designer Application 파일 메뉴를 클릭하고 새로 생성된 보고서에 대한 연속 페이지 레이아웃 템플릿을 선택합니다.

    속성 관리자의 Data panel을 열고 추가 버튼을 클릭합니다.

    데이터 소스 편집기 대화상자에서 ENDPOINT 입력란에 http://localhost:8080/api/sales을 입력하고 변경사항 저장 버튼을 클릭합니다.



    데이터 패널에서 DataSource 근처의 + 아이콘을 클릭합니다.

    Data Set Editor 대화상자에서 NAME 필드에 Sales를 입력하고 JSON Path 필드에 $.*를 입력합니다.

    Validate 버튼을 클릭하고 DataBase Fields 섹션에 [3개 항목] 텍스트가 표시되는지 확인한 다음 Save Changes 버튼을 클릭합니다.



    툴바의 왼쪽에 있는 햄버거 메뉴를 사용하여 toolbox을 확장합니다.

    도구 상자에서 보고서 페이지 영역의 왼쪽 상단으로 차트 항목을 드래그 앤 드롭합니다. 차트 마법사 대화상자가 나타납니다. Bar 유형을 선택하고 첫 화면에서 Next 버튼을 클릭합니다.

    대화상자의 두 번째 화면에서 다음 이미지와 같이 데이터를 구성하고 다음 버튼을 클릭합니다.



    세 번째 화면에서 마침 버튼을 클릭합니다.

    보고서 페이지의 전체 너비를 채우도록 차트 보고서 항목의 크기를 조정합니다. 차트 범례를 클릭하여 해당 속성을 속성 패널에 로드하고 방향 속성을 가로로, 위치 속성을 아래쪽으로 설정합니다.

    File 메뉴를 클릭하고 애플리케이션의 'ReportingOnDjango\sales_api\static' 폴더에 새로 만든 보고서를 SalesReport.rdlx-json이라는 이름으로 저장합니다.

    보고서를 표시할 정적 HTML 페이지 만들기

    In the "ReportingOnDjango\sales_api\static"folder of the application, create the report.html file and replace its content with the following code:

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Sales Report</title>
        <link
        rel="stylesheet"
        href="https://cdn.grapecity.com/activereportsjs/3.latest/styles/ar-js-ui.css"
        type="text/css"
      />
      <link
        rel="stylesheet"
        href="https://cdn.grapecity.com/activereportsjs/3.latest/styles/ar-js-viewer.css"
        type="text/css"
      />
      <script src="https://cdn.grapecity.com/activereportsjs/3.latest/dist/ar-js-core.js"></script>
      <script src="https://cdn.grapecity.com/activereportsjs/3.latest/dist/ar-js-viewer.js"></script>
      <script src="https://cdn.grapecity.com/activereportsjs/3.latest/dist/ar-js-pdf.js"></script>
      <style>
        #viewer-host {
          width: 100%;
          height: 100vh;
        }
      </style>      
    </head>
    
    <body>
        <div id="viewer-host"></div>
        <script>
            var viewer = new ActiveReports.Viewer("#viewer-host");
            viewer.open('SalesReport.rdlx-json');
          </script>  
    </body>
    </html>
    
    Open the  http://localhost:8080/static/report.html 브라우저에서 보고서를 볼 수 있습니다. 단계를 올바르게 따른 경우 JSON API 데이터를 표시하는 보고서가 표시되어야 합니다.

    좋은 웹페이지 즐겨찾기