DynamoDB_Communicator.py 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. import boto3
  2. import names
  3. import random
  4. import datetime
  5. # return dynamodb client to authenticate
  6. def dynamodb():
  7. client = boto3.client('dynamodb', region_name=TABLE_REGION)
  8. return client
  9. # the function will produce a random date depending on set range
  10. def random_date():
  11. day = random.randint(10, 20)
  12. month = random.randint(5, 7)
  13. year = 2019
  14. date = datetime.date(year, month, day).strftime("%Y%m%d")
  15. return date
  16. # the function willl generate a random job position
  17. def random_position():
  18. positions = [
  19. 'HR', 'devops', 'data scientist', 'developer', 'janitor',
  20. 'office coordinator'
  21. ]
  22. return random.choice(positions)
  23. # the function will generate random first name
  24. def random_contract_type():
  25. contract_types = ['permanent', 'intern', 'contract']
  26. return random.choice(contract_types)
  27. # the function writes to the table, item with ID partition key
  28. def write_items(id_number):
  29. client = dynamodb()
  30. client.put_item(
  31. TableName=TABLE_NAME,
  32. Item={
  33. "id": {
  34. "S": id_number
  35. },
  36. "contract_type": {
  37. "S": random_contract_type()
  38. },
  39. "last_accessed": {
  40. "N": random_date()
  41. },
  42. "name": {
  43. "S": names.get_first_name()
  44. },
  45. "position": {
  46. "S": random_position()
  47. }
  48. })
  49. print('writing item number {}'.format(id_number))
  50. # the function reads from the table, item with ID partition key
  51. def read_items(id_number):
  52. client = dynamodb()
  53. client.get_item(TableName=TABLE_NAME, Key={"id": {"S": id_number}})
  54. print('reading item number {}'.format(id_number))
  55. # set the number of requests you'd like to make to the table
  56. REQUESTS = 10000
  57. # set table name, where you want to sent the requests
  58. TABLE_NAME = 'elaborate_employee_table'
  59. # in what region does the table reside
  60. TABLE_REGION = 'eu-west-1'
  61. # which action you'd like to do write / read
  62. ACTION = 'read'
  63. # for loop that will go through request number and either write or read from the table
  64. # depending on action type
  65. for request in range(REQUESTS):
  66. if ACTION == 'write':
  67. write_items(str(request))
  68. elif ACTION == 'read':
  69. read_items(str(request))
  70. else:
  71. pass