api+ Dy_updata.py 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273
  1. import json
  2. import boto3
  3. import time
  4. def lambda_handler(event, context):
  5. print(event)
  6. msg = json.loads(event['body'])
  7. secret = msg['secret_code']
  8. print(secret)
  9. client = boto3.client('dynamodb')
  10. table_name = "xdctb"
  11. # timedata = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
  12. response = client.update_item(
  13. TableName=table_name,
  14. # ExpressionAttributeNames={
  15. # 'skip': secret,
  16. # },
  17. ExpressionAttributeValues={
  18. ':y': {
  19. 'S': secret,
  20. }
  21. },
  22. Key={
  23. 'dtime': {
  24. 'S': '20200605',
  25. }
  26. },
  27. UpdateExpression='SET skip = :y',
  28. ReturnValues="UPDATED_NEW"
  29. )
  30. return {
  31. "statusCode": 200,
  32. "isBase64Encoded": False,
  33. "headers": {
  34. "Content-Type": "application/json; charset=utf-8"
  35. },
  36. "body": "OK ! "
  37. }
  38. #=======================第一版本=========================#
  39. import json
  40. import boto3
  41. import time
  42. def lambda_handler(event, context):
  43. print(event)
  44. msg = json.loads(event['body'])
  45. secret = msg['secret_code']
  46. print(secret)
  47. client = boto3.client('dynamodb')
  48. table_name = "xdctb"
  49. # timedata = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
  50. response = client.update_item(
  51. TableName=table_name,
  52. Key={
  53. 'dtime': {
  54. 'S': '20200605',
  55. },
  56. 'skip': {
  57. 'S': secret,
  58. },
  59. })
  60. # print(timedata)
  61. return {
  62. "statusCode": 200,
  63. "isBase64Encoded": False,
  64. "headers": {
  65. "Content-Type": "application/json; charset=utf-8"
  66. },
  67. "body": "OK ! "
  68. }
  69. # ========================? v2 ========================
  70. import boto3
  71. import json
  72. import time
  73. import base64
  74. from botocore.exceptions import ClientError
  75. print('Loading function')
  76. dynamodb = boto3.client('dynamodb')
  77. def respond(err, res=None):
  78. return {
  79. 'statusCode': '400' if err else '200',
  80. 'body': err.message if err else json.dumps(res),
  81. 'headers': {
  82. 'Content-Type': 'application/json',
  83. },
  84. }
  85. def lambda_handler(event, context):
  86. response = {}
  87. response["headers"] = event["headers"]
  88. #dynamodb.put_item(TableName='K12D', Item= {'id':{"S": json.loads(event['body'])["secret_code"]},'key':{"S": str(round(time.time()))}})
  89. #ret_data=dynamodb.scan(TableName='K12D')
  90. secret_name = "test"
  91. region_name = "cn-northwest-1"
  92. # Create a Secrets Manager client
  93. session = boto3.session.Session()
  94. client = session.client(
  95. service_name='secretsmanager',
  96. region_name=region_name
  97. )
  98. # In this sample we only handle the specific exceptions for the 'GetSecretValue' API.
  99. # See https://docs.aws.amazon.com/secretsmanager/latest/apireference/API_GetSecretValue.html
  100. # We rethrow the exception by default.
  101. try:
  102. get_secret_value_response = client.get_secret_value(
  103. SecretId=secret_name
  104. )
  105. except ClientError as e:
  106. if e.response['Error']['Code'] == 'DecryptionFailureException':
  107. # Secrets Manager can't decrypt the protected secret text using the provided KMS key.
  108. # Deal with the exception here, and/or rethrow at your discretion.
  109. raise e
  110. elif e.response['Error']['Code'] == 'InternalServiceErrorException':
  111. # An error occurred on the server side.
  112. # Deal with the exception here, and/or rethrow at your discretion.
  113. raise e
  114. elif e.response['Error']['Code'] == 'InvalidParameterException':
  115. # You provided an invalid value for a parameter.
  116. # Deal with the exception here, and/or rethrow at your discretion.
  117. raise e
  118. elif e.response['Error']['Code'] == 'InvalidRequestException':
  119. # You provided a parameter value that is not valid for the current state of the resource.
  120. # Deal with the exception here, and/or rethrow at your discretion.
  121. raise e
  122. elif e.response['Error']['Code'] == 'ResourceNotFoundException':
  123. # We can't find the resource that you asked for.
  124. # Deal with the exception here, and/or rethrow at your discretion.
  125. raise e
  126. else:
  127. # Decrypts secret using the associated KMS CMK.
  128. # Depending on whether the secret is a string or binary, one of these fields will be populated.
  129. if 'SecretString' in get_secret_value_response:
  130. secret = get_secret_value_response['SecretString']
  131. else:
  132. decoded_binary_secret = base64.b64decode(get_secret_value_response['SecretBinary'])
  133. #updated_secret=get_secret_value_response.update({"key": "test223123123"})
  134. try:
  135. client.update_secret(SecretId=secret_name, SecretString=json.dumps(json.loads(event['body'])["secret_code"]))
  136. return {
  137. 'statusCode': 200,
  138. #'body': json.loads(event['body'])["secret_code"]
  139. #'body': str(max(ret_data['Items'].key))
  140. #'body': json.loads(get_secret_value_response['SecretString'])['key']
  141. #'body': get_secret_value_response['SecretString']
  142. 'body': json.loads(event['body'])["secret_code"]
  143. }
  144. except:
  145. return {
  146. 'statusCode': 200,
  147. #'body': json.loads(event['body'])["secret_code"]
  148. #'body': str(max(ret_data['Items'].key))
  149. #'body': json.loads(get_secret_value_response['SecretString'])['key']
  150. #'body': get_secret_value_response['SecretString']
  151. 'body': json.loads(get_secret_value_response['SecretString'])
  152. }
  153. # ========================? v3 ========================
  154. import boto3
  155. import json
  156. import time
  157. import base64
  158. from botocore.exceptions import ClientError
  159. print('Loading function')
  160. dynamodb = boto3.client('dynamodb')
  161. def respond(err, res=None):
  162. return {
  163. 'statusCode': '400' if err else '200',
  164. 'body': err.message if err else json.dumps(res),
  165. 'headers': {
  166. 'Content-Type': 'application/json',
  167. },
  168. }
  169. def lambda_handler(event, context):
  170. response = {}
  171. response["headers"] = event["headers"]
  172. #dynamodb.put_item(TableName='K12D', Item= {'id':{"S": json.loads(event['body'])["secret_code"]},'key':{"S": str(round(time.time()))}})
  173. #ret_data=dynamodb.scan(TableName='K12D')
  174. secret_name = "test"
  175. region_name = "cn-northwest-1"
  176. # Create a Secrets Manager client
  177. session = boto3.session.Session()
  178. client = session.client(
  179. service_name='secretsmanager',
  180. region_name=region_name
  181. )
  182. # In this sample we only handle the specific exceptions for the 'GetSecretValue' API.
  183. # See https://docs.aws.amazon.com/secretsmanager/latest/apireference/API_GetSecretValue.html
  184. # We rethrow the exception by default.
  185. try:
  186. get_secret_value_response = client.get_secret_value(
  187. SecretId=secret_name
  188. )
  189. except ClientError as e:
  190. if e.response['Error']['Code'] == 'DecryptionFailureException':
  191. # Secrets Manager can't decrypt the protected secret text using the provided KMS key.
  192. # Deal with the exception here, and/or rethrow at your discretion.
  193. raise e
  194. elif e.response['Error']['Code'] == 'InternalServiceErrorException':
  195. # An error occurred on the server side.
  196. # Deal with the exception here, and/or rethrow at your discretion.
  197. raise e
  198. elif e.response['Error']['Code'] == 'InvalidParameterException':
  199. # You provided an invalid value for a parameter.
  200. # Deal with the exception here, and/or rethrow at your discretion.
  201. raise e
  202. elif e.response['Error']['Code'] == 'InvalidRequestException':
  203. # You provided a parameter value that is not valid for the current state of the resource.
  204. # Deal with the exception here, and/or rethrow at your discretion.
  205. raise e
  206. elif e.response['Error']['Code'] == 'ResourceNotFoundException':
  207. # We can't find the resource that you asked for.
  208. # Deal with the exception here, and/or rethrow at your discretion.
  209. raise e
  210. else:
  211. # Decrypts secret using the associated KMS CMK.
  212. # Depending on whether the secret is a string or binary, one of these fields will be populated.
  213. if 'SecretString' in get_secret_value_response:
  214. secret = get_secret_value_response['SecretString']
  215. else:
  216. decoded_binary_secret = base64.b64decode(get_secret_value_response['SecretBinary'])
  217. #updated_secret=get_secret_value_response.update({"key": "test223123123"})
  218. try:
  219. client.update_secret(SecretId=secret_name, SecretString=json.dumps(json.loads(event['body'])["secret_code"]))
  220. return {
  221. 'statusCode': 200,
  222. #'body': json.loads(event['body'])["secret_code"]
  223. #'body': str(max(ret_data['Items'].key))
  224. #'body': json.loads(get_secret_value_response['SecretString'])['key']
  225. #'body': get_secret_value_response['SecretString']
  226. 'body': json.loads(event['body'])["secret_code"]
  227. }
  228. except:
  229. return {
  230. 'statusCode': 200,
  231. #'body': json.loads(event['body'])["secret_code"]
  232. #'body': str(max(ret_data['Items'].key))
  233. #'body': json.loads(get_secret_value_response['SecretString'])['key']
  234. #'body': get_secret_value_response['SecretString']
  235. 'body': json.loads(get_secret_value_response['SecretString'])
  236. }