如何通过HTTP触发器传递输入参数触发Google Cloud Function
云函数HTTP触发器参数接收实现方案
基础运行逻辑
HTTP触发器是云厂商提供的HTTP接口端点,移动端可以向这个端点发送HTTP请求,云函数触发执行时,入口参数request会自动封装本次请求的所有数据,包括请求头、请求体、查询参数等。
你需要先从request中解析出JSON格式的请求体,才能拿到移动端传递的四个参数。
修正后完整代码
import pandas as pd import json def open_seats(request): # 第一步:解析请求体JSON,兼容不同云厂商的request结构 if isinstance(request, dict): # 部分云厂商会自动把JSON请求体转换为dict格式,可直接取值 req_data = request else: # 若request是原始请求对象,先读取body内容再解析为JSON req_data = json.loads(request.get_data()) # 第二步:参数校验,避免传参缺失导致运行报错 required_params = ["college", "department", "course", "section"] for param in required_params: if param not in req_data: return {"code": 400, "msg": f"缺失必填参数:{param}"} # 第三步:替换硬编码值,赋值用户传入的参数 college = req_data["college"] department = req_data["department"] course = req_data["course"] section = req_data["section"] # 原有业务逻辑不变,新增异常处理避免程序崩溃 url = 'https://www.bu.edu/link/bin/uiscgi_studentlink.pl/1630695081?ModuleName=univschr.pl&SearchOptionDesc=Class+Number&SearchOptionCd=S&KeySem=20223&ViewSem=Fall+2021&College=' \ + college + '&Dept=' + department + '&Course=' + course + '&Section=' + section try: table = pd.read_html(url)[4] class_table = table['Class'] open_seats_table = table['OpenSeats'] new_table = pd.concat([class_table, open_seats_table], axis=1) full_section_string = college + '\u00A0' + department + course + '\u00A0' + section val = None for i in range(len(new_table)): if new_table['Class'][i] == full_section_string: val = new_table['OpenSeats'][i] break if val is not None: return {"code": 200, "open_seats": val} else: return {"code": 404, "msg": "未找到对应课程"} except Exception as e: return {"code": 500, "msg": f"查询失败:{str(e)}"}
移动端请求要求
- 请求方法使用
POST - 请求头必须添加
Content-Type: application/json - 请求体JSON格式如下(注意你之前的JSON漏了逗号,已修正):
{ "college":"ENG", "department":"EC", "course":"414", "section":"A1" }
常见云厂商适配说明
- 阿里云函数计算:可以直接用
request.get_json()获取JSON请求体 - 腾讯云云函数:JSON请求体直接放在
event参数中,入口函数调整为def open_seats(event, context):,直接从event中取值即可 - AWS Lambda:JSON请求体存放在
event['body']中,需要手动用json.loads解析
内容的提问来源于stack exchange,提问作者Aymane
相关产品推荐
相关产品推荐

