Advertisement
Guest User

Untitled

a guest
Sep 22nd, 2017
116
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 13.17 KB | None | 0 0
  1. #program  one
  2.  
  3. import gdata.docs.data
  4. import gdata.docs.client
  5. import gdata.docs.service
  6. import gdata.spreadsheet.service
  7. import getpass
  8.  
  9. user = raw_input('Please enter your username: ')
  10. pw = getpass.getpass()
  11. source = ' '
  12. gd_client = gdata.docs.service.DocsService()
  13. gd_client.ClientLogin(user, pw, source=source)
  14.  
  15. file_path = raw_input('enter path to file: ')
  16.  
  17. title = raw_input('please enter name of the reporty: ')
  18. content_type = gdata.docs.service.SUPPORTED_FILETYPES['HTML']
  19. ms = gdata.MediaSource(file_path=file_path, content_type=content_type)
  20.  
  21. entry = gd_client.Upload(ms, title)
  22.  
  23. #program two
  24. import gdata.docs.service
  25. import getpass
  26. client = gdata.docs.service.DocsService()
  27. user = raw_input('enter user email')
  28. pw = getpass.getpass()
  29.  
  30. client.ClientLogin(user,pw)
  31. documents_feed = client.GetDocumentListFeed()
  32. for document_entry in documents_feed.entry:
  33.   print document_entry.title.text
  34.  
  35.  
  36. # A hack to implement both..
  37. import gdata.docs.data
  38. import gdata.docs.client
  39. import gdata.docs.service
  40. import gdata.spreadsheet.service
  41. import getpass
  42.  
  43. #def GdatLog(self,user,pw):
  44. client = gdata.docs.service.DocsService()
  45. user = raw_input('Please enter your username: ')
  46. pw = getpass.getpass()
  47. source = ' '
  48. gd_client = gdata.docs.service.DocsService()
  49. gd_client.ClientLogin(user, pw, source=source)
  50.  
  51. print """"
  52.    Please enter your choice of what you would like to do
  53.    1 :Get the list of documents on your Google Docs account
  54.    2 :Upload a Csv file data to a Spreadsheet
  55.    3 :Upload a file of Html format """
  56.    
  57. choice = input('enter your choice ::')
  58.  
  59. #def option(choice):
  60.  
  61. if choice == 1:
  62.         documents_feed = gd_client.GetDocumentListFeed()
  63.         for document_entry in documents_feed.entry:
  64.             print document_entry.title.text
  65.  
  66. elif choice == 2:
  67.         file_path = raw_input('enter path to csv file: ')
  68.  
  69.         title = raw_input('please enter name of the spreadsheet: ')
  70.         content_type = gdata.docs.service.SUPPORTED_FILETYPES['CSV']
  71.         ms = gdata.MediaSource(file_path=file_path, content_type=content_type)
  72.  
  73.         entry = gd_client.Upload(ms, title)
  74.  
  75. elif choice == 3:
  76.         file_path = raw_input('enter path to ', content_type, 'file: ')
  77.  
  78.         title = raw_input('please enter name of the spreadsheet: ')
  79.         content_type = gdata.docs.service.SUPPORTED_FILETYPES['HTML']
  80.         ms = gdata.MediaSource(file_path=file_path, content_type=content_type)
  81.  
  82.         entry = gd_client.Upload(ms, title)
  83.  
  84. # a more Advance hack ..which does it all
  85. import sys
  86. import re
  87. import os.path
  88. import getopt
  89. import getpass
  90. import gdata.docs.service
  91. import gdata.spreadsheet.service
  92.  
  93.  
  94. def truncate(content, length=15, suffix='...'):
  95.   if len(content) <= length:
  96.     return content
  97.   else:
  98.     return content[:length] + suffix
  99.  
  100.  
  101. class DocsSample(object):
  102.   """A DocsSample object demonstrates the Document List feed."""
  103.  
  104.   def __init__(self, email, password):
  105.     """Constructor for the DocsSample object.
  106.  
  107.    Takes an email and password corresponding to a gmail account to
  108.    demonstrate the functionality of the Document List feed.
  109.  
  110.    Args:
  111.      email: [string] The e-mail address of the account to use for the sample.
  112.      password: [string] The password corresponding to the account specified by
  113.          the email parameter.
  114.  
  115.    Returns:
  116.      A DocsSample object used to run the sample demonstrating the
  117.      functionality of the Document List feed.
  118.    """
  119.     source = 'Document List Python Sample'
  120.     self.gd_client = gdata.docs.service.DocsService()
  121.     self.gd_client.ClientLogin(email, password, source=source)
  122.  
  123.     # Setup a spreadsheets service for downloading spreadsheets
  124.     self.gs_client = gdata.spreadsheet.service.SpreadsheetsService()
  125.     self.gs_client.ClientLogin(email, password, source=source)
  126.  
  127.   def _PrintFeed(self, feed):
  128.     """Prints out the contents of a feed to the console.
  129.  
  130.    Args:
  131.      feed: A gdata.docs.DocumentListFeed instance.
  132.    """
  133.     print '\n'
  134.     if not feed.entry:
  135.       print 'No entries in feed.\n'
  136.     print '%-18s %-12s %s' % ('TITLE', 'TYPE', 'RESOURCE ID')
  137.     for entry in feed.entry:
  138.       print '%-18s %-12s %s' % (truncate(entry.title.text.encode('UTF-8')),
  139.                                 entry.GetDocumentType(),
  140.                                 entry.resourceId.text)
  141.  
  142.   def _GetFileExtension(self, file_name):
  143.     """Returns the uppercase file extension for a file.
  144.  
  145.    Args:
  146.      file_name: [string] The basename of a filename.
  147.  
  148.    Returns:
  149.      A string containing the file extension of the file.
  150.    """
  151.     match = re.search('.*\.([a-zA-Z]{3,}$)', file_name)
  152.     if match:
  153.       return match.group(1).upper()
  154.     return False
  155.  
  156.   def _UploadMenu(self):
  157.     """Prompts that enable a user to upload a file to the Document List feed."""
  158.     file_path = ''
  159.     file_path = raw_input('Enter path to file: ')
  160.  
  161.     if not file_path:
  162.       return
  163.     elif not os.path.isfile(file_path):
  164.       print 'Not a valid file.'
  165.       return
  166.  
  167.     file_name = os.path.basename(file_path)
  168.     ext = self._GetFileExtension(file_name)
  169.  
  170.     if not ext or ext not in gdata.docs.service.SUPPORTED_FILETYPES:
  171.       print 'File type not supported. Check the file extension.'
  172.       return
  173.     else:
  174.       content_type = gdata.docs.service.SUPPORTED_FILETYPES[ext]
  175.  
  176.     title = ''
  177.     while not title:
  178.       title = raw_input('Enter name for document: ')
  179.  
  180.     try:
  181.       ms = gdata.MediaSource(file_path=file_path, content_type=content_type)
  182.     except IOError:
  183.       print 'Problems reading file. Check permissions.'
  184.       return
  185.  
  186.     if ext in ['CSV', 'ODS', 'XLS', 'XLSX']:
  187.       print 'Uploading spreadsheet...'
  188.     elif ext in ['PPT', 'PPS']:
  189.       print 'Uploading presentation...'
  190.     else:
  191.       print 'Uploading word processor document...'
  192.  
  193.     entry = self.gd_client.Upload(ms, title)
  194.  
  195.     if entry:
  196.       print 'Upload successful!'
  197.       print 'Document now accessible at:', entry.GetAlternateLink().href
  198.     else:
  199.       print 'Upload error.'
  200.  
  201.   def _DownloadMenu(self):
  202.     """Prompts that enable a user to download a local copy of a document."""
  203.     resource_id = ''
  204.     resource_id = raw_input('Enter an resource id: ')
  205.     file_path = ''
  206.     file_path = raw_input('Save file to: ')
  207.  
  208.     if not file_path or not resource_id:
  209.       return
  210.  
  211.     file_name = os.path.basename(file_path)
  212.     ext = self._GetFileExtension(file_name)
  213.  
  214.     if not ext or ext not in gdata.docs.service.SUPPORTED_FILETYPES:
  215.       print 'File type not supported. Check the file extension.'
  216.       return
  217.     else:
  218.       content_type = gdata.docs.service.SUPPORTED_FILETYPES[ext]
  219.  
  220.     doc_type = resource_id[:resource_id.find(':')]
  221.  
  222.     # When downloading a spreadsheet, the authenticated request needs to be
  223.     # sent with the spreadsheet service's auth token.
  224.     if doc_type == 'spreadsheet':
  225.       print 'Downloading spreadsheet to %s...' % (file_path,)
  226.       docs_token = self.gd_client.GetClientLoginToken()
  227.       self.gd_client.SetClientLoginToken(self.gs_client.GetClientLoginToken())
  228.       self.gd_client.Export(resource_id, file_path, gid=0)
  229.       self.gd_client.SetClientLoginToken(docs_token)
  230.     else:
  231.       print 'Downloading document to %s...' % (file_path,)
  232.       self.gd_client.Export(resource_id, file_path)
  233.  
  234.   def _ListDocuments(self):
  235.     """Retrieves and displays a list of documents based on the user's choice."""
  236.     print 'Retrieve (all/document/folder/presentation/spreadsheet/pdf): '
  237.     category = raw_input('Enter a category: ')
  238.  
  239.     if category == 'all':
  240.       feed = self.gd_client.GetDocumentListFeed()
  241.     elif category == 'folder':
  242.       query = gdata.docs.service.DocumentQuery(categories=['folder'],
  243.                                                params={'showfolders': 'true'})
  244.       feed = self.gd_client.Query(query.ToUri())
  245.     else:
  246.       query = gdata.docs.service.DocumentQuery(categories=[category])
  247.       feed = self.gd_client.Query(query.ToUri())
  248.  
  249.     self._PrintFeed(feed)
  250.  
  251.   def _ListAclPermissions(self):
  252.     """Retrieves a list of a user's folders and displays them."""
  253.     resource_id = raw_input('Enter an resource id: ')
  254.     query = gdata.docs.service.DocumentAclQuery(resource_id)
  255.     print '\nListing document permissions:'
  256.     feed = self.gd_client.GetDocumentListAclFeed(query.ToUri())
  257.     for acl_entry in feed.entry:
  258.       print '%s - %s (%s)' % (acl_entry.role.value, acl_entry.scope.value,
  259.                               acl_entry.scope.type)
  260.  
  261.   def _ModifyAclPermissions(self):
  262.     """Create or updates the ACL entry on an existing document."""
  263.     resource_id = raw_input('Enter an resource id: ')
  264.     email = raw_input('Enter an email address: ')
  265.     role_value = raw_input('Enter a permission (reader/writer/owner/remove): ')
  266.  
  267.     uri = gdata.docs.service.DocumentAclQuery(resource_id).ToUri()
  268.     acl_feed = self.gd_client.GetDocumentListAclFeed(uri)
  269.  
  270.     found_acl_entry = None
  271.     for acl_entry in acl_feed.entry:
  272.       if acl_entry.scope.value == email:
  273.         found_acl_entry = acl_entry
  274.         break
  275.  
  276.     if found_acl_entry:
  277.       if role_value == 'remove':
  278.         # delete ACL entry
  279.         self.gd_client.Delete(found_acl_entry.GetEditLink().href)
  280.       else:
  281.         # update ACL entry
  282.         found_acl_entry.role.value = role_value
  283.         updated_entry = self.gd_client.Put(
  284.             found_acl_entry, found_acl_entry.GetEditLink().href,
  285.             converter=gdata.docs.DocumentListAclEntryFromString)
  286.     else:
  287.       scope = gdata.docs.Scope(value=email, type='user')
  288.       role = gdata.docs.Role(value=role_value)
  289.       acl_entry = gdata.docs.DocumentListAclEntry(scope=scope, role=role)
  290.       inserted_entry = self.gd_client.Post(
  291.         acl_entry, uri, converter=gdata.docs.DocumentListAclEntryFromString)
  292.  
  293.     print '\nListing document permissions:'
  294.     acl_feed = self.gd_client.GetDocumentListAclFeed(uri)
  295.     for acl_entry in acl_feed.entry:
  296.       print '%s - %s (%s)' % (acl_entry.role.value, acl_entry.scope.value,
  297.                               acl_entry.scope.type)
  298.  
  299.   def _FullTextSearch(self):
  300.     """Searches a user's documents for a text string.
  301.  
  302.    Provides prompts to search a user's documents and displays the results
  303.    of such a search. The text_query parameter of the DocumentListQuery object
  304.    corresponds to the contents of the q parameter in the feed. Note that this
  305.    parameter searches the content of documents, not just their titles.
  306.    """
  307.     input = raw_input('Enter search term: ')
  308.     query = gdata.docs.service.DocumentQuery(text_query=input)
  309.     feed = self.gd_client.Query(query.ToUri())
  310.     self._PrintFeed(feed)
  311.  
  312.   def _PrintMenu(self):
  313.     """Displays a menu of options for the user to choose from."""
  314.     print ('\nDocument List Sample\n'
  315.            '1) List your documents.\n'
  316.            '2) Search your documents.\n'
  317.            '3) Upload a document.\n'
  318.            '4) Download a document.\n'
  319.            "5) List a document's permissions.\n"
  320.            "6) Add/change a document's permissions.\n"
  321.            '7) Exit.\n')
  322.  
  323.   def _GetMenuChoice(self, max):
  324.     """Retrieves the menu selection from the user.
  325.  
  326.    Args:
  327.      max: [int] The maximum number of allowed choices (inclusive)
  328.  
  329.    Returns:
  330.      The integer of the menu item chosen by the user.
  331.    """
  332.     while True:
  333.       input = raw_input('> ')
  334.  
  335.       try:
  336.         num = int(input)
  337.       except ValueError:
  338.         print 'Invalid choice. Please choose a value between 1 and', max
  339.         continue
  340.  
  341.       if num > max or num < 1:
  342.         print 'Invalid choice. Please choose a value between 1 and', max
  343.       else:
  344.         return num
  345.  
  346.   def Run(self):
  347.     """Prompts the user to choose funtionality to be demonstrated."""
  348.     try:
  349.       while True:
  350.         self._PrintMenu()
  351.         choice = self._GetMenuChoice(7)
  352.  
  353.         if choice == 1:
  354.           self._ListDocuments()
  355.         elif choice == 2:
  356.           self._FullTextSearch()
  357.         elif choice == 3:
  358.           self._UploadMenu()
  359.         elif choice == 4:
  360.           self._DownloadMenu()
  361.         elif choice == 5:
  362.           self._ListAclPermissions()
  363.         elif choice == 6:
  364.           self._ModifyAclPermissions()
  365.         elif choice == 7:
  366.           print '\nGoodbye.'
  367.           return
  368.     except KeyboardInterrupt:
  369.       print '\nGoodbye.'
  370.       return
  371.  
  372.  
  373. def main():
  374.   """Demonstrates use of the Docs extension using the DocsSample object."""
  375.   # Parse command line options
  376.   try:
  377.     opts, args = getopt.getopt(sys.argv[1:], '', ['user=', 'pw='])
  378.   except getopt.error, msg:
  379.     print 'python docs_example.py --user [username] --pw [password] '
  380.     sys.exit(2)
  381.  
  382.   user = ''
  383.   pw = ''
  384.   key = ''
  385.   # Process options
  386.   for option, arg in opts:
  387.     if option == '--user':
  388.       user = arg
  389.     elif option == '--pw':
  390.       pw = arg
  391.  
  392.   while not user:
  393.     print 'NOTE: Please run these tests only with a test account.'
  394.     user = raw_input('Please enter your username: ')
  395.   while not pw:
  396.     pw = getpass.getpass()
  397.     if not pw:
  398.       print 'Password cannot be blank.'
  399.  
  400.   try:
  401.     sample = DocsSample(user, pw)
  402.   except gdata.service.BadAuthentication:
  403.     print 'Invalid user credentials given.'
  404.     return
  405.  
  406.   sample.Run()
  407.  
  408.  
  409. if __name__ == '__main__':
  410.   main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement