Serverless-实现bing每日壁纸API(二)

2020-05-18 14:27:14 浏览数 (1)

上一篇使用腾讯云的云函数(Serverless-实现bing每日壁纸API(一)),实现了每日定时抓取bing壁纸并保存到数据库的功能,这一篇继续利用云函数实现一个获取bing壁纸列表的api

直接贴代码

代码语言:txt复制
# -*- coding: utf8 -*-
from serverless_db_sdk import database
import json
def main_handler(event, context):
    print(str(event))
    if "requestContext" not in event.keys():
        return {"errorCode":410,"errorMsg":"event is not come from api gateway"}
    request = event["requestContext"]
    query = event['queryString']
    
    #获取请求的参数
    offset = int(query.get('offset', 0))
    limit = int(query.get('limit', 50))
    if limit > 50:
        limit = 50

    result_data = []
    #查询数据库
    sql_template = """SELECT id, startdate, fullstartdate,  url, urlbase, copyright FROM bing.wallpaper order by id desc limit %s offset %s """
    connection = database("BING").connection(autocommit=False)
    try:
        cursor = connection.cursor()
        cursor.execute(sql_template, (limit, offset))
        result = cursor.fetchall()
        for x in result:
            result_data.append({
                "id": x[0], "startdate": x[1], "fullstartdate": x[2],
                "url": x[3], "urlbase": x[4], "copyright": x[5]
            })
    finally:
        connection.close()
    return  {"code":200,"data":result_data} 

这个就更加简单,从数据库中查出最近的bing壁纸数据,简单组装之后返回。

api设置

函数的功能实现很简单,需要注意的是这个要设置为网关触发调用的模式,可以直接在template.yml文件中设置,也可以在腾讯云的控制台去设置:

代码语言:txt复制
Resources:
  default:
    Type: TencentCloud::Serverless::Namespace
    bing_wallpaper_api:
      Properties:
        CodeUri: .
        Description: 获取bing壁纸api
        Environment:
          Variables:
            DB_BING_DATABASE: bing
            DB_BING_HOST: ***
            DB_BING_PASSWORD: ****
            DB_BING_PORT: '3306'
            DB_BING_USER: bing
            DB_DEFAULT: BING
        Events:
          apigw_bqdajp9lrb9t3qc7cuu0:
            Properties:
              Enable: true
              HttpMethod: GET
              IntegratedResponse: true
              ServiceId: service-j88xp030
              StageName: test
            Type: APIGW
          apigw_bqdaprsst4lfojhi0ks0:
            Properties:
              Enable: true
              HttpMethod: ANY
              IntegratedResponse: false
              ServiceId: service-jmhm1hno
              StageName: release
            Type: APIGW
        Handler: index.main_handler
        MemorySize: 128
        Runtime: Python3.6
        Timeout: 3
      Type: TencentCloud::Serverless::Function

登录腾讯云控制台,在函数管理中,可以找到函数的调用路径:

比如这个:

https://service-jmhm1hno-1256668370.gz.apigw.tencentcs.com/release/bing_wallpaper_api

直接发起http请求就可以调用函数获取结果了。

下一步

接下来我们可以试着去实现一个小程序,通过调用这个云函数来获取bing壁纸并展示出来。

0 人点赞