Guest User

Untitled

a guest
Nov 16th, 2017
110
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 5.40 KB | None | 0 0
  1. import psycopg2
  2. import logging # will allow you to track what happens in the application, and identify problems with the code
  3. import argparse
  4. import sys
  5.  
  6. # set the log output file, and the log level
  7. logging.basicConfig(filename="snippets.log", level=logging.DEBUG)
  8. logging.debug("Connecting to PostgreSQL")
  9.  
  10. # connect to database from python
  11. connection = psycopg2.connect(
  12. database = "drinkwater",
  13. user = "postgres",
  14. password = "lawncare"
  15. )
  16.  
  17. logging.debug("Database connection established.")
  18.  
  19.  
  20. def put(name,snippet,hide=False):
  21. """Store a snippet with an associated name."""
  22. # import pdb; pdb.set_trace()
  23. logging.info("Storing snippet {!r}: {!r}".format(name, snippet))
  24.  
  25. with connection.cursor() as cursor:
  26. try:
  27. command = "insert into snippets values (%s, %s, %s)"
  28. cursor.execute(command, (name, snippet, hide))
  29. except psycopg2.IntegrityError:
  30. connection.rollback()
  31. command = "update snippets set message=%s, hidden=%s where keyword=%s"
  32. cursor.execute(command, (snippet,hide,name))
  33. connection.commit()
  34. logging.debug("Snippet stored successfully.")
  35. return name, snippet
  36.  
  37. # connection.cursor method: creating a cursor object - allows us to run SQL
  38. # commands in Postgres session insert into statement: constructing a string
  39. # which contains insert into, with two placeholders for keyword and message
  40. # (%s) cursor.execute: running the command on the database, substituting the
  41. # snippet keyword and message by passing them as a tuple connection.commit:
  42. # saving changes to the database
  43.  
  44. ### GET CHALLENGE ###
  45. # Try to implement the get() function
  46. # Construct a select statement to retrieve the snippet with a given keyword
  47. # Run the statement on the database
  48. # Fetch the corresponding row from the database
  49. # Run the message from the row
  50.  
  51. def get(name):
  52. """Retrieve the snippet with a given keyword"""
  53. logging.info("Retrieving snippet {!r}".format(name))
  54.  
  55. with connection.cursor() as cursor:
  56. cursor.execute("select message from snippets where keyword=%s", (name,))
  57. row = cursor.fetchone()
  58. logging.debug("Snippet retrieved successfully.")
  59. if not row:
  60. # If no snippet was found with that name
  61. logging.debug("Snippet does not exist")
  62. return "404: Snippet Not Found"
  63. else:
  64. logging.debug("Snippet retrieved successfully.")
  65. return row[0]
  66.  
  67. # Snippets Catalog
  68. # Create Catalog function: Provides list of keywords to select from
  69. def catalog():
  70. """Query keywords from snippets table"""
  71. # import pdb; pdb.set_trace()
  72. logging.info("Querying the database")
  73. with connection.cursor() as cursor:
  74. command = "select keyword, message from snippets where hidden=False \
  75. order by keyword ASC"
  76. cursor.execute(command)
  77. rows = cursor.fetchall()
  78. for x in rows:
  79. print("the keyworrd is: {}, the message is: {}".format(x[0], x[1]))
  80. logging.debug("Query complete")
  81.  
  82. # Create Search function: Search for word within snippet messages
  83.  
  84. def search(word):
  85. """Return a list of snippets containing a given word"""
  86. logging.info("Searching snippets for {}".format(word))
  87. with connection.cursor() as cursor:
  88. cursor.execute(
  89. "select * from snippets where hidden=False \
  90. and message like '%{}%'".format(word))
  91. # select * from snippets where hidden=False and message like %insert%
  92. rows = cursor.fetchall()
  93. for row in rows:
  94. print(row)
  95. logging.debug("Search complete")
  96.  
  97.  
  98. def main():
  99. # import pdb; pdb.set_trace()
  100. """Main function"""
  101. logging.info("Constructing parser")
  102. parser = argparse.ArgumentParser(description="Store and retrieve snippets of text")
  103.  
  104. subparsers = parser.add_subparsers(dest="command", help="Available commands")
  105.  
  106. # Subparser for the put command
  107. logging.debug("Constructing put subparser")
  108. put_parser = subparsers.add_parser("put", help="Store a snippet")
  109. put_parser.add_argument("name", help="Name of the snippet")
  110. put_parser.add_argument("snippet", help="Snippet text")
  111.  
  112.  
  113. # Subparser for the get command
  114. get_parser = subparsers.add_parser("get", help="Retrieve a snippet")
  115. get_parser.add_argument("name", help="Name of the snippet")
  116.  
  117. # Subparser for the catalog command
  118. catalog_parser = subparsers.add_parser("catalog", help = "List keywords fron snippet")
  119.  
  120. # Subparser for the search command
  121. import pdb; pdb.set_trace()
  122. search_parser = subparsers.add_parser("search", help = "Query snippets based on word")
  123. search_parser.add_argument("word", help = "word in snippet")
  124.  
  125. arguments = parser.parse_args()
  126.  
  127. # Convert parsed arguments from Namespace to dictionary
  128. arguments = vars(arguments)
  129. command = arguments.pop("command")
  130.  
  131. if command == "put":
  132. name, snippet = put(**arguments)
  133. print("Stored {!r} as {!r}".format(snippet, name))
  134. elif command == "get":
  135. snippet = get(**arguments)
  136. print("Retrieved snippet: {!r}".format(snippet))
  137. elif command == "catalog":
  138. catalog()
  139. print("Retrieved keywords")
  140. # elif command == "search":
  141. # string = search(**arguments)
  142. # print
  143. # print("Search complete")
  144. elif command == "search":
  145. word = search(**arguments)
  146. print()
  147. print("Search complete")
  148. print("Found {} in these messages".format(word))
  149.  
  150. if __name__ == "__main__":
  151. main()
Add Comment
Please, Sign In to add comment