Guest User

Untitled

a guest
Oct 23rd, 2017
104
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.51 KB | None | 0 0
  1. #!/usr/bin/env python
  2. # Use /usr/bin/env python to support virtual environments
  3. # This script is for Python > 3.6
  4. # -*- coding: utf-8 -*-
  5. """
  6. Test loading mock initial alliances data into a test table with asyncpg and Postgres
  7. """
  8.  
  9. import datetime
  10. import json
  11. import asyncio
  12.  
  13. import asyncpg
  14. import uvloop
  15.  
  16.  
  17. # Load configuration variables from json configuration file
  18. with open('d2_postgres_config.json', 'r') as cfgfile:
  19. CONFIG = json.load(cfgfile)
  20.  
  21. # Setup PostgreSQL client URI
  22. POSTGRES_URI = 'postgres://{}:{}@{}:{}/{}'.format(CONFIG['DB']['USER'], CONFIG['DB']['PASSWORD'],\
  23. CONFIG['DB']['HOST'], CONFIG['DB']['PORT'], CONFIG['DB']['DATABASE'])
  24.  
  25.  
  26. async def main():
  27. """
  28. Try some mock data with with custom jsonb type encoder/decoder
  29. """
  30.  
  31. # Establish a connection to Postgres
  32. conn = await asyncpg.connect(POSTGRES_URI)
  33.  
  34. # Build test input record fields
  35. a_id = 1
  36. a_name = 'Some Test'
  37. a_jsonb_data = [123456]
  38. a_last_updated = datetime.datetime.utcnow()
  39.  
  40. try:
  41.  
  42. # Setup jsonb encoder/decoder
  43. def _encoder(value):
  44. return b'\x01' + json.dumps(value).encode('utf-8')
  45.  
  46. def _decoder(value):
  47. return json.loads(value[1:].decode('utf-8'))
  48.  
  49. await conn.set_type_codec('jsonb', encoder=_encoder, decoder=_decoder, schema='pg_catalog', format='binary')
  50.  
  51. # Drop test table
  52. await conn.execute('DROP TABLE IF EXISTS t_test_table')
  53.  
  54. # Execute a statement to create a new table.
  55. await conn.execute('''
  56. CREATE TABLE t_test_table(
  57. id INT4 NOT NULL,
  58. name TEXT NOT NULL,
  59. jsonb_data JSONB NOT NULL,
  60. last_updated TIMESTAMP(0) NOT NULL DEFAULT NOW(),
  61. CONSTRAINT pk_t_test_table_id PRIMARY KEY (id)
  62. )
  63. ''')
  64.  
  65. # Insert a record into the created table.
  66. await conn.execute('''
  67. INSERT INTO t_test_table(id, name, jsonb_data, last_updated) VALUES($1, $2, $3, $4)
  68. ''', a_id, a_name, a_jsonb_data, a_last_updated)
  69.  
  70. # Select a row from the table.
  71. row = await conn.fetchrow('SELECT * FROM t_test_table WHERE id = $1', a_id)
  72. print('----------')
  73. print('Returned row: ')
  74. print('{}, {}, {}, {}'.format(row['id'], row['name'], row['jsonb_data'], row['last_updated']))
  75. print('----------')
  76.  
  77. finally:
  78. # Close the connection.
  79. await conn.close()
  80.  
  81.  
  82. # Run the task
  83. asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())
  84. asyncio.get_event_loop().run_until_complete(main())
Add Comment
Please, Sign In to add comment