Advertisement
LemmyNjaria

Python Version For Your Challenge

Dec 1st, 2019
200
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 3.38 KB | None | 0 0
  1. #library for calling GET Requests
  2. import urllib.request
  3. #library for mapping JSON Requests
  4. import json
  5. #library for hadling postgreSQl
  6. import psycopg2
  7.  
  8.  
  9. #this one calls the main function
  10. if __name__ == '__main__':
  11.     #this is the main function
  12.     main()
  13.  
  14. #this is the main function    
  15. def main():
  16.     #define the Url here in your case utakuwa na three urls
  17.     #run this url through Postman like how i taught you and see the JSON view for you to understand
  18.     urlData = "http://mjalimobile.com:81/households/members?userDetail=0722860131"
  19.     #call the getResponse function passing urlData parameter the function iko chini ya this function
  20.     jsonData = getResponse(urlData)
  21.    
  22.     #print the JSON response
  23.     print(jsonData['data']['type'])
  24.    
  25.     # this is where i was telling you about looping through the JSON records
  26.     # i have decided to use for loop instead while loop instead
  27.     # for a successfull loop it calls the function conectToPostGres passing some parameters
  28.     # such as householdNumber,safeWater,treatedWater
  29.     for i in jsonData['data']['attributes']:
  30.         conectToPostGres(i["householdNumber"],i["safeWater"],i["treatedWater"])
  31.  
  32. #this function handles a successful connection of the url
  33. def getResponse(url):
  34.     #opens the url
  35.     operUrl = urllib.request.urlopen(url)
  36.     #cheks if the GET response is successfull
  37.     if(operUrl.getcode()==200):
  38.         #opens the url and reads the content
  39.         data = operUrl.read()
  40.         #decods the JSON content
  41.         jsonData = json.loads(data)
  42.     else:
  43.         print("Error receiving data", operUrl.getcode())
  44.     return jsonData
  45.  
  46. #this function handles successfull connection and storing of data to postgreSQL
  47. def conectToPostGres(householdNumber,safeWater,treatedWater):
  48.    try:
  49.         #handles connection
  50.         #in your case you will change the password and database name umeshika!          
  51.         connection = psycopg2.connect(user="postgres",
  52.                                         password="123",
  53.                                         host="127.0.0.1",
  54.                                         port="5432",
  55.                                         database="members")
  56.         #this calls the cursor
  57.         cursor = connection.cursor()
  58.  
  59.         #this query helps in storying values to the table
  60.         #in this case you will just change the household name to your table name and its column names
  61.         postgres_insert_query = """ INSERT INTO public.household("householdNumber", "safeWater", "treatedWater") VALUES (%s,%s,%s)"""
  62.         #define here the json objects and store them
  63.         record_to_insert = (int(householdNumber), safeWater, treatedWater)
  64.         #execute the cursor
  65.         cursor.execute(postgres_insert_query, record_to_insert)
  66.         #commit the connection
  67.         connection.commit()
  68.         #this counts the rows
  69.         count = cursor.rowcount
  70.         #this prints them if its successfull
  71.         print (count, "Record inserted successfully into member table")
  72.    
  73.    #this handles errors if it occurs    
  74.    except(Exception, psycopg2.Error) as error:
  75.        if(connection):
  76.            print("Failed to insert record into the table",error)
  77.            
  78.    finally:
  79.        #closing database connection
  80.        if(connection):
  81.            cursor.close()
  82.            connection.close()
  83.            print("PostgresQl connection is closed")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement