使用 Serverless(SCF) 快速架构院校查询小工具

终于终于,研究了半拉小时折腾出来了,今天给大家分享如何使用纯SCF来制作一个院校查询的小工具。

这个工具需要两个云函数,一个云函数为了独立调用方便做API的调用,另一个函数来展示我们的页面。

原理非常简单,如下图所示

完成的效果如下:

展示端:https://service-fib8bidg-1251746107.gz.apigw.tencentcs.com/release/showhtml

 

 

API端:https://service-4jpdvu5o-1251746107.gz.apigw.tencentcs.com/release/educhaxun/?groups=%E6%95%99%E8%82%B2%E9%83%A8

我们要完成此单页的话,数据库是关键,这里我会在文章最后分享出我的SQL数据库文件,大家不用担心

 

 

数据库的结构如图所示,这边的话也是使用 PHP+MySQL 来完成此作品。

首先,我们来准备一些工具:

腾讯云SCF平台: https://cloud.tencent.com/product/scf

腾讯云SCF CLI 工具: https://cloud.tencent.com/document/product/583/33449

腾讯云SCF VSCode 工具:https://cloud.tencent.com/document/product/583/37511

具体的安装注册这边就不在展示了,这些工具会极大的方便我们对代码做部署和拉取。

其中注意的是 CLI 工具依赖 Python ,可以去Python 官网直接下载  3.6+ 顺带装上 pip ,然后执行 pip install scf  即可。

然后我们来创建第一个函数,我们的主API函数 educhaxun,使用PHP 7.0创建

核心代码如下 :

$edu = $event['queryString']['edu'];
$code  = $event['queryString']['code'];
$groups = $event['queryString']['groups'];
$local = $event['queryString']['local'];
$level = $event['queryString']['level'];

if ($edu != null) {
  $sql = "SELECT id, edu ,code,groups,local,level,othen FROM edu where edu LIKE '%".$edu."%'";
} else if ($code != null) {
  $sql = "SELECT id, edu ,code,groups,local,level,othen FROM edu where code LIKE '%".$code."%'";
} else if ($groups != null) {
  $sql = "SELECT id, edu ,code,groups,local,level,othen FROM edu where groups LIKE '%".$groups."%'";
}else if ($local != null) {
  $sql = "SELECT id, edu ,code,groups,local,level,othen FROM edu where local LIKE '%".$local."%'";
}else if ($level != null) {
  $sql = "SELECT id, edu ,code,groups,local,level,othen FROM edu where level LIKE '%".$level."%'";
}
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
  // 输出数据
  $ends = array();
  while ($rows=mysqli_fetch_array($result)){
    $count=count($rows);//不能在循环语句中,由于每次删除 row数组长度都减小  
    for($i=0;$i<$count;$i++){  
        unset($rows[$i]);//删除冗余数据  
      } 
    array_push($ends,$rows);
    }
}
return $ends;

思路如下,我们需要先拿到get请求的数值,然后将请求值传递给数据库做查询,并输出数据。

首先,我们使用云函数特殊变量 $event,该变量可以参数传递触发事件数据,我们来看看它的返回值到底是怎样的把:

 

 

请求一个数据并 return 后,我们发现我们的请求值在 queryString 字段,所以我们只要拿到该字段的返回请求,就可以当 get 传递值了,我第一次想到的方法是使用 $_GET[‘value’] 去取值,当然这样是取不到的。

后面的代码就很好理解了,判断并查询输出相应数值。当然,感兴趣的同学可以试试级联查询,这边就不多做解释了。

其次,我们需要设置添加 APIGW 的触发网关,这块的设置也很有讲究,由于我们没有使用官方的默认返回格式,所以“是否启用响应集成”这块务必选为否,让请求直接穿透即可。请求鉴权这块我们需要让另一个云函数调用,所以需要选择“支持CORS”

 

 

我们的最终效果如下:

 

 

至此,我们的第一个函数就制作完成了,下面我们需要制作我们的第二个展示函数,这块就非常简单了,使用HTML单页即可完成

核心代码如下:

<script>
  document.getElementById("getForm").addEventListener("submit",getForm);
  function getForm(e){
      e.preventDefault();
      let sinpt = document.getElementById('sinput').value;
      let sselect = document.getElementById('edu-select').value;
      if (sinpt == "" || sinpt == null || sinpt == undefined) {
        $('#err').modal();
      }else{
      let xhr = new XMLHttpRequest();
      xhr.open("GET","https://service-4jpdvu5o-1251746107.gz.apigw.tencentcs.com/release/educhaxun/?"+sselect+"="+sinpt, true);
      xhr.onload = function(){
        var data = this.responseText;
        var datajson = JSON.parse(data);
        console.log(datajson);
        if (datajson == "" || datajson == null || datajson == undefined){
          $('#null').modal();
        }else{
        var html="";
        for(var i = 0; i< datajson.length; i++){
        html += "<tr><td>"+datajson[i].id+"</td><td>"+datajson[i].edu+"</td><td>"+datajson[i].code+"</td><td>"+datajson[i].groups+"</td><td>"+datajson[i].local+"</td> <td>"+datajson[i].level+"</td><td>"+datajson[i].othen+"</td></tr>";
        }
        var html1="<div class='am-scrollable-horizontal am-animation-fade'><table class='am-table am-table-bordered am-table-striped am-text-nowrap'> <thead><tr><th>序列</th><th>院校名称</th><th>院校标识码</th><th>主管部门</th><th>所在地</th><th>办学层次</th><th>备注</th></tr></thead><tbody>";
        var html2="</tbody></table></div>";
        document.getElementById("result").innerHTML =html1+html+html2;
        }
      }
      xhr.send();
    }
 }
</script>

值得注意的是,云函数默认不支持单独展示HTML,我们需要将它封装一个函数,写法参照官网即可:

const fs = require('fs')
const path = require('path')

exports.main_handler = async (event, context, callback) => {
  let html = fs.readFileSync(path.resolve(__dirname, './index.html'), {
    encoding: 'utf-8'
  })
  return {
    isBase64Encoded: false,
    statusCode: 200,
    headers: { 'Content-Type': 'text/html; charset=utf-8' },
    body: html
  }
}

同样,我们需要将它发布为API网关的形式进行访问,当然为了访问方便&好看的话,我们可以在API GW 自定义我们的访问域名。这块的操作都很简单,就不在赘述了。

下面是完整的代码包和数据库文件,觉得有用的同学别忘了留言哦~~

 

腾讯云 COS 下载地址 : http://95s.pw/3g 

 



906 thoughts on “使用 Serverless(SCF) 快速架构院校查询小工具”

  • cüzdan kodu hakkında detaylı bilgi veya oyun tutkunlarına özel olarak tasarlanmış “atapazar.com” adresine hemen göz atın ve favori oyunlarınız için en uygun oyun parası ve epinleri kolayca satın alarak oyun deneyiminizi zirveye taşıyın!

  • 60 uc ne kadar hakkında detaylı bilgi veya oyun tutkunlarına özel olarak tasarlanmış “atapazar.com” adresine hemen göz atın ve favori oyunlarınız için en uygun oyun parası ve epinleri kolayca satın alarak oyun deneyiminizi zirveye taşıyın!

  • bursa konser bilet hakkında detaylı bilgi veya hemen bugün “https://bursaetkinlikmerkezi.com/” adresine tıklayarak unutulmaz anılar biriktireceğiniz etkinliklere katılma fırsatını kaçırmayın!

  • google reklam hakkında detaylı bilgi veya dijital pazarlamada başarıya ulaşmak için adımlarınızı doğru atın! “https://www.erdalalcan.com/” ziyaret ederek, reklam stratejilerinizi güçlendirecek ve işinizi zirveye taşıyacak taktikleri keşfedin.

  • You actually make it seem so easy with your presentation but I find this matter to be actually something which I think I would never understand. It seems too complicated and very broad for me. I’m looking forward for your next post, I will try to get the hang of it!

Casibom giriş进行回复 取消回复

邮箱地址不会被公开。 必填项已用*标注

2 × = 2