顯示具有 CKAN 標籤的文章。 顯示所有文章
顯示具有 CKAN 標籤的文章。 顯示所有文章

2022年5月8日 星期日

CAKN 偵錯: flask_debugtoolbar

  1. 啟動 Python 虛擬環境
    . /usr/lib/ckan/default/bin/activate
  2. 安裝 flask_debugtoolbar
    pip install flask_debugtoolbar
  3. 開啟偵錯模式
    vi /etc/ckan/default/ckan.ini
    debug = true
  4. 重啟 CKAN
    sudo supervisorctl restart ckan-uwsgi:*
  • 若有錯檢視 uwsgi.ERR
    cat /etc/ckan/default/uwsgi.ERR


2022年5月6日 星期五

CKAN Templates Tutorial 9(v2.9): 存取自訂的 config 設定

http://docs.ckan.org/en/2.9/theming/templates.html#accessing-custom-config-settings-from-templates

template 裡的 app_globals 不是所有 CKAN config 設定都能存取,自訂的 config 設定無法取得,但透過 helper function 就可以。

參考:Using custom config settings in extensions。

延續 上個 CKAN templates CSS tutorial。

新增自訂 config 設定

如下 show_most_popular_groups 設定,決定首頁是否顯示最受歡迎群組。

修改 extension 根目錄下的 plugin.py,新增 helper function 存取自訂的 show_most_popular_groups 設定:

# encoding: utf-8


import ckan.plugins as plugins
import ckan.plugins.toolkit as toolkit
from ckan.common import config


def show_most_popular_groups():
    '''Return the value of the most_popular_groups config setting.

    To enable showing the most popular groups, add this line to the
    [app:main] section of your CKAN config file::

      ckan.example_theme.show_most_popular_groups = True

    Returns ``False`` by default, if the setting is not in the config file.

    :rtype: bool

    '''
    value = config.get('ckan.example_theme.show_most_popular_groups', False)
    value = toolkit.asbool(value)
    return value

略⋯⋯

class ExampleThemePlugin(plugins.SingletonPlugin):
    略⋯⋯

    def get_helpers(self):
        '''Register the most_popular_groups() function above as a template
        helper function.

        '''
        # Template helper function names should begin with the name of the
        # extension they belong to, to avoid clashing with functions from
        # other extensions.
        return {'example_theme_most_popular_groups': most_popular_groups,
                'example_theme_show_most_popular_groups':
                show_most_popular_groups,
                }

extension 加入的 config 設定名稱要以 extension 名稱開頭,以避免與其他 extension 或 CKAN 內建設定衝突(參考 Avoid name clashes)。

在 layout1.html 中呼叫自訂 helper function

修改 templates/home/layout1.html 如下:

{% ckan_extends %}

略⋯⋯

{# Show the most popular groups if the show_most_popular_groups config setting
   is True, otherwise call the super block. #}
{% block featured_organization %}
<p>example_theme_show_most_popular_groups: [{{h.example_theme_show_most_popular_groups()}}]</p>
  {% if h.example_theme_show_most_popular_groups() %}
    {% snippet 'snippets/example_theme_most_popular_groups.html' %}
  {% else %}
    {{ super() }}
  {% endif %}
{% endblock %}

修改 ckan.ini 設定

/etc/ckan/default/ckan.ini

[app:main]
## example_theme
ckan.example_theme.show_most_popular_groups = False

安裝

  1. 進入Python Virtual Environment: 
    . /usr/lib/ckan/default/bin/activate
  2. 切換目錄:
    cd /usr/lib/ckan/default/src/ckanext-example_theme
  3. 安裝 Plugin: 
    python setup.py develop
  4. 重啟 CKAN 服務:
    (production版) sudo supervisorctl restart ckan-uwsgi:*
    (develop版) ckan -c /etc/ckan/default/ckan.ini run


CKAN Templates Tutorial 8(v2.9): CSS class

http://docs.ckan.org/en/2.9/theming/templates.html#html-tags-and-css-classes

CKAN 使用的 CSS class 來自:

  1. Bootstrap 3.3.7
    這個版本 Bootstrap 的 HTML, CSS, JavaScript 都可在 CKAN 中使用
  2. CKAN 的 development primer page
    CKAN 網站下的 /testing/primer

調整 snippet 裡的 CSS class

修改 ckanext-example_theme/ckanext/example_theme/templates/snippets/example_theme_most_popular_groups.html 如下:

{#

Renders a list of the site's most popular groups.

groups - the list of groups to render

#}
<div class="box">
  <header class="module-heading">
    <h3>Most popular groups</h3>
  </header>
  <section class="module-content">
    <ul class="unstyled">
      {% for group in groups %}
      <li>
        <a href="{{ h.url_for('group_read', action='read', id=group.name) }}">
          <h3>{{ group.display_name }}</h3>
        </a>
        {% if group.description %}
          <p>
            {{ h.markdown_extract(group.description, extract_length=80) }}
          </p>
        {% else %}
          <p>{{ _('This group has no description') }}</p>
        {% endif %}
        {% if group.package_count %}
          <strong>{{ ungettext('{num} Dataset', '{num} Datasets', group.package_count).format(num=group.package_count) }}</strong>
        {% else %}
          <span>{{ _('0 Datasets') }}</span>
        {% endif %}
      </li>
    {% endfor %}
 </ul>
  <section>
</div>

以上加入:

  • 把程式碼放進
    • <div class="box">
    • <header class="module-heading">
    • <section class="module-content">
  • 用 Bootstrap 的 class="unstyled" 移除 <ul> 前的黑點

調整 layout1.html 的 CSS class

修改 ckanext-example_theme/ckanext/example_theme/templates/home/layout1.html 如下:

{% ckan_extends %}

{% block featured_group %}
  <div class="box">
    <header class="module-heading">
      <h3>Recent activity</h3>
    </header>
    <div class="module-content">
    <ul>
        {% for stream in h.recently_changed_packages_activity_stream(limit=4) %}
            <li>stream id: {{ stream.id }}</li>
        {% endfor %}
    </ul>
    </div>
  </div>

{% endblock %}

{% block featured_organization %}
  {% snippet 'snippets/example_theme_most_popular_groups.html',
             groups=h.example_theme_most_popular_groups()  %}
{% endblock %}


重新檢視網頁:






CKAN Templates Tutorial 7(v2.9): 自訂 snippet

http://docs.ckan.org/en/2.9/theming/templates.html#adding-your-own-template-snippets

延續 上個 CKAN templates snippet tutorial,plugin 只要在它的 templates/snippets 目錄下加檔案即可自訂 snippet。

以下撰寫一個 snippet 來顯示最受歡迎群組。


在 templates/snippets 目錄下新增 snippet

建立目錄 ckanext-example_theme/ckanext/example_theme/templates/snippets,並在其下加入一個檔案:example_theme_most_popular_groups.html ,內容如下:

{#

Renders a list of the site's most popular groups.

groups - the list of groups to render

#}
<h3>熱門群組(自訂snippet)</h3>
<ul>
  {% for group in groups %}
    <li>
      <a href="{{ h.url_for('group_read', action='read', id=group.name) }}">
        <h3>{{ group.display_name }}</h3>
      </a>
      {% if group.description %}
        <p>
          {{ h.markdown_extract(group.description, extract_length=80) }}
        </p>
      {% else %}
        <p>{{ _('This group has no description') }}</p>
      {% endif %}
      {% if group.package_count %}
        <strong>{{ ungettext('{num} Dataset', '{num} Datasets', group.package_count).format(num=group.package_count) }}</strong>
      {% else %}
        <span>{{ _('0 Datasets') }}</span>
      {% endif %}
    </li>
  {% endfor %}
</ul>

  • snippet 檔最開頭需以 docstring 描述需傳入的參數。在這個例子裡是:groups。
  • 呼叫 url_for() 為每個 group 名稱產生超連結至群組頁面
  • 若群組有 description 呼叫 markdown_extract() 產生其內容,若無則呼叫 _() 把 'This group has no description' 訊息翻譯使用者瀏覽器對應的語言。
  • 呼叫 ungettext() 顯示群組的資料集數(翻譯成對應的複數表示方式)。
  • 群組屬性/group attributes 如: {{ group.name }}, {{ group.display_name }}, {{ group.description }}, {{ group.package_count }},及其他 CKAN 物件(packages/datasets, organizations, users…) 屬性可透過 CKAN API 讀取,如 group_show()。


修改 templates/home/layout1.html

如下:

{% ckan_extends %}

{% block featured_group %}
  {{ h.recently_changed_packages_activity_stream(limit=4) }}
{% endblock %}

{% block featured_organization %}
  {% snippet 'snippets/example_theme_most_popular_groups.html',
             groups=h.example_theme_most_popular_groups()  %}
{% endblock %}

重啟 CKAN,再次瀏覽網頁可看到:

覆寫預設 snippet

若 plugin 加入的 snippet 名稱與 CKAN 預設 snippet 同名,則 plugin 的 snippet 會覆寫預設 snippet,無論是否有使用它。

若兩個 plugins 有同名 snippet 便會互相覆蓋。為避免這個問題,snippet 檔名最好以它的 extension 名稱開頭,如:snippets/example_theme_*.html。

snippet 「不能」存取 template 全域環境變數 c ( Variables and functions available to templates). 但可以存取:

  • h
  • app_globals
  • request
  • 其他父 template 透過 {% snippet %} 呼叫時傳入的參數

CKAN Templates Tutorial 6(v2.9): snippet

http://docs.ckan.org/en/2.9/theming/templates.html#template-snippets

Template snippets 是一小段/snippet template code,如同 helper functions,可在 template 裡呼叫。CKAN 在 ckan/templates/ 目錄下,可看到如:ckan/templates/snippets/ 及 ckan/templates/package/snippets/。

如下 ckan/templates/group/snippets/group_list.html 這個 snippet,可協助很好地顯示 group 清單。它裡面又呼叫了另一段 snippet- group/snippets/group_item.html:

{#
Display a grid of group items.

groups - A list of groups.

Example:

    {% snippet "group/snippets/group_list.html" %}

#}
{% block group_list %}
<ul class="media-grid" data-module="media-grid">
{% block group_list_inner %}
  {% for group in groups %}
    {% snippet "group/snippets/group_item.html", group=group, position=loop.index %}
  {% endfor %}
  {% endblock %}
</ul>
{% endblock %}


修改 layout1.html

ckanext-example_theme/ckanext/example_theme/templates/home/layout1.html:

⋯⋯略

{% block featured_organization %}

  <h3>熱門群組</h3>
  {# Call the group_list.html snippet. #}
  {% snippet 'group/snippets/group_list.html',
             groups=h.example_theme_most_popular_groups() %}

{% endblock %}

如上程式,傳了兩個參數給 {% snippet %} tag:

  • 'group/snippets/group_list.html'
    要呼叫的 template snippet
  • groups=h.example_theme_most_popular_groups()

在 snippet 檔名後面,可傳入任意個參數給 snippet 裡的程式,變成 snippet 裡的全域變數。每個 snippet 檔應該在最前面的 docstring 註解它需要傳入那些參數。

更新後,首頁右下區塊結果如下:




2022年5月5日 星期四

CKAN Templates Tutorial 5(v2.9): Template helper functions

http://docs.ckan.org/en/2.9/theming/templates.html#template-helper-functions

若要讀出 CKAN 裡的資訊,template helper function 是方法之一。

內建的 template helper functions

延續 上個 CKAN templates Tutorial,將 example_theme 底下的 templates/home/layout1.html 修改如下:

{% ckan_extends %}

{% block featured_group %}
<p>recently_changed_packages_activity_stream</p>
    <ul>
        {% for stream in h.recently_changed_packages_activity_stream(limit=4) %}
            <li>stream id: {{ stream.id }}</li>
        {% endfor %}
    </ul>
{% endblock %}

以 h 開頭的 h.recently_changed_packages_activity_stream,便是 template helper function,可讀出最近資料集(package)的更新資訊 ,結果如下:

在 templates 裡可透過 h 全域變數呼叫 ckan.lib.helpers 底下的 template helper function。參考:Template helper functions reference。

自訂 template helper functions

實作 ckan.plugins.interfaces.ITemplateHelpers,列出最受歡迎的 group。

修改 plugin.py 

import ckan.plugins as plugins
import ckan.plugins.toolkit as toolkit

def most_popular_groups():
    '''Return a sorted list of the groups with the most datasets.'''

    # Get a list of all the site's groups from CKAN, sorted by number of
    # datasets.
    groups = toolkit.get_action('group_list')(
        data_dict={'sort': 'package_count desc', 'all_fields': True})

    # Truncate the list to the 10 most popular groups only.
    groups = groups[:10]

    return groups


class ExampleThemePlugin(plugins.SingletonPlugin):
    '''An example theme plugin.
    '''
    plugins.implements(plugins.IConfigurer)

    # Declare that this plugin will implement ITemplateHelpers.
    plugins.implements(plugins.ITemplateHelpers)

    def update_config(self, config):

        # Add this plugin's templates dir to CKAN's extra_template_paths, so
        # that CKAN will use this plugin's custom templates.
        toolkit.add_template_directory(config, 'templates')

    def get_helpers(self):
        '''Register the most_popular_groups() function above as a template
        helper function.
        '''
        # Template helper function names should begin with the name of the
        # extension they belong to, to avoid clashing with functions from
        # other extensions.
        return {'example_theme_most_popular_groups': most_popular_groups}

修改 layout1.html

修改 ckanext-example_theme/ckanext/example_theme/templates/home/layout1.html 如下:

{% ckan_extends %}

{% block featured_group %}
  {{ h.recently_changed_packages_activity_stream(limit=4) }}
{% endblock %}

{% block featured_organization %}

  {# Show a list of the site's most popular groups. #}
  <h3>Most popular groups</h3>
  <ul>
    {% for group in h.example_theme_most_popular_groups() %}
      <li>{{ group.display_name }}</li>
    {% endfor %}
  </ul>

{% endblock %}

測試

重新安裝 plugin

切換到 ckanext-example_theme 目錄,執行:

cd ckanext-example_theme
python setup.py develop

重啟 CKAN

  • 進入Python Virtual Environment:
    . /usr/lib/ckan/default/bin/activate
  • 重啟 CKAN 服務:
    (production版) sudo supervisorctl restart ckan-uwsgi:*
    (develop版) ckan -c /etc/ckan/default/ckan.ini run

結果如下:






CKAN v2.9 templates 4: {% ckan_extends %} {% block %} {{ super() }}

{% ckan_extends %}

用 Jinja 的 {% ckan_extends %} 可讓自訂 template 「擴充」預設內容,而不是取代它。

修改 index.html

修改上個 tutorial 產生的 home/index.html 如下:

{% ckan_extends %}

重新瀏覽 CKAN 首頁,自訂 index.html 裡的 {% ckan_extends %} 告訴 CKAN 先執行原本的 home/index.html。

{% block %}

Jinja templates 中可嵌入 block 讓其它 templates 取代其內容,如 CKAN 預設 /usr/lib/ckan/default/src/ckan/ckan/templates/home/layout1.html:


<div role="main">
  <div class="main hero">
    <div class="container">
      <div class="row row1">
        <div class="col-md-6 col1">
          {% block promoted %}
            {% snippet 'home/snippets/promoted.html' %}
          {% endblock %}
        </div>
        <div class="col-md-6 col2">
          {% block search %}
            {% snippet 'home/snippets/search.html' %}
          {% endblock %}
        </div>
      </div>
    </div>
  </div>
  <div class="main">
    <div class="container">
      <div class="row row2">
        <div class="col-md-6 col1">
          {# Note: this featured_group block is used as an example in the theming
             tutorial in the docs! If you change this code, be sure to check
             whether you need to update the docs. #}
          {# Start template block example. #}
          {% block featured_group %}
            {% snippet 'home/snippets/featured_group.html' %}
          {% endblock %}
          {# End template block example. #}
        </div>
        <div class="col-md-6 col2">
          {% block featured_organization %}
            {% snippet 'home/snippets/featured_organization.html' %}
          {% endblock %}
        </div>
      </div>
    </div>
  </div>
</div>

CKAN 支援不同的layout: layout1, layout2, layout3 等。由 sysadmin 在 admin 頁設定。假設使用第一個 layout1.html。

以 {% ckan_extends %} 擴充 CKAN 預設的 template,可用 {% block %} 取代預設 template 中的任何 block。

新增 layout1.html

建立 ckanext-example_theme/ckanext/example_theme/templates/home/layout1.html ,內容如下:

{% ckan_extends %}

{% block featured_group %}
  取代原本的 featured_group: Hello block world!
{% endblock %}

這個檔案擴充原本的 layout1.html,覆寫其中的 featured_group block。

重啟 web server,瀏覽 CKAN 首頁,可看到 featured_group 區塊已被取代為 Hello block world!,但其它內容都沒有動。


{{ super() }}

{{ super() }} 可在 block 加入內容,而不是取代它。

修改:layout1.html

{% ckan_extends %}

{% block featured_group %}
    <p>這段文字會出現在 <code>featured_group</code> block 上方</p>      
    {{ super() }}
    <p>這段文字會出現在 <code>featured_group</code> block 下方</p>
{% endblock %}

以上 block 執行時,{{ super() }} 會被 parent block 的內容取代。



CKAN v2.9 templates 3: Jinja2

Jinjia2

CKAN template 以 Jinja2 撰寫。

敍述式及變數

{{ ... }} 中即 Jinja2 敍述式,最後放入執行結果。

{{ foo }} 會顯示成變數 foo 的值。

template 可用 CKAN 的許多全域變數,像是 app_globals 用 g 別名取得 CKAN 設定檔中部分設定,例如 ckan.site_title:

<p>The title of this site is: {{ g.site_title }}.</p>

其他可參考:http://docs.ckan.org/en/2.9/theming/variables-and-functions.html。

並不是所有設定都讀得到,自訂設定就讀不到,參考:CKAN Templates Tutorial 9(v2.9): 存取自訂的 config 設定。

若 template 要讀取的變數不存在,不會 crash 也不會有錯誤訊息,Jinja2 只會傳回空字串。

{{ g.an_attribute_that_does_not_exist }}
{{ a_variable_that_does_not_exist }}

但如果要產生不存在變數的 attribute,Jinja2 會 crash,如下:

{{ a_variable_that_does_not_exist.an_attribute_that_does_not_exist }}

UndefinedError: 'a_variable_that_does_not_exist' is undefined

Jinja2 不只是列印變數,還可以呼叫 Jinja2 的 global functions, CKAN 的 template helper functions 及自訂的 template helper functions。參考:Variables and functions available to templates。

Jinja tags

{% ... %} 裡的 Jinja tags 可控制程式邏輯。我們可以顯示啟用的 plugin 清單:

<ul>
  {% for plugin in g.plugins %}
    <li>{{ plugin }}</li>
  {% endfor %}
</ul>

用 Jinja’s {% if %} 測試條件:

{% if g.tracking_enabled %}
  <p>CKAN's page-view tracking feature is enabled.</p>
{% else %}
  <p>CKAN's page-view tracking feature is <i>not</i> enabled.</p>
{% endif %}

註解

{# ... #} 裡的是註解。

{# This text will not appear in the output when this template is rendered. #}

修改 index.html

修改上個 tutorial 產生的 home/index.html 如下:

{# Jinja variable example #}
<p>The title of this site is: {{ g.site_title }}.</p>
{# End example #}

{# Jinja for-loop example #}
<p>The currently enabled plugins are:</p>
<ul>
  {% for plugin in g.plugins %}
    <li>{{ plugin }}</li>
  {% endfor %}
</ul>
{# End example #}

{# Jinja if example #}
{% if g.tracking_enabled %}
  <p>CKAN's page-view tracking feature is enabled.</p>
{% else %}
  <p>CKAN's page-view tracking feature is <i>not</i> enabled.</p>
{% endif %}
{# End example #}

重啟 CKAN

  1. 進入Python Virtual Environment: 
    . /usr/lib/ckan/default/bin/activate
  2. 重啟 CKAN 服務:
    (production版) sudo supervisorctl restart ckan-uwsgi:*
    (develop版) ckan -c /etc/ckan/default/ckan.ini run

測試

重新瀏覽 http://[CKAN web site]/



CKAN v2.9 templates 2: 取代預設的 template

http://docs.ckan.org/en/2.9/theming/templates.html#replacing-a-default-template-file

每個 CKAN 網頁都由對應的 template 產生,如:

  • /index --> ckan/templates/home/index.html
  • /about --> ckan/templates/home/about.html
  • /dataset --> ckan/templates/package/search.html

要自訂,plugin 需註冊一個包含 template 的 template 目錄來覆寫 CKAN 的預設內容。

延續上個 CKAN templates Tutorial 1(v2.9): 空的example_theme。

修改 plugin.py

修改 ckanext-example_theme/ckanext/example_theme/plugin.py,如下:

import ckan.plugins as plugins
import ckan.plugins.toolkit as toolkit

class ExampleThemePlugin(plugins.SingletonPlugin):
    plugins.implements(plugins.IConfigurer)

    def update_config(self, config):
        toolkit.add_template_directory(config, 'templates')

程式中:

  • import ckan.plugins.toolkit as toolkit
    plugins toolkit 是 Python module 提供 CKAN plugins 必要的 functions, classes 及 exceptions。
  • plugins.implements(plugins.IConfigurer)
    實作 plugins.IConfigurer
  • def update_config
    實作 plugins.IConfigurer 介面的 update_config。
    CKAN 會在啟動時呼叫 IConfigurer 介面的 update_config,讓我們有機會修改 CKAN 的設定。
  • ckan.plugins.toolkit.add_template_directory 向 CKAN 註冊 template 目錄,告訴 CKAN 產生/render 網頁時來找這個plugin目錄下的 templates 目錄。
    只要與 CKAN 預設 template 同名的檔案就會取代掉原本的。

查看 CKAN 使用的 template

修改 /etc/ckan/default/ckan.ini 中的 debug = true。

重新載入 CKAN 首頁,會看到下方有個 Debug 連結,按下後展開 debug footer 顯示許多偵錯資訊,其中便有產生此網頁的 template 檔名。

Template name: home/index.html
Template path: /usr/lib/ckan/default/src/ckan/ckan/templates/home/index.html

大部分的 CKAN 網頁由多個 template 產生,第一個是 root template,其它則是相關的 included 檔。

覆寫 home/index.html

在 ckanext-example_theme 目錄下為要覆寫的 template 建立對應的目錄及檔案,如:
  ckanext/
    example_theme/
      templates/
        home/
          index.html  

編輯 index.html 如下:

Hello new Index Page! 中文也沒問題!

如果執行 ckan 沒有用 -r(--disable-reloader) 選項,如此修改 Python file,  template file,  CKAN config file, 或其它 CKAN file 都不需重啟伺服器。但如果是新加檔案、目錄就要重啟。

測試

重新瀏覽 http://[你的IP]/



CKAN v2.9 templates 1: 空的example_theme

http://docs.ckan.org/en/2.9/theming/templates.html

CKAN 網頁由 Jinja2 template 產生。以下練習將修改 layout 及預設內容。

CKAN theme 就是 CKAN plugin,內含自訂的 templates、靜態檔案。

建立: ckanext-example_theme

  • 啟用 CKAN Virtual Environment
. /usr/lib/ckan/default/bin/activate
  • 切換到 /usr/lib/ckan/default/src 執行 ckan generate extension
Extension's name [must begin 'ckanext-']: ckanext-example_theme
 
ckanext-example_theme
├── ckanext
│   ├── example_theme
│   │   ├── assets
│   │   │   └── webassets.yml
│   │   ├── fanstatic
│   │   ├── i18n
│   │   ├── __init__.py
│   │   ├── plugin.py
│   │   ├── public
│   │   ├── templates
│   │   └── tests
│   │       ├── __init__.py
│   │       └── test_plugin.py
│   └── __init__.py
├── dev-requirements.txt
├── LICENSE
├── MANIFEST.in
├── README.md
├── requirements.txt
├── setup.cfg
├── setup.py
└── test.ini
 

修改 plugin.py 

所有 CKAN plugin 都需繼承自 plugins.SingletonPlugin。修改 ckanext-example_theme/ckanext/example_theme/plugin.py 如下:

import ckan.plugins as plugins

class ExampleThemePlugin(plugins.SingletonPlugin):
    '''An example theme plugin.

    '''
    pass


        修改並執行 setup.py 

        修改 ckanext-example_theme/setup.py 的 entry_points
        entry_points='''
            [ckan.plugins]
            example_theme=ckanext.example_theme.plugin:ExampleThemePlugin
        ''',

        切換到 ckanext-example_theme 目錄,執行:

        cd ckanext-example_theme
        python setup.py develop


        修改 /etc/ckan/default/ckan.ini 並重啟 CKAN

        extension plugins 必須加到 CKAN 設定檔的 ckan.plugins 中,CKAN 才會呼叫。

        ckan.plugins = stats text_view 略... example_theme

        重啟 CKAN

        1. 進入Python Virtual Environment: 
          . /usr/lib/ckan/default/bin/activate
        2. 重啟 CKAN 服務:
          (production版) sudo supervisorctl restart ckan-uwsgi:*
          (develop版) ckan -c /etc/ckan/default/ckan.ini run

        測試

        重新載入 http://[CKAN web site]/

        沒錯就是對了。

        2022年5月3日 星期二

        CKAN Extensions Tutorial 3(v2.9): 在 plugin 中呼叫 toolkit

        https://docs.ckan.org/en/2.9/extensions/tutorial.html#using-the-plugins-toolkit

        CKAN plugins toolkit 是一個 Python module,提供 CKAN 相關的 functions, classes 及 exceptions 協助撰寫 CKAN extension。

        toolkit.get_action 可用來呼叫 CKAN 的 action function,這和透過 web interface 或 API 呼叫 的方法一樣。以下程式,ckan.plugins.toolkit.get_action 呼叫ckan.logic.action.get.member_list 取得 curators group 的成員名單,結果和 API 呼叫 /api/3/action/member_list 會是一樣的:

            members = toolkit.get_action('member_list')(
                data_dict={'id': 'curators', 'object_type': 'user'})


        延續上個 CKACKAN Extensions Tutorial(v2.9): 實作 IAuthFunctions 自訂授權規則,以下將實作只允許 curators 群組成員建立群組的功能。

        建立 curators 群組

        在 CKAN 中建立 curators 群組。

        修改 plugin.py:實作 IAuthFunctions

        修改 ckanext-iauthfunctions/ckanext/iauthfunctions/plugin.py (程式碼)

        import ckan.plugins as plugins
        import ckan.plugins.toolkit as toolkit

        def group_create(context, data_dict=None):

            # Get the user name of the logged-in user.
            user_name = context['user']

            # Get a list of the members of the 'curators' group.
            members = toolkit.get_action('member_list')(
                data_dict={'id': 'curators', 'object_type': 'user'})

            # 'members' is a list of (user_id, object_type, capacity) tuples, we're
            # only interested in the user_ids.
            member_ids = [member_tuple[0] for member_tuple in members]

            # We have the logged-in user's user name, get their user id.
            convert_user_name_or_id_to_id = toolkit.get_converter(
                'convert_user_name_or_id_to_id')
            user_id = convert_user_name_or_id_to_id(user_name, context)

            # Finally, we can test whether the user is a member of the curators group.
            if user_id in member_ids:
                return {'success': True}
            else:
                return {'success': False,
                        'msg': 'Only curators are allowed to create groups'}

        class ExmapleAuthFunctionsPlugin(plugins.SingletonPlugin):
            plugins.implements(plugins.IAuthFunctions)

            def get_auth_functions(self):
                return {'group_create': group_create}


        • 實作 IAuthFunctions
        • 覆寫 IAuthFunctions 介面的 get_auth_functions 方法
        • 呼叫 toolkit.get_action('member_list') 判斷目前使用者是否在 curators 群組

        安裝

        1. 進入Python Virtual Environment: 
          . /usr/lib/ckan/default/bin/activate
        2. 切換目錄:
          cd /usr/lib/ckan/default/src/ckanext-iauthfunctions
        3. 安裝 Plugin: 
          python setup.py develop
        4. 重啟 CKAN 服務:
          sudo supervisorctl restart ckan-uwsgi:*

        測試

        • 開 Postman 執行 api 呼叫
        curl POST 'http://[CKAN web site]/api/3/action/group_create
        --header 'Authorization: [測試會員的API Key]' 
        --header 'Content-Type: application/json' 
        --data-raw '{
            "name": "0506-Group",
            "owner_org": "0427-org",
            "description": "test ckanext-iauthfunctions"    
        }'

        視是否為 curators group 的帳號,success 回傳 true 或 false:

        {
            "error": {
                "__type": "Authorization Error",
                "message": "拒絕存取: Only curators are allowed to create groups[ExampleIAuthFunctionsPlugin]"
            },
            "help": "...",
            "success": false
        }
        • 以管理員登入 CKAN,建立 curators 群組
          • 把測試會員加入這個群組。
          • 再次以 Postman 執行以上 api 呼叫
          • 即可成功

        CKAN Extensions Tutorial(v2.9): 實作 IAuthFunctions 自訂授權規則

        https://docs.ckan.org/en/2.9/extensions/tutorial.html#implementing-the-iauthfunctions-plugin-interface

        CKAN 提供許多 plugin interfaces(v2.9) 以便掛勾/hook 到 CKAN 修改或擴充功能:

        • u'Interface',
        • u'IRoutes',
        • u'IMapper',
        • u'ISession',
        • u'IMiddleware',
        • u'IAuthFunctions',
        • u'IDomainObjectModification',
        • u'IFeed',
        • u'IGroupController',
        • u'IOrganizationController',
        • u'IPackageController',
        • u'IPluginObserver',
        • u'IConfigurable',
        • u'IConfigurer',
        • u'IActions',
        • u'IResourceUrlChange',
        • u'IDatasetForm',
        • u'IValidators',
        • u'IResourcePreview',
        • u'IResourceView',
        • u'IResourceController',
        • u'IGroupForm',
        • u'ITagController',
        • u'ITemplateHelpers',
        • u'IFacets',
        • u'IAuthenticator',
        • u'ITranslation',
        • u'IUploader',
        • u'IBlueprint',
        • u'IPermissionLabels',
        • u'IForkObserver',
        • u'IApiToken',
        • u'IClick',

        CKAN 如何驗證

        參考: plugin interfaces。凡可透過 CKAN web 介面或 API 呼叫的動作都是以 ckan/logic/action/{create,delete,get,update}.py 實作的 action function。

        例如資料集相關的 Web API 便對應到:

        • func:`ckan.logic.action.create.package_create`
        • func:`ckan.logic.action.get.package_show`
        • func:`ckan.logic.action.update.package_update`
        • func:`ckan.logic.action.delete.package_delete`

        每個 action function 都有對應的 authorization function (ckan/logic/auth/{create,delete,get,update}.py),CKAN 呼叫 authorization function 決定使用者是否有被授權執行。

        實作 ckan.plugins.interfaces.IAuthFunctions,並註冊與 CKAN 同名的 authorization function,如:'user_create', 'group_create',即可覆寫 CKAN 的授權規則。

        在 CKAN 呼叫 authorization function 之前,會先驗證呼叫端是否提供合法的 API key。若要允許匿名執行, authorization function 需標示為 auth_allow_anonymous_access。如:

                    @p.toolkit.auth_allow_anonymous_access
                    def my_search_action(context, data_dict):
                        略⋯⋯

        IAuthFunctions

        實作 ckan.plugins.interfaces.IAuthFunctions。所有 authorization function 都有兩個參數:

        • context
          • model: 可用來查詢資料庫
          • user: 內容使用者的 名稱/IP(匿名存取)
          • auth_user_obj: model.User物件/None(匿名存取)
        • data_dict
          • CKAN 會傳給所有 authorization and action functions data_dict,內容所有 post 進來的資料,可能是網頁中填寫的表單欄位內容,或 API 呼叫傳入的 JSON 內容如:
        {'description': u'A really cool group',
         'image_url': u'',
         'name': u'my_group',
         'title': u'My Group',
         'type': 'group',
         'users': [{'capacity': 'admin', 'name': u'seanh'}]}

        回傳 dictionary:

        • {'success': True} 授權
        • {'success': False} 拒絕

        範例如下:

        def user_create(context, data_dict=None):
          if (some condition):
            return {'success': True}
          else:
            return {'success': False, 'msg': 'Not allowed to register'}

        CKAN Extensions Tutorial(v2.9):一個空的 CKAN extension

        https://docs.ckan.org/en/2.9/extensions/tutorial.html

        建立:ckan generate extension  

        1. 進入Python Virtual Environment:
          . /usr/lib/ckan/default/bin/activate
        2. 切換目錄
          cd /usr/lib/ckan/default/src 
        3. 執行 ckan generate extension

        Extension's name [must begin 'ckanext-']: ckanext-你的extension名稱
        (如: ckanext-iauthfunctions )]

        ├── ckanext
        │   ├── iauthfunctions //Python package 程式碼目錄
        │   │   ├── assets
        │   │   │   └── webassets.yml
        │   │   ├── fanstatic
        │   │   ├── i18n
        │   │   ├── __init__.py
        │   │   ├── plugin.py //CKAN Extension的功能寫在這裡
        │   │   ├── public
        │   │   ├── templates
        │   │   └── tests
        │   │       ├── __init__.py
        │   │       └── test_plugin.py
        │   └── __init__.py
        ├── dev-requirements.txt
        ├── LICENSE
        ├── MANIFEST.in
        ├── README.md
        ├── requirements.txt
        ├── setup.cfg
        ├── setup.py  //用它安裝到Virtual Environment
        └── test.ini

        若出現錯誤 `cookiecutter` library is missing from import path.。則加裝 cookiecutter :

         pip install cookiecutter 

        修改 plugin.py:撰寫 plugin 類別

        修改 ckanext-iauthfunctions/ckanext/iauthfunctions/plugin.py。CKAN 的 extension 其實就是一個 plugin,所有 CKAN plugin 都需繼承自 plugins.SingletonPlugin:
         
        import ckan.plugins as plugins

        class ExampleIAuthFunctionsPlugin(plugins.SingletonPlugin):
            pass

        修改 setup.py:設定 entry_points

        修改 ckanext-iauthfunctions/setup.py 的 entry_points

        entry_points='''
                [ckan.plugins] 
                example_iauthfunctions=ckanext.iauthfunctions.plugin:ExampleIAuthFunctionsPlugin

        修改 ckan.ini:啟用 plugin

        修改 /etc/ckan/default/ckan.ini。CKAN 的 extension plugins 必須加到 CKAN 設定檔的 ckan.plugins 中,CKAN 才會呼叫。

        ckan.plugins = stats text_view 略... example_iauthfunctions

        安裝測試

        1. 進入Python Virtual Environment: 
          . /usr/lib/ckan/default/bin/activate
        2. 切換目錄:
          cd /usr/lib/ckan/default/src/ckanext-iauthfunctions
        3. 安裝 Plugin: 
          python setup.py develop
        4. 重啟 CKAN 服務:
          sudo supervisorctl restart ckan-uwsgi:*

        檢視錯誤

        cat /etc/ckan/default/uwsgi.ERR

        2022年4月26日 星期二

        CKAN Get Started:CKAN API(v2.9)

        Check CKAN API 玩一下它的 api。(把 JSON formatter plugin for Chrome 裝起來比較好看 JSON 資料)

        Datasets 與 resources

        在 CKAN,資料以 dataset 形式上傳。dataset 包含:

        • metadata
          說明資料,如:標題、出版者、日期...。
        • resource
          即資料本身。CKAN 不管格式,可以是 CSV, Excel, XML, PDF, RDF 或圖檔。
          CKAN 可將資料儲存在內部或僅儲存連結。
        一個 dataset 可包含多個 resource,如歷年資料,或同樣的資料但不同的格式。

        建立 Organizations, Datasets 及 Resources

        有四個步驟:

        1. Get an API key (API Key 不等於 API Token)
        2. Create an organization;
        3. Create dataset inside an organization (dataset 一定掛在某個 organization 下);
        4. Add resources to the dataset

        開個 Postman 執行以下 api 呼叫

        Get

        curl http://11.11.11.163/api/3/action/group_list

        Create Organization

        curl -X POST 'http://[你的IP]/api/3/action/organization_create'
        -H 'Authorization: [你的API Key]'
        -H 'Content-Type: application/json' 
        -d '{
        "name": "0509-org",
        "title": "0509組織",
        "description": "測試CKAN"
        }'

        Create Dataset

        curl POST 'http://[你的IP]/api/3/action/package_create'
        --header 'Authorization: [你的API Key]'
        --header 'Content-Type: application/json'
        --data-raw '{
        "name": "0509-dataset",
        "title": "0509 資料集",
        "description": "測試CKAN",
        "owner_org": "0509-org"
        }'

        Add a resource

        curl POST 'http://[你的IP]/api/3/action/resource_create'
        --header 'Authorization: [你的API Key]'
        --header 'Content-Type: application/json'
        --data-raw '{
        "url": "https://raw.githubusercontent.com/frictionlessdata/test-data/master/files/csv/100kb.csv",
        "description": "來自 githubusercontent frictionlessdata 的範例資料",
        "name": "0509-daset-test-csv-data",
        "owner_org": "0509-org",
        "package_id": "0509-dataset"
        }'


        CKAN創始人Rufus Pollock:CKAN 概覽

        Rufus Pollock,CKAN的創始人,著有 《The Open Revolution: Rewriting the Rules of the Information Age (2018) 》一書主張 Open Data(參考:Open (Public) Data: What, Why, How)。

        以下為他在 CKAN Open Data Portal Webinar 中的介紹。(Webinar 的 Key Takeaways) 

        CKAN Platform

        CKAN 是 Data Management System (DMS) 。相對於 CMS 針對 content, DMS 的對象是 data。

        CKAN 可以是以下解決方案的平台:

        • Data Portals:a gateway to data
        • Data Catalog
        • Data Lake:結合雲端儲存及運算能力。

        CKAN Features

        CKAN 許多功能 都可客制化。


        CKAN 採元件化設計,各元件可單獨或組合使用。


        CKAN 官方文件