上一篇使用腾讯云的云函数(Serverless-实现bing每日壁纸API(一)),实现了每日定时抓取bing壁纸并保存到数据库的功能,这一篇继续利用云函数实现一个获取bing壁纸列表的api
# -*- 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壁纸数据,简单组装之后返回。
函数的功能实现很简单,需要注意的是这个要设置为网关触发调用的模式,可以直接在template.yml文件中设置,也可以在腾讯云的控制台去设置:
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壁纸并展示出来。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有