Board logo

標題: [教學] 用 ChromeOS/Linux 開發 Google Apps Script WebApp (API Content Service) [打印本頁]

作者: javacomhk    時間: 2022-5-24 00:09     標題: 用 ChromeOS/Linux 開發 Google Apps Script WebApp (API Content Service)

本帖最後由 javacomhk 於 2022-7-4 04:07 編輯

之前一篇是關於 Google Apps Script WebApp 嘅 backend 功能
這篇就討論一下,點樣利用Google Apps Script Webscrape 返來嘅 stock data 提供 JSON API 嘅 ContentService。

(F1)首先好似上一篇 Webscrape 那樣在 main.gs 增加一個 function hkej_scrape() 去 stock360.hkej.com 獲取香港所有股票的更多 data 。如下
  1. function hkej_scrape() {
  2.   var webAppSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("HKEJ");
  3.   webAppSheet.getRange("A1:E3000").clearContent();
  4.   const datestr = (new Date().toLocaleString('sv',{timeZone: 'Asia/Hong_Kong'})).slice(0, 19).replace(/-/g, "").replace(/:/g, "").replace("T", " ");
  5.   const url = ["https://stock360.hkej.com/stockList/all/99999999?&p=1","https://stock360.hkej.com/stockList/all/99999999?&p=2","https://stock360.hkej.com/stockList/all/99999999?&p=3","https://stock360.hkej.com/stockList/all/99999999?&p=4","https://stock360.hkej.com/stockList/all/99999999?&p=5","https://stock360.hkej.com/stockList/all/99999999?&p=6","https://stock360.hkej.com/stockList/all/99999999?&p=7","https://stock360.hkej.com/stockList/all/99999999?&p=8","https://stock360.hkej.com/stockList/all/99999999?&p=9","https://stock360.hkej.com/stockList/all/99999999?&p=10"]
  6.   for (i = 0 ; i < url.length; i++) {
  7.     var res=UrlFetchApp.fetch(url[i]);
  8.     var content = res.getContentText();
  9.     const $ = Cheerio.load(content);
  10.     var valdatestr = $('#datepicker').attr('value')

  11.     const a = $("tbody > tr").each((index,element) =>
  12.      {
  13.        const tds = $(element).find("td");
  14.        if ($(tds[0]).text() >= '00001' && $(tds[0]).text() <= '99999' ) {
  15.          webAppSheet.appendRow([$(tds[0]).text()+".HK", $(tds[1]).text().replace("s",""), $(tds[5]).text(), $(tds[6]).text(), valdatestr]);
  16.        }
  17.      }
  18.     );
  19.     console.log('HKEJ scraped page ' + (i+1) + "  " + valdatestr + ' !!')
  20.   }
  21. }
複製代碼
(F2)然後在 React Test Project 的 Google Sheet 內加上一個新的 worksheet 叫 HKEJ

(F3)新增 Triggers 設定每日定時上午6時執行 function hkej_scrape() 去獲取股票價值。
[attach]2321751[/attach]

(F4)測試 function hkej_scrape() 成功後,worksheet  HKEJ 就如下圖
[attach]2321747[/attach]

(F5)在 main.gs 修改 doGet 及新增 doPost 如下:
  1. function doGet(e) {
  2.   if (typeof e.parameters.request === 'object' || typeof e.parameters.stock === 'object') {
  3.     return doPost(e);
  4.   }
  5.   else
  6.     return HtmlService.createTemplateFromFile("index")
  7.     .evaluate()
  8.     .addMetaTag("viewport","width=device-width, initial-scale=1.0")
  9. }

  10. function doPost(e) {
  11.   if (e.parameters.request.includes("getStock") ) {
  12.     return ContentService.createTextOutput(JSON.stringify(getStock(e.parameters.stock))).setMimeType(ContentService.MimeType.JSON)
  13.   }
  14.   else if (e.parameters.request.includes("getData") ) {
  15.     return ContentService.createTextOutput(JSON.stringify(getData())).setMimeType(ContentService.MimeType.JSON)
  16.   }
  17.   else if (e.parameters.request.includes("hello")) {
  18.     return ContentService.createTextOutput('Hello, world '+JSON.stringify(e))
  19.   }
  20.   else {
  21.     return ContentService.createTextOutput(JSON.stringify(e))
  22.   }
  23. }
複製代碼
(F6)在 main.gs 新增 function getStock(codes) 如下:
  1. function getStock(codes) {
  2.   var hkejSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("HKEJ");
  3.   const hkejVals = hkejSheet.getDataRange().getValues();
  4.   const uppercodes = codes.map(code => code.toUpperCase());
  5.   var filterStock = hkejVals.filter(function (row) {
  6.     if (uppercodes.includes(row[0])) { // 0-based
  7.       return row
  8.     }
  9.   })
  10.   if (filterStock.length > 0) {
  11.     Logger.log(filterStock)
  12.     var jsn = []
  13.     filterStock.forEach(function (r, i) {
  14.       jsn[i] = {}
  15.       jsn[i]['code'] = r[0]
  16.       jsn[i]['name'] = r[1]
  17.       jsn[i]['price'] = r[2]
  18.       jsn[i]['change'] = r[3]
  19.       jsn[i]['date'] = r[4].slice(0,-3).replace('年','').replace('月','').replace('日','')
  20.     })
  21. //    Logger.log(JSON.stringify(jsn))
  22.     return jsn
  23.   }
  24.   else {
  25.     var jsn = {}
  26.     return jsn
  27.   }
  28. }
複製代碼
(F7)使用 Test Deployments WebApp URL 地址 例如是 https://script.google.com/macros/s/AAbbccddeeyyzz/dev

使用 Chrome Browser 測試 API 及返回的 JSON 如下

(F7a)測試 hello https://script.google.com/macros/s/AAbbccddeeyyzz/dev?request=hello
[attach]2321748[/attach]
(F7b)測試 getData https://script.google.com/macros/s/AAbbccddeeyyzz/dev?request=getData
[attach]2321749[/attach]
(F7c)測試 getStock https://script.google.com/macros/s/AAbbccddeeyyzz/dev?request=getStock&stock=00001.HK&stock=00005.HK
[attach]2321772[/attach]

(F8) 最後將個 WebApp deploy to production 然後將個 WebApp URL 可以去登記的 URL shortener 例如 tinyurl.com 去進行測試
https://tinyurl.com/react9?request=getStock&stock=00001.HK&stock=00005.HK&stock=00700.HK

使用 curl 去測試 doPost
  1. $ curl -L --data "request=getStock&stock=00001.HK&stock=00006.HK" https://tinyurl.com/react9
  2. [{"code":"00001.HK","name":"長江和記實業","price":56.4,"change":-0.15,"date":"20220523"},{"code":"00006.HK","name":"電能實業","price":52.3,"change":-2.3,"date":"20220523"}]

  3. $ curl -L --data "request=getData" https://tinyurl.com/react9
  4. [{"key":"apple","value":"green"},{"key":"banana","value":"yellow"}]
複製代碼


使用 wget 去測試 doPost
  1. $ wget -qO - --post-data='request=hello'  https://tinyurl.com/react9
  2. Hello, world {"postData":{"contents":"request=hello","length":13,"name":"postData","type":"application/x-www-form-urlencoded"},"contentLength":13,"queryString":"","contextPath":"","parameter":{"request":"hello"},"parameters":{"request":["hello"]}}
複製代碼


在 Google Apps Script Editor 修改完代碼,是需要更新 Linux 的檔案,方法是在 Terminal 輸入
  1. cd ~/webappreact
  2. npm run gpull
複製代碼

作者: javacomhk    時間: 2022-5-24 04:56

留位
作者: chue    時間: 2022-6-22 18:36

據初步了解如果撇除中資背景,FYDEOS現階段係比 CHROME OS FLEX 更值得安裝既 CHROME OS 類 OS,因為佢可以比較簡單裝返 GAPPS.CHROME OS FLEX可能背負"特朗普壓力"而未有提供官方安裝 GAPPS 辦法,背後原因就係中興華為





歡迎光臨 電腦領域 HKEPC Hardware (https://www.hkepc.com/forum/) Powered by Discuz! 7.2