溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Python中Apache APISIX插件怎么用

發(fā)布時間:2021-09-18 09:06:16 來源:億速云 閱讀:355 作者:小新 欄目:開發(fā)技術(shù)

這篇文章將為大家詳細(xì)講解有關(guān)Python中Apache APISIX插件怎么用,小編覺得挺實用的,因此分享給大家做個參考,希望大家閱讀完這篇文章后可以有所收獲。

前言:

Python 語言作為一個解釋型的高級編程語言,它語法簡潔易上手、代碼可讀性好 ,在跨平臺 、可移植性 、開發(fā)效率上都有很好的表現(xiàn),同時作為一個高級編程語言它的封裝抽象程度比較高屏蔽了很多底層細(xì)節(jié)(例如:GC )讓我們在開發(fā)的過程中可以更專注應(yīng)用邏輯的開發(fā)。

同時作為一個有 30 年歷史的老牌開發(fā)語言,它的生態(tài)以及各種模塊已經(jīng)非常完善,我們大部分的開發(fā)和應(yīng)用場景都可以從社區(qū)中找到很成熟的模塊或解決方案。

Python 其他的優(yōu)點就不再一一贅述,當(dāng)然它的缺點也比較明顯:Python 作為一門解釋性語言,相較于 C++ 和 Go 這樣的編譯型語言,在性能上的差距還是比較大的。

一、了解:項目架構(gòu)

apache-apisix-python-runner 這個項目可以理解為 Apache APISIX Python 之間的一道橋梁,通過 Python Runner 可以把 Python 直接應(yīng)用到 Apache APISIX 的插件開發(fā)中,最重要的還是希望讓更多對 Apache APISIX 和 API 網(wǎng)關(guān)感興趣的 Python 開發(fā)者通過這個項目,更多地了解和使用 Apache APISIX,以下為 Apache APISIX 多語言支持的架構(gòu)圖。

Python中Apache APISIX插件怎么用

上圖左邊是 Apache APISIX 的工作流程,右邊的 Plugin Runner 是各語言的插件運行器,本文介紹的 apisix-python-plugin-runner 就是支持 Python 語言的 Plugin Runner

Apache APISIX 中配置一個 Plugin Runner 時,Apache APISIX 會啟動一個子進(jìn)程運行 Plugin Runner,該子進(jìn)程與 Apache APISIX 進(jìn)程屬于同一個用戶,當(dāng)我們重啟或重新加載 Apache APISIX 時,Plugin Runner 也將被重啟。

如果你為一個給定的路由配置了 ext-plugin-* 插件,請求命中該路由時將觸發(fā) Apache APISIX 通過 Unix Socket Plugin Runner 發(fā)起 RPC 調(diào)用。調(diào)用分為兩個階段:

  • ext-plugin-pre-req :在執(zhí)行 Apache APISIX 內(nèi)置插件(Lua 語言插件)之前

  • ext-plugin-post-req :在執(zhí)行 Apache APISIX 內(nèi)置插件(Lua 語言插件)之后

大家可以根據(jù)需要選擇并配置 Plugin Runner 的執(zhí)行時機。Plugin Runner 會處理 RPC 調(diào)用,在其內(nèi)部創(chuàng)建一個模擬請求,然后運行多語言編寫的插件,并將結(jié)果返回給 Apache APISIX。

多語言插件的執(zhí)行順序是在 ext-plugin-* 插件配置項中定義的,像其他插件一樣,它們可以被啟用并在運行中重新定義。

二、安裝:部署測試

基礎(chǔ)運行環(huán)境:Apache APISIX 2.7、Python 3.6+

Apache APISIX 的安裝部署可參考 Apache APISIX 官方文檔:如何構(gòu)建 Apache APISIX (https://github.com/apache/api...)進(jìn)行部署。

1. 下載安裝 Python Runner

$ git clone https://github.com/apache/apisix-python-plugin-runner.git
$ cd apisix-python-plugin-runner
$ make install

2. 配置 Python Runner

  • 開發(fā)模式配置

運行 Python Runner:

    $ cd /path/to/apisix-python-plugin-runner
    $ APISIX_LISTEN_ADDRESS=unix:/tmp/runner.sock python3 apisix/main.py start
    修改 Apache APISIX 配置文件
    $ vim /path/to/apisix/conf/config.yaml
    apisix:
      admin_key:
        - name: "admin"
          key: edd1c9f034335f136f87ad84b625c8f1
          role: admin
    ext-plugin:
      path_for_test: /tmp/runner.sock
  • 生產(chǎn)模式配置

修改 Apache APISIX 配置文件

    $ vim /path/to/apisix/conf/config.yaml
    apisix:
      admin_key:
        - name: "admin"
          key: edd1c9f034335f136f87ad84b625c8f1
          role: admin
    ext-plugin:
      cmd: [ "python3", "/path/to/apisix-python-plugin-runner/apisix/main.py", "start" ]
  • Python Runner 配置(可選)

如果需要對 Log Level Unix Domain Socket 環(huán)境變量調(diào)整可以修改 Runner 的配置文件

$ vim /path/to/apisix-python-plugin-runner/apisix/config.yaml
socket:
  file: $env.APISIX_LISTEN_ADDRESS # Environment variable or absolute path

logging:
  level: debug # error warn info debug

3. 啟動 Python Runner

$ cd /path/to/apisix
# Start or Restart
$ ./bin/apisix [ start | restart ]

啟動或重啟 Apache APISIX 即可,此時 Apache APISIX Python Runner 已經(jīng)完成配置并啟動。

4. 測試 Python Runner

配置 Apache APISIX 路由及插件信息:

# 使用默認(rèn)demo插件進(jìn)行測試
$ curl http://127.0.0.1:9080/apisix/admin/routes/1 -H 'X-API-KEY: edd1c9f034335f136f87ad84b625c8f1' -X PUT -d '
{
  "uri": "/get",
  "plugins": {
    "ext-plugin-pre-req": {
      "conf": [
        { "name": "stop", "value":"{\"body\":\"hello\"}"}
      ]
    }
  },
  "upstream": {
        "type": "roundrobin",
        "nodes": {
            "127.0.0.1:1980": 1
        }
    }
}'
  • plugins.ext-plugin-pre-req.confRunner 插件配置,conf 為數(shù)組格式可以同時設(shè)置多個插件。

  • 插件配置對象中 name 為插件名稱,該名稱需要與插件代碼文件和對象名稱一致。

  • 插件配置對象中 value 為插件配置,可以為 JSON 字符串。

 訪問驗證:

$ curl http://127.0.0.1:9080/get -i
HTTP/1.1 200 OK
Date: Fri, 13 Aug 2021 13:39:18 GMT
Content-Type: text/plain; charset=utf-8
Transfer-Encoding: chunked
Connection: keep-alive
host: 127.0.0.1:9080
accept: */*
user-agent: curl/7.64.1
X-Resp-A6-Runner: Python
Server: APISIX/2.7

Hello, Python Runner of APISIX

三、實踐:插件開發(fā)

1. 插件目錄

/path/to/apisix-python-plugin-runner/apisix/plugins

此目錄中的 .py 文件將會被自動加載。

2. 插件示例

/path/to/apisix-python-plugin-runner/apisix/plugins/stop.py
/path/to/apisix-python-plugin-runner/apisix/plugins/rewrite.py

3. 插件格式

from apisix.runner.plugin.base import Base
from apisix.runner.http.request import Request
from apisix.runner.http.response import Response


class Stop(Base):
    def __init__(self):
        """
        Example of `stop` type plugin, features:
            This type of plugin can customize response `body`, `header`, `http_code`
            This type of plugin will interrupt the request
        """
        super(Stop, self).__init__(self.__class__.__name__)

    def filter(self, request: Request, response: Response):
        """
        The plugin executes the main function
        :param request:
            request parameters and information
        :param response:
            response parameters and information
        :return:
        """
        # 在插件中可以通過 `self.config` 獲取配置信息,如果插件配置為JSON將自動轉(zhuǎn)換為字典結(jié)構(gòu)
        # print(self.config)

        # 設(shè)置響應(yīng)頭信息
        headers = request.headers
        headers["X-Resp-A6-Runner"] = "Python"
        response.headers = headers

        # 設(shè)置響應(yīng)體信息
        response.body = "Hello, Python Runner of APISIX"

        # 設(shè)置響應(yīng)狀態(tài)碼
        response.status_code = 201

        # 通過調(diào)用 `self.stop()` 中斷請求流程,此時將立即響應(yīng)請求給客戶端
        # 如果未顯示調(diào)用 `self.stop()` 或 顯示調(diào)用 `self.rewrite()`將繼續(xù)將請求
        # 默認(rèn)為 `self.rewrite()`
        self.stop()

4. 插件規(guī)范及注意事項

  • 實現(xiàn)插件對象必須繼承 Base

  • 插件必須實現(xiàn) filter 函數(shù)

  • filter 函數(shù)參數(shù)只能包含 Request Response 類對象作為參數(shù)

  • Request 對象參數(shù)可以獲取請求信息

  • Response 對象參數(shù)可以設(shè)置響應(yīng)信息

  • self.config 可以獲取插件配置信息

  • filter 函數(shù)中調(diào)用 self.stop() 時將馬上中斷請求,響應(yīng)數(shù)據(jù)。

  • filter 函數(shù)中調(diào)用 self.rewrite() 時,將會繼續(xù)請求。

關(guān)于“Python中Apache APISIX插件怎么用”這篇文章就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,使各位可以學(xué)到更多知識,如果覺得文章不錯,請把它分享出去讓更多的人看到。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI