Sử dụng bộ sưu tập để sắp xếp ngăn nắp các trang
Lưu và phân loại nội dung dựa trên lựa chọn ưu tiên của bạn.
Google có một thư viện Python nguồn mở giúp tạo các đối tượng DataTable
để sử dụng bằng cách trực quan hoá. Bạn có thể dùng thư viện này để tạo DataTable bằng Python và xuất tệp đó ở một trong 3 định dạng sau:
Chuỗi JSON – Nếu đang lưu trữ trang lưu trữ hình ảnh sử dụng dữ liệu của mình, thì bạn có thể tạo một chuỗi JSON để truyền vào hàm khởi tạo DataTable để điền hình ảnh đó.
Phản hồi JSON – Nếu không lưu trữ trang lưu trữ hình ảnh trực quan và chỉ muốn đóng vai trò là nguồn dữ liệu cho hình ảnh bên ngoài, thì bạn có thể tạo một chuỗi phản hồi JSON hoàn chỉnh có thể được trả về nhằm phản hồi một yêu cầu dữ liệu.
Chuỗi JavaScript – Bạn có thể xuất bảng dữ liệu dưới dạng một chuỗi bao gồm một số dòng mã JavaScript để tạo và điền sẵn dữ liệu từ bảng Python vào đối tượng
google.visualization.DataTable. Sau đó, bạn có thể chạy JavaScript này trong một công cụ để tạo và điền đối tượng google.visualization.DataTable. Tính năng này thường chỉ dùng để gỡ lỗi.
Nhập thư viện gviz_api.py từ đường liên kết ở trên và tạo thực thể cho lớp gviz_api.DataTable. Lớp này sẽ nhận hai tham số: một giản đồ bảng sẽ mô tả định dạng của dữ liệu trong bảng và dữ liệu không bắt buộc để điền vào bảng. Bạn có thể thêm dữ liệu vào lúc khác nếu muốn
hoặc ghi đè toàn bộ dữ liệu, nhưng không xoá từng hàng riêng lẻ hoặc xoá
giản đồ bảng.
2. Mô tả giản đồ bảng của bạn
Giản đồ bảng được chỉ định bằng tham số table_description được truyền vào hàm khởi tạo. Bạn không thể thay đổi tên này sau này. Giản đồ mô tả tất cả cột trong bảng: loại dữ liệu của mỗi cột, mã nhận dạng và một nhãn không bắt buộc.
Mỗi cột được mô tả bằng một bộ dữ liệu: (mã nhận dạng [,data_type [,label
[,custom_properties]]]).
Mã nhận dạng – Mã nhận dạng chuỗi được dùng để xác định cột. Có thể bao gồm dấu cách.
Mã nhận dạng cho mỗi cột phải là duy nhất.
data_type – [không bắt buộc] Phần mô tả chuỗi của loại dữ liệu Python của dữ liệu trong cột đó. Bạn có thể tìm thấy danh sách các loại dữ liệu được hỗ trợ trong phương thức SingleValueToJS(). Ví dụ: "string" và "boolean".
Nếu không được chỉ định, giá trị mặc định sẽ là "chuỗi".
label – Tên thân thiện với người dùng của cột, có thể xuất hiện dưới dạng một phần của hình ảnh trực quan. Nếu không được chỉ định, giá trị mã nhận dạng sẽ được sử dụng.
custom_properties – Từ điển {String:String} của các thuộc tính
cột tùy chỉnh.
Giản đồ bảng là một tập hợp các bộ dữ liệu mô tả cột. Mọi thành phần của danh sách, khoá từ điển hoặc giá trị từ điển phải là một tập hợp khác hoặc một bộ mã mô tả. Bạn có thể sử dụng bất kỳ tổ hợp từ điển hoặc danh sách nào, nhưng cuối cùng mọi khoá, giá trị hoặc thành phần đều phải đánh giá thành một bộ mô tả. Sau đây là một số ví dụ.
Danh sách các cột: [('a', 'number'), ('b', 'string')]
Dictionary of lists: {('a', 'number'): [('b', 'number'), ('c', 'string')]}
Dictionary of dictionaries: {('a', 'number'): {'b': 'number', 'c': 'string'}}
Và cứ tiếp tục như vậy, với bất kỳ mức độ lồng nhau nào.
3. Điền dữ liệu
Để thêm dữ liệu vào bảng, hãy xây dựng cấu trúc của các phần tử dữ liệu theo cấu trúc hoàn toàn giống như giản đồ bảng. Vì vậy, nếu giản đồ của bạn là một danh sách, dữ liệu phải là một danh sách:
Một hàng trong bảng là một mục chứa dữ liệu và giản đồ tương ứng. Ví dụ: dưới đây là cách áp dụng giản đồ của danh sách hai cột cho 2 hàng dữ liệu.
Schema:[(color),(shape)]
/ \
Data: [["blue", "square"], ["red", "circle"]]
Table:
ColorShape
blue square
red circle
Xin lưu ý rằng các khoá trong từ điển ở đây sẽ đánh giá dữ liệu cột. Bạn có thể tìm thấy các ví dụ phức tạp hơn trong tài liệu về phương thức AttachData() trong đoạn mã. Mục đích của việc cho phép lồng ghép phức tạp như vậy là để bạn có thể sử dụng cấu trúc dữ liệu Python phù hợp với nhu cầu của mình.
4. Xuất dữ liệu
Định dạng đầu ra phổ biến nhất là JSON, vì vậy, bạn có thể sẽ sử dụng hàm ToJsonResponse()
để tạo dữ liệu cần trả về. Tuy nhiên, nếu đang phân tích cú pháp yêu cầu nhập và hỗ trợ nhiều định dạng đầu ra, thì bạn có thể gọi bất kỳ phương thức đầu ra nào khác để trả về các định dạng khác, bao gồm cả giá trị phân tách bằng dấu phẩy, giá trị được phân tách bằng ký tự tab và JavaScript. JavaScript thường chỉ được dùng để gỡ lỗi. Hãy xem bài viết Triển khai nguồn dữ liệu để tìm hiểu cách xử lý yêu cầu nhằm lấy định dạng phản hồi ưu tiên.
Ví dụ về cách sử dụng
Dưới đây là một số ví dụ minh hoạ cách sử dụng nhiều định dạng đầu ra.
Ví dụ về ToJSon và ToJS
#!/usr/bin/python
import gviz_api
page_template = """
<html>
<script src="https://www.gstatic.com/charts/loader.js"></script>
<script>
google.charts.load('current', {packages:['table']});
google.charts.setOnLoadCallback(drawTable);
function drawTable() {
%(jscode)s
var jscode_table = new google.visualization.Table(document.getElementById('table_div_jscode'));
jscode_table.draw(jscode_data, {showRowNumber: true});
var json_table = new google.visualization.Table(document.getElementById('table_div_json'));
var json_data = new google.visualization.DataTable(%(json)s, 0.6);
json_table.draw(json_data, {showRowNumber: true});
}
</script>
<body>
<H1>Table created using ToJSCode</H1>
<div id="table_div_jscode"></div>
<H1>Table created using ToJSon</H1>
<div id="table_div_json"></div>
</body>
</html>
"""
def main():
# Creating the data
description = {"name": ("string", "Name"),
"salary": ("number", "Salary"),
"full_time": ("boolean", "Full Time Employee")}
data = [{"name": "Mike", "salary": (10000, "$10,000"), "full_time": True},
{"name": "Jim", "salary": (800, "$800"), "full_time": False},
{"name": "Alice", "salary": (12500, "$12,500"), "full_time": True},
{"name": "Bob", "salary": (7000, "$7,000"), "full_time": True}]
# Loading it into gviz_api.DataTable
data_table = gviz_api.DataTable(description)
data_table.LoadData(data)
# Create a JavaScript code string.
jscode = data_table.ToJSCode("jscode_data",
columns_order=("name", "salary", "full_time"),
order_by="salary")
# Create a JSON string.
json = data_table.ToJSon(columns_order=("name", "salary", "full_time"),
order_by="salary")
# Put the JS code and JSON string into the template.
print "Content-type: text/html"
print
print page_template % vars()
if __name__ == '__main__':
main()
Ví dụ về ToJSonResponse
Máy khách từ xa sử dụng JSonResponse trong một yêu cầu dữ liệu.
[[["Dễ hiểu","easyToUnderstand","thumb-up"],["Giúp tôi giải quyết được vấn đề","solvedMyProblem","thumb-up"],["Khác","otherUp","thumb-up"]],[["Thiếu thông tin tôi cần","missingTheInformationINeed","thumb-down"],["Quá phức tạp/quá nhiều bước","tooComplicatedTooManySteps","thumb-down"],["Đã lỗi thời","outOfDate","thumb-down"],["Vấn đề về bản dịch","translationIssue","thumb-down"],["Vấn đề về mẫu/mã","samplesCodeIssue","thumb-down"],["Khác","otherDown","thumb-down"]],["Cập nhật lần gần đây nhất: 2024-07-10 UTC."],[[["\u003cp\u003eGoogle's open-sourced Python library, \u003ccode\u003egviz_api\u003c/code\u003e, enables the creation of \u003ccode\u003eDataTable\u003c/code\u003e objects for visualizations, supporting JSON string, JSON response, and JavaScript string output formats.\u003c/p\u003e\n"],["\u003cp\u003eThe library requires a table schema definition outlining the data types, IDs, and labels for each column within the \u003ccode\u003eDataTable\u003c/code\u003e.\u003c/p\u003e\n"],["\u003cp\u003eUsers populate the \u003ccode\u003eDataTable\u003c/code\u003e with data structured according to the defined schema, using lists or dictionaries for rows and columns.\u003c/p\u003e\n"],["\u003cp\u003e\u003ccode\u003egviz_api\u003c/code\u003e offers functions like \u003ccode\u003eToJsonResponse()\u003c/code\u003e to format data for visualization consumption, with JSON being the most common format.\u003c/p\u003e\n"],["\u003cp\u003eThe library facilitates data exchange between Python and Google Charts, enabling dynamic and interactive visualizations.\u003c/p\u003e\n"]]],[],null,["# Data Source Python Library\n\nGoogle has open-sourced a Python library that creates `DataTable`\nobjects for consumption by visualizations. This library can be used to create\na `DataTable` in Python, and output it in any of three formats:\n\n- **JSON string** -- If you are hosting the page that hosts the visualization that uses your data, you can generate a JSON string to pass into a `DataTable` constructor to populate it.\n- **JSON response**-- If you do not host the page that hosts the visualization, and just want to act as a data source for external visualizations, you can create a complete JSON response string that can be returned in response to a data request.\n- **JavaScript string** -- You can output the data table as a string that consists of several lines of JavaScript code that will create and populate a [google.visualization.DataTable](/chart/interactive/docs/reference#DataTable) object with the data from your Python table. You can then run this JavaScript in an engine to generate and populate the `google.visualization.DataTable` object. This is typically used for debugging only.\n\nThis document assumes that you understand basic [Python\nprogramming](http://www.python.org), and have read the introductory\nvisualization documentation for [creating a visualization](/chart/interactive/docs/quick_start) and [using\na visualization](/chart/interactive/docs). \n[The Python library is available here](https://github.com/google/google-visualization-python).\n\nContents\n--------\n\n- [How to Use the Library](#howtouse)\n - [Create a gviz_api.DataTable\n object](#createinstance)\n - [Describe your table schema](#describeschema)\n - [Populate your data](#populatedata)\n - [Output your data](#outputdata)\n- [Example Usage](#exampleusage)\n - [ToJSon and ToJS Example](#tojsonexample)\n - [ToJSonResponse Example](#tojsonresponseexample)\n\nHow to Use the Library\n----------------------\n\nHere are the basic steps, in more detail:\n\n### 1. Create\na `gviz_api.DataTable` object\n\nImport the gviz_api.py library from the link above and instantiate\nthe `gviz_api.DataTable` class. The class takes two parameters:\na table schema, which will describe the format of the data in the table, and\noptional data to populate the table with. You can add data later, if you like,\nor completely overwrite the data, but not remove individual rows, or clear\nout the table schema.\n\n### 2. Describe your table schema\n\nThe table schema is specified by the `table_description` parameter\npassed into the constructor. You cannot change it later. The schema describes\nall the columns in the table: the data type of each column, the ID, and an\noptional label.\n\nEach column is described by a tuple: (*ID* \\[*,data_type* \\[*,label*\n\\[*,custom_properties*\\]\\]\\]).\n\n- *ID* - A string ID used to identify the column. Can include spaces. The ID for each column must be unique.\n- *data_type* - \\[*optional*\\] A string descriptor of the Python data type of the data in that column. You can find a list of supported data types in the SingleValueToJS() method. Examples include \"string\" and \"boolean\". If not specified, the default is \"string.\"\n- *label* - A user-friendly name for the column, which might be displayed as part of the visualization. If not specified, the ID value is used.\n- *custom_properties* - A {String:String} dictionary of custom column properties.\n\nThe table schema is a collection of column descriptor tuples. Every list member,\ndictionary key or dictionary value must be either another collection or a descriptor\ntuple. You can use any combination of dictionaries or lists, but every key,\nvalue, or member must eventually evaluate to a descriptor tuple. Here are some\nexamples.\n\n- List of columns: \\[('a', 'number'), ('b', 'string')\\]\n- Dictionary of lists: {('a', 'number'): \\[('b', 'number'), ('c', 'string')\\]}\n- Dictionary of dictionaries: {('a', 'number'): {'b': 'number', 'c': 'string'}}\n- And so on, with any level of nesting.\n\n### 3. Populate your data\n\nTo add data to the table, build a structure of data elements in the exact\nsame structure as the table schema. So, for example, if your schema is a list,\nthe data must be a list:\n\n- schema: \\[(\"color\", \"string\"), (\"shape\", \"string\")\\]\n- data: \\[\\[\"blue\", \"square\"\\], \\[\"red\", \"circle\"\\]\\]\n\nIf the schema is a dictionary, the data must be a dictionary:\n\n- schema: {(\"rowname\", \"string\"): \\[(\"color\", \"string\"), (\"shape\", \"string\")\\] }\n- data: {\"row1\": \\[\"blue\", \"square\"\\], \"row2\": \\[\"red\", \"circle\"\\]}\n\nOne table row is a section of corresponding data and schema. For example,\nhere's how a schema of a list of two columns is applied to two rows of data. \n\n```\nSchema:[(color),(shape)]\n / \\ \nData: [[\"blue\", \"square\"], [\"red\", \"circle\"]]\n\nTable: \n Color Shape\n blue square\n red circle\n```\n\nNote that the\ndictionary keys here evaluate to column data. You can find more complex examples\nin the AppendData() method documentation in the code. The purpose of allowing\nsuch complex nesting is to let you use a Python data structure appropriate\nto your needs.\n\n### 4. Output your data\n\nThe most common output format is JSON, so you will probably use the `ToJsonResponse()`\nfunction to create the data to return. If, however, you are parsing the\ninput request and supporting different output formats, you can call any of\nthe other output methods to return other formats, including comma-separated\nvalues, tab-separated values, and JavaScript. JavaScript is typically only\nused for debugging. See\n[Implementing a Data Source](/chart/interactive/docs/dev/implementing_data_source) to learn\nhow to process a request to obtain the preferred response format.\n\nExample Usage\n-------------\n\nHere are some examples demonstrating how to use the various output formats.\n\n### ToJSon and ToJS Example\n\n```\n#!/usr/bin/python\n\nimport gviz_api\n\npage_template = \"\"\"\n\u003chtml\u003e\n \u003cscript src=\"https://www.gstatic.com/charts/loader.js\"\u003e\u003c/script\u003e\n \u003cscript\u003e\n google.charts.load('current', {packages:['table']});\n\n google.charts.setOnLoadCallback(drawTable);\n function drawTable() {\n %(jscode)s\n var jscode_table = new google.visualization.Table(document.getElementById('table_div_jscode'));\n jscode_table.draw(jscode_data, {showRowNumber: true});\n\n var json_table = new google.visualization.Table(document.getElementById('table_div_json'));\n var json_data = new google.visualization.DataTable(%(json)s, 0.6);\n json_table.draw(json_data, {showRowNumber: true});\n }\n \u003c/script\u003e\n \u003cbody\u003e\n \u003cH1\u003eTable created using ToJSCode\u003c/H1\u003e\n \u003cdiv id=\"table_div_jscode\"\u003e\u003c/div\u003e\n \u003cH1\u003eTable created using ToJSon\u003c/H1\u003e\n \u003cdiv id=\"table_div_json\"\u003e\u003c/div\u003e\n \u003c/body\u003e\n\u003c/html\u003e\n\"\"\"\n\ndef main():\n # Creating the data\n description = {\"name\": (\"string\", \"Name\"),\n \"salary\": (\"number\", \"Salary\"),\n \"full_time\": (\"boolean\", \"Full Time Employee\")}\n data = [{\"name\": \"Mike\", \"salary\": (10000, \"$10,000\"), \"full_time\": True},\n {\"name\": \"Jim\", \"salary\": (800, \"$800\"), \"full_time\": False},\n {\"name\": \"Alice\", \"salary\": (12500, \"$12,500\"), \"full_time\": True},\n {\"name\": \"Bob\", \"salary\": (7000, \"$7,000\"), \"full_time\": True}]\n\n # Loading it into gviz_api.DataTable\n data_table = gviz_api.DataTable(description)\n data_table.LoadData(data)\n\n # Create a JavaScript code string.\n jscode = data_table.ToJSCode(\"jscode_data\",\n columns_order=(\"name\", \"salary\", \"full_time\"),\n order_by=\"salary\")\n # Create a JSON string.\n json = data_table.ToJSon(columns_order=(\"name\", \"salary\", \"full_time\"),\n order_by=\"salary\")\n\n # Put the JS code and JSON string into the template.\n print \"Content-type: text/html\"\n print\n print page_template % vars()\n\n\nif __name__ == '__main__':\n main()\n```\n\n### ToJSonResponse\nExample\n\nJSonResponse is used by a remote client in a data request. \n\n```\n#!/usr/bin/python\n\nimport gviz_api\n\ndescription = {\"name\": (\"string\", \"Name\"),\n \"salary\": (\"number\", \"Salary\"),\n \"full_time\": (\"boolean\", \"Full Time Employee\")}\ndata = [{\"name\": \"Mike\", \"salary\": (10000, \"$10,000\"), \"full_time\": True},\n {\"name\": \"Jim\", \"salary\": (800, \"$800\"), \"full_time\": False},\n {\"name\": \"Alice\", \"salary\": (12500, \"$12,500\"), \"full_time\": True},\n {\"name\": \"Bob\", \"salary\": (7000, \"$7,000\"), \"full_time\": True}]\n\ndata_table = gviz_api.DataTable(description)\ndata_table.LoadData(data)\nprint \"Content-type: text/plain\"\nprint\nprint data_table.ToJSonResponse(columns_order=(\"name\", \"salary\", \"full_time\"),\n order_by=\"salary\")\n```"]]