python怎样判断字符串可以反序列化_从字符串值issu反序列化的Python AWS Lambda Stringargument构造函数/工厂方法...
我正在用python开发awslambda中的amazonlex Chatbot,它将发出一个API post调用,并得到JSON字符串的响应,如下所示'{"_id":"598045d12e1f98980a00001e","unique_id":"ed7e4e17c7db499caee576a7761512","cerebro":{"_id":"59451b239db9fa8b0a000004","acc_id":"533a9f0d2eda783019000002","name":"cerebro","access_id":"g01n0XTwoYfEWSIP","access_token":"3Yxw8ZiUlfSPsbEVLI6Z93vZyKyBFFIV"},"bot":{"_id":"59452f42dbd13ad867000001","name":"helloword"},"rundata":{"arguments":"","target":"local"},"state":"created","queue_id":null,"s_ts":null,"e_ts":null,"response":{},"responses":[],"summary":null,"resolve_incident":false,"err":null}'
但是我只对id值感兴趣,所以我将json转换成字典,如下所示并获取id值
^{pr2}$
如果我在Lambda控制台中测试代码,我会得到输出
但我在聊天机器人中得到的输出如下所示I was unable to process your message. DependencyFailedException: Invalid Lambda Response: Received invalid response from Lambda: Can not construct instance of IntentResponse: no String-argument constructor/factory method to deserialize from String value ('59832ba22e1f98980a00009b') at [Source: "59832ba22e1f98980a00009b"; line: 1, column: 1]
我的源代码如下:import math
import dateutil.parser
import datetime
import time
import os
import logging
import requests
import uuid
logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
""" --- Helpers to build responses which match the structure of the necessary dialog actions --- """
def get_slots(intent_request):
return intent_request['currentIntent']['slots']
def elicit_slot(session_attributes, intent_name, slots, slot_to_elicit, message):
return {
'sessionAttributes': session_attributes,
'dialogAction': {
'type': 'ElicitSlot',
'intentName': intent_name,
'slots': slots,
'slotToElicit': slot_to_elicit,
'message': message
}
}
def close(session_attributes, fulfillment_state, message):
response = {
'sessionAttributes': session_attributes,
'dialogAction': {
'type': 'Close',
'fulfillmentState': fulfillment_state,
'message': message
}
}
return response
def delegate(session_attributes, slots):
return {
'sessionAttributes': session_attributes,
'dialogAction': {
'type': 'Delegate',
'slots': slots
}
}
""" --- Helper Functions --- """
def parse_int(n):
try:
return int(n)
except ValueError:
return float('nan')
def build_validation_result(is_valid, violated_slot, message_content):
if message_content is None:
return {
"isValid": is_valid,
"violatedSlot": violated_slot,
}
return {
'isValid': is_valid,
'violatedSlot': violated_slot,
'message': {'contentType': 'PlainText', 'content': message_content}
}
def APIbot(intent_request):
"""
Performs dialog management and fulfillment for cluster configuration input arguments.
Beyond fulfillment, the implementation of this intent demonstrates the use of the elicitSlot dialog action
in slot validation and re-prompting.
"""
value1 = get_slots(intent_request)["myval1"]
value2 = get_slots(intent_request)["myval2"]
intense_type = get_slots(intent_request)["Instance"]
source = intent_request['invocationSource']
api_endpoint = 'url'
api_creds = {
'apiuser': 'user',
'apikey': 'key'
}
#trigger a bot run
botrun_api = api_endpoint + '/botruns'
botrun_payload = {
"botname":"helloword",
"arguments":"",
"target":"local",
"unique_id": uuid.uuid4().hex[:30] #unique run id - 30 chars max
}
headers = {
'Content-Type': 'application/json',
'Authorization': 'Key apiuser=%(apiuser)s apikey=%(apikey)s' % api_creds
}
res = requests.post(botrun_api, json=botrun_payload, headers=headers)
data = json.loads(res.content)
new_id=json_data.get('_id', None)
return new_id
# Instiate a cluster setup, and rely on the goodbye message of the bot to define the message to the end user.
# In a real bot, this would likely involve a call to a backend service.
return close(intent_request['sessionAttributes'],
'Fulfilled',
{'contentType': 'PlainText',
'content': 'Thanks, your values are {} and {} '.format(value1, value2)})
""" --- Intents --- """
def dispatch(intent_request):
"""
Called when the user specifies an intent for this bot.
"""
logger.debug('dispatch userId={}, intentName={}'.format(intent_request['userId'], intent_request['currentIntent']['name']))
intent_name = intent_request['currentIntent']['name']
# Dispatch to your bot's intent handlers
if intent_name == 'my_Values':
return APIbot(intent_request)
raise Exception('Intent with name ' + intent_name + ' not supported')
""" --- Main handler --- """
def lambda_handler(event, context):
"""
Route the incoming request based on intent.
The JSON body of the request is provided in the event slot.
"""
# By default, treat the user request as coming from the America/New_York time zone.
os.environ['TZ'] = 'America/New_York'
time.tzset()
logger.debug('event.bot.name={}'.format(event['bot']['name']))
return dispatch(event)
请提前帮我解决这个问题谢谢:)
python怎样判断字符串可以反序列化_从字符串值issu反序列化的Python AWS Lambda Stringargument构造函数/工厂方法...相关推荐
- python以下字符串合法的是_以下字符串合法的是().
[单选题]关于科学和人文的关系,说法不正确的一项是( ) [单选题]下列语句中,___________是不正确的Python语句. [多选题]以下属于人机交互方式的是(). [单选题]下面选项中,__ ...
- python字符串去头尾_悉尼大学某蒟蒻的Python学习笔记
About me 本蒟蒻是悉尼大学计算机科学大一的学生,这篇博客记录了学习INFO1110这门课的一些心得,希望能对大家有帮助. To start with 因为计算机只能识别机器语言,所以我们需要编 ...
- python字符串连接数字电视_【学习猿地】初识python脚本 #千万别看,我怕你控制不住...
>编写python程序的文件,称为python的脚本或程序 >要求当前的python脚本的文件后缀名必须是.py #### pycharm使用注意 > 需要明确的知道你当前pycha ...
- python怎么判断是不是汉字危机_谈 Python 的中文编码处理
最近业务中需要用 Python 写一些脚本.尽管脚本的交互只是命令行 + 日志输出,但是为了让界面友好些,我还是决定用中文输出日志信息. 很快,我就遇到了异常: Python代码 UnicodeE ...
- python字符串驼峰转换_将字符串转换为驼峰格式
输入例子: cssStyle2DomStyle('font-size') 输出例子: fontSize 题目解析 1.将输入字符串分割成字符数组 sName.split('') 2.首先判断字符数组的 ...
- python 筛选提取连续多行_没有比这更简单的Python入门案例,用python打印你的宠物小精灵...
现在学习Python的人越来越多,但你会以怎样的方式开始编写你的第一个Python代码呢? 下面我教你一个简单的入门案例,很适合最开始的Python学习哦! 即将用到的Python基础语法是:prin ...
- python中脚本是指什么_【学习猿地】初识python脚本 #千万别看,我怕你控制不住...
>编写python程序的文件,称为python的脚本或程序 >要求当前的python脚本的文件后缀名必须是.py #### pycharm使用注意 > 需要明确的知道你当前pycha ...
- 反转字符串java实现_反转字符串的几种实现(Java)
反转字符串的几种实现(Java) 首先第一种是利用Java中的类库对象进行反转 //第一种 使用Java类库的diam实现反转 public String reverse(String str){ S ...
- 用vs写python和c++需要哪些工具包_从运行效率与开发效率比较Python和C++
之前有人一直在说python怎么怎么好用,也有人说C++太难了,下面我做了一些笔记: 1.运行效率:C++ >> Python Python代码和C++最终都会变成CPU指令来跑,但一般情 ...
最新文章
- 彻底理解Spring AOP
- Flash/Flex学习笔记(53):利用FMS快速创建一个文本聊天室
- Linux C: 内嵌汇编语法
- GridControl详解(八)菜单
- 福建省计算机二级vb试题及答案,福建省计算机二级VB考的是什么内容?
- flume的概述和运行机制
- 计算机系统基础:磁盘调度知识笔记
- Linux学习之CentOS(三)----将Cent0S 7的网卡名称eno16777736改为eth0
- python 去除nan inf_Python实现半自动评分卡建模(附代码)
- linux搭建SonarQube_Oracle
- 编译mysql 5.7 源码安装常见问题
- ssis zip压缩文件_SSIS平面文件与原始文件
- tableview cell自适应撑高
- 我的世界java版盔甲架_我的世界盔甲架指令 手机版盔甲架指令
- Qt Building the android package failed! 构建失败
- 第二课 了解编程环境
- 水仙花数,用scratch编程实现
- Android Studio 中 gradle 下载失败的解决办法
- Matlab突然打不开,运行后一闪就消失了,任务管理器也没有的解决办法
- Docker-jenkins安装与部署
热门文章
- 简单易上手编译FFmpeg
- 好程序员web前端分享值得参考的css理论:OOCSS、SMACSS与BEM
- zabbix 小纪录
- 百度搜索_如何打开Intellij IDEA的代码提示功能?
- 微信红包如何抢大包、直播反垃圾、老骗局翻新……这一期宅客周刊你值得拥有...
- 使用maven profile 构建不同环境引用不同的值
- dedeCMS修改文章更新发布时间问题
- 基于matlab的退化图像复原(三)------维纳滤波复原
- [LeetCode]题解(python):019-Remove Nth Node From End of List
- 10行Python代码自动清理电脑内重复文件,释放双手!