file.py 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. # Copyright 2014 Google Inc. All rights reserved.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. """Utilities for OAuth.
  15. Utilities for making it easier to work with OAuth 2.0
  16. credentials.
  17. """
  18. import os
  19. import threading
  20. from oauth2client import _helpers
  21. from oauth2client import client
  22. class Storage(client.Storage):
  23. """Store and retrieve a single credential to and from a file."""
  24. def __init__(self, filename):
  25. super(Storage, self).__init__(lock=threading.Lock())
  26. self._filename = filename
  27. def locked_get(self):
  28. """Retrieve Credential from file.
  29. Returns:
  30. oauth2client.client.Credentials
  31. Raises:
  32. IOError if the file is a symbolic link.
  33. """
  34. credentials = None
  35. _helpers.validate_file(self._filename)
  36. try:
  37. f = open(self._filename, 'rb')
  38. content = f.read()
  39. f.close()
  40. except IOError:
  41. return credentials
  42. try:
  43. credentials = client.Credentials.new_from_json(content)
  44. credentials.set_store(self)
  45. except ValueError:
  46. pass
  47. return credentials
  48. def _create_file_if_needed(self):
  49. """Create an empty file if necessary.
  50. This method will not initialize the file. Instead it implements a
  51. simple version of "touch" to ensure the file has been created.
  52. """
  53. if not os.path.exists(self._filename):
  54. old_umask = os.umask(0o177)
  55. try:
  56. open(self._filename, 'a+b').close()
  57. finally:
  58. os.umask(old_umask)
  59. def locked_put(self, credentials):
  60. """Write Credentials to file.
  61. Args:
  62. credentials: Credentials, the credentials to store.
  63. Raises:
  64. IOError if the file is a symbolic link.
  65. """
  66. self._create_file_if_needed()
  67. _helpers.validate_file(self._filename)
  68. f = open(self._filename, 'w')
  69. f.write(credentials.to_json())
  70. f.close()
  71. def locked_delete(self):
  72. """Delete Credentials file.
  73. Args:
  74. credentials: Credentials, the credentials to store.
  75. """
  76. os.unlink(self._filename)