sungkhum

test

Oct 13th, 2021
775
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import json
  2. import boto3
  3. from collections import defaultdict
  4. from botocore.config import Config
  5. import os
  6. import urllib3
  7. from boto3.session import Session
  8.  
  9. # Retrieve the CloudFlare API key from Parameter Store in Systems Manager
  10. Params_Client = boto3.client('ssm')
  11. CLOUDFLARE = Params_Client.get_parameter(Name='Cloudflare',WithDecryption=True)['Parameter']['Value']
  12. EMAIL = 'sungkhum@gmail.com'
  13.  
  14. def lambda_handler(event, context):
  15.     DB_NAME = "DeSo"
  16.     TBL_NAME = "CreatorCoin"
  17.     QUERY = f"""
  18.    WITH pricelag AS (
  19.     SELECT *,
  20.      LAG(measure_value::bigint,1) OVER(PARTITION BY Username ORDER BY time) AS yesterday
  21.      FROM "DeSo"."CreatorCoin"
  22.      ORDER BY time
  23.    )
  24.    SELECT *,
  25.      measure_value::bigint - yesterday AS price_difference,
  26.      COALESCE(ROUND((cast(measure_value::bigint as double) - cast(yesterday as double)) / cast(yesterday as double) * 100,2),0) AS percentchange
  27.      FROM pricelag
  28.      WHERE time between ago(26h) and now()
  29.      GROUP BY pricelag.Username, pricelag.time, pricelag.PublicKeyBase58Check, pricelag.measure_name, pricelag.measure_value::bigint, pricelag.yesterday
  30.      ORDER BY price_difference ASC
  31.      LIMIT 110
  32.    """
  33.     try:
  34.       client = boto3.client('timestream-query', config=Config(read_timeout=10000, max_pool_connections=5000, retries={'max_attempts': 10}))
  35.       response = client.query(
  36.       QueryString=QUERY,
  37.       MaxRows=200)
  38.     except Exception as e:
  39.         print ("Unexpected error: %s" % e)
  40.    
  41.     column_names = [i["Name"] for i in response["ColumnInfo"]]
  42.     records = defaultdict(list)
  43.     for row in response["Rows"]:
  44.       for column, entry in zip(column_names, row["Data"]):
  45.         record = entry.get("ScalarValue")
  46.         records[column].append(record)
  47.        
  48.     generated = ""
  49.     i = 1
  50.     x = 0
  51.     while i <= 100:
  52.       first_price = int(records["yesterday"][x]) / 1e9
  53.       second_price = int(records["measure_value::bigint"][x])/ 1e9
  54.       diff = int(records['price_difference'][x])/ 1e9
  55.       if second_price != 0:
  56.         generated = generated + f"""<tr><td class="text-center">{i}</td>"""
  57.         public = records["PublicKeyBase58Check"][x]
  58.         user = records["Username"][x]
  59.         generated = generated + f"""<td><a href="https://bitclout.com/u/{user}" class="hover-warning" target="_blank" rel="noopener noreferrer"><img alt="Profile" src="https://bitclout.com/api/v0/get-single-profile-picture/{public}?fallback=https://bitclout.com/assets/img/default_profile_pic.png" class="avatar me-10">{user}</a></td>"""
  60.         generated = generated + f"""<td class="text-end" id="yesterday">{first_price}</td>"""
  61.         generated = generated + f"""<td class="text-end" id="today">{second_price}</td>"""
  62.         generated = generated + f"""<td class="text-end" id="difference">{diff}</td>"""
  63.         change = records['percentchange'][x]
  64.         generated = generated + f"""<td class="text-end"><span class="label label-danger">{change}%</span></td></tr>"""
  65.         i += 1
  66.       x += 1
  67.     s3 = boto3.resource('s3')
  68.    
  69.     view_parts = {}
  70.     view_item_names = ['header.html','footer.html','body.html']
  71.     for item in view_item_names:
  72.       with open('views/' + item, encoding='utf8') as file:
  73.           view_parts[item] = file.read()
  74.          
  75.     body_file = view_parts['body.html']
  76.    
  77.     html = body_file.format(
  78.         header=view_parts['header.html'],
  79.         content=generated,
  80.         footer=view_parts['footer.html'])
  81.     try:
  82.       s3.Bucket('desolosers.com').put_object(
  83.         Key= 'index.html',
  84.         Body=(str.encode(html)),
  85.         ContentType='text/html',
  86.         ACL='public-read'
  87.       )
  88.     except botocore.exceptions.ClientError as e:
  89.       print("Unexpected error: %s" % e)
  90.    
  91.     try:
  92.       url = os.environ['cf_api']
  93.       http = urllib3.PoolManager()
  94.       response = http.request('POST', url,
  95.         headers={"X-Auth-Email":EMAIL,"X-Auth-Key":CLOUDFLARE,"Content-Type":"application/json"},
  96.         body='{"purge_everything":true}')
  97.       data = response.data
  98.       if response.data:
  99.         result = json.loads(data)
  100.    
  101.     except Exception as e:
  102.         print ("Unexpected error: %s" % e)
  103.  
  104.  
  105.     return {
  106.         'statusCode': 200,
  107.         'body': 'Done'
  108.     }
  109.  
RAW Paste Data