code
stringlengths
1
1.72M
language
stringclasses
1 value
#!/usr/bin/env python """ FCKeditor - The text editor for Internet - http://www.fckeditor.net Copyright (C) 2003-2008 Frederico Caldeira Knabben == BEGIN LICENSE == Licensed under the terms of any of the following licenses at your choice: - GNU General Public License Version 2 or later (the "GPL") http://www.gnu.org/licenses/gpl.html - GNU Lesser General Public License Version 2.1 or later (the "LGPL") http://www.gnu.org/licenses/lgpl.html - Mozilla Public License Version 1.1 or later (the "MPL") http://www.mozilla.org/MPL/MPL-1.1.html == END LICENSE == This is the "File Uploader" for Python """ import os from fckutil import * from fckcommands import * # default command's implementation from fckconnector import FCKeditorConnectorBase # import base connector import config as Config class FCKeditorQuickUpload( FCKeditorConnectorBase, UploadFileCommandMixin, BaseHttpMixin, BaseHtmlMixin): def doResponse(self): "Main function. Process the request, set headers and return a string as response." # Check if this connector is disabled if not(Config.Enabled): return self.sendUploadResults(1, "This file uploader is disabled. Please check the \"editor/filemanager/connectors/py/config.py\"") command = 'QuickUpload' # The file type (from the QueryString, by default 'File'). resourceType = self.request.get('Type','File') currentFolder = getCurrentFolder(self.request.get("CurrentFolder","")) # Check for invalid paths if currentFolder is None: return self.sendUploadResults(102, '', '', "") # Check if it is an allowed command if ( not command in Config.ConfigAllowedCommands ): return self.sendUploadResults( 1, '', '', 'The %s command isn\'t allowed' % command ) if ( not resourceType in Config.ConfigAllowedTypes ): return self.sendUploadResults( 1, '', '', 'Invalid type specified' ) # Setup paths self.userFilesFolder = Config.QuickUploadAbsolutePath[resourceType] self.webUserFilesFolder = Config.QuickUploadPath[resourceType] if not self.userFilesFolder: # no absolute path given (dangerous...) self.userFilesFolder = mapServerPath(self.environ, self.webUserFilesFolder) # Ensure that the directory exists. if not os.path.exists(self.userFilesFolder): try: self.createServerFoldercreateServerFolder( self.userFilesFolder ) except: return self.sendError(1, "This connector couldn\'t access to local user\'s files directories. Please check the UserFilesAbsolutePath in \"editor/filemanager/connectors/py/config.py\" and try again. ") # File upload doesn't have to return XML, so intercept here return self.uploadFile(resourceType, currentFolder) # Running from command line (plain old CGI) if __name__ == '__main__': try: # Create a Connector Instance conn = FCKeditorQuickUpload() data = conn.doResponse() for header in conn.headers: if not header is None: print '%s: %s' % header print print data except: print "Content-Type: text/plain" print import cgi cgi.print_exception()
Python
#!/usr/bin/env python """ FCKeditor - The text editor for Internet - http://www.fckeditor.net Copyright (C) 2003-2008 Frederico Caldeira Knabben == BEGIN LICENSE == Licensed under the terms of any of the following licenses at your choice: - GNU General Public License Version 2 or later (the "GPL") http://www.gnu.org/licenses/gpl.html - GNU Lesser General Public License Version 2.1 or later (the "LGPL") http://www.gnu.org/licenses/lgpl.html - Mozilla Public License Version 1.1 or later (the "MPL") http://www.mozilla.org/MPL/MPL-1.1.html == END LICENSE == Base Connector for Python (CGI and WSGI). See config.py for configuration settings """ import cgi, os from fckutil import * from fckcommands import * # default command's implementation from fckoutput import * # base http, xml and html output mixins import config as Config class FCKeditorConnectorBase( object ): "The base connector class. Subclass it to extend functionality (see Zope example)" def __init__(self, environ=None): "Constructor: Here you should parse request fields, initialize variables, etc." self.request = FCKeditorRequest(environ) # Parse request self.headers = [] # Clean Headers if environ: self.environ = environ else: self.environ = os.environ # local functions def setHeader(self, key, value): self.headers.append ((key, value)) return class FCKeditorRequest(object): "A wrapper around the request object" def __init__(self, environ): if environ: # WSGI self.request = cgi.FieldStorage(fp=environ['wsgi.input'], environ=environ, keep_blank_values=1) self.environ = environ else: # plain old cgi self.environ = os.environ self.request = cgi.FieldStorage() if 'REQUEST_METHOD' in self.environ and 'QUERY_STRING' in self.environ: if self.environ['REQUEST_METHOD'].upper()=='POST': # we are in a POST, but GET query_string exists # cgi parses by default POST data, so parse GET QUERY_STRING too self.get_request = cgi.FieldStorage(fp=None, environ={ 'REQUEST_METHOD':'GET', 'QUERY_STRING':self.environ['QUERY_STRING'], }, ) else: self.get_request={} def has_key(self, key): return self.request.has_key(key) or self.get_request.has_key(key) def get(self, key, default=None): if key in self.request.keys(): field = self.request[key] elif key in self.get_request.keys(): field = self.get_request[key] else: return default if hasattr(field,"filename") and field.filename: #file upload, do not convert return value return field else: return field.value
Python
#!/usr/bin/env python """ FCKeditor - The text editor for Internet - http://www.fckeditor.net Copyright (C) 2003-2008 Frederico Caldeira Knabben == BEGIN LICENSE == Licensed under the terms of any of the following licenses at your choice: - GNU General Public License Version 2 or later (the "GPL") http://www.gnu.org/licenses/gpl.html - GNU Lesser General Public License Version 2.1 or later (the "LGPL") http://www.gnu.org/licenses/lgpl.html - Mozilla Public License Version 1.1 or later (the "MPL") http://www.mozilla.org/MPL/MPL-1.1.html == END LICENSE == Connector for Python (CGI and WSGI). See config.py for configuration settings """ import os from fckutil import * from fckcommands import * # default command's implementation from fckoutput import * # base http, xml and html output mixins from fckconnector import FCKeditorConnectorBase # import base connector import config as Config class FCKeditorConnector( FCKeditorConnectorBase, GetFoldersCommandMixin, GetFoldersAndFilesCommandMixin, CreateFolderCommandMixin, UploadFileCommandMixin, BaseHttpMixin, BaseXmlMixin, BaseHtmlMixin ): "The Standard connector class." def doResponse(self): "Main function. Process the request, set headers and return a string as response." s = "" # Check if this connector is disabled if not(Config.Enabled): return self.sendError(1, "This connector is disabled. Please check the connector configurations in \"editor/filemanager/connectors/py/config.py\" and try again.") # Make sure we have valid inputs for key in ("Command","Type","CurrentFolder"): if not self.request.has_key (key): return # Get command, resource type and current folder command = self.request.get("Command") resourceType = self.request.get("Type") currentFolder = getCurrentFolder(self.request.get("CurrentFolder")) # Check for invalid paths if currentFolder is None: return self.sendError(102, "") # Check if it is an allowed command if ( not command in Config.ConfigAllowedCommands ): return self.sendError( 1, 'The %s command isn\'t allowed' % command ) if ( not resourceType in Config.ConfigAllowedTypes ): return self.sendError( 1, 'Invalid type specified' ) # Setup paths if command == "QuickUpload": self.userFilesFolder = Config.QuickUploadAbsolutePath[resourceType] self.webUserFilesFolder = Config.QuickUploadPath[resourceType] else: self.userFilesFolder = Config.FileTypesAbsolutePath[resourceType] self.webUserFilesFolder = Config.FileTypesPath[resourceType] if not self.userFilesFolder: # no absolute path given (dangerous...) self.userFilesFolder = mapServerPath(self.environ, self.webUserFilesFolder) # Ensure that the directory exists. if not os.path.exists(self.userFilesFolder): try: self.createServerFoldercreateServerFolder( self.userFilesFolder ) except: return self.sendError(1, "This connector couldn\'t access to local user\'s files directories. Please check the UserFilesAbsolutePath in \"editor/filemanager/connectors/py/config.py\" and try again. ") # File upload doesn't have to return XML, so intercept here if (command == "FileUpload"): return self.uploadFile(resourceType, currentFolder) # Create Url url = combinePaths( self.webUserFilesFolder, currentFolder ) # Begin XML s += self.createXmlHeader(command, resourceType, currentFolder, url) # Execute the command selector = {"GetFolders": self.getFolders, "GetFoldersAndFiles": self.getFoldersAndFiles, "CreateFolder": self.createFolder, } s += selector[command](resourceType, currentFolder) s += self.createXmlFooter() return s # Running from command line (plain old CGI) if __name__ == '__main__': try: # Create a Connector Instance conn = FCKeditorConnector() data = conn.doResponse() for header in conn.headers: print '%s: %s' % header print print data except: print "Content-Type: text/plain" print import cgi cgi.print_exception()
Python
#!/usr/bin/env python """ FCKeditor - The text editor for Internet - http://www.fckeditor.net Copyright (C) 2003-2008 Frederico Caldeira Knabben == BEGIN LICENSE == Licensed under the terms of any of the following licenses at your choice: - GNU General Public License Version 2 or later (the "GPL") http://www.gnu.org/licenses/gpl.html - GNU Lesser General Public License Version 2.1 or later (the "LGPL") http://www.gnu.org/licenses/lgpl.html - Mozilla Public License Version 1.1 or later (the "MPL") http://www.mozilla.org/MPL/MPL-1.1.html == END LICENSE == Connector for Python and Zope. This code was not tested at all. It just was ported from pre 2.5 release, so for further reference see \editor\filemanager\browser\default\connectors\py\connector.py in previous releases. """ from fckutil import * from connector import * import config as Config class FCKeditorConnectorZope(FCKeditorConnector): """ Zope versiof FCKeditorConnector """ # Allow access (Zope) __allow_access_to_unprotected_subobjects__ = 1 def __init__(self, context=None): """ Constructor """ FCKeditorConnector.__init__(self, environ=None) # call superclass constructor # Instance Attributes self.context = context self.request = FCKeditorRequest(context) def getZopeRootContext(self): if self.zopeRootContext is None: self.zopeRootContext = self.context.getPhysicalRoot() return self.zopeRootContext def getZopeUploadContext(self): if self.zopeUploadContext is None: folderNames = self.userFilesFolder.split("/") c = self.getZopeRootContext() for folderName in folderNames: if (folderName <> ""): c = c[folderName] self.zopeUploadContext = c return self.zopeUploadContext def setHeader(self, key, value): self.context.REQUEST.RESPONSE.setHeader(key, value) def getFolders(self, resourceType, currentFolder): # Open the folders node s = "" s += """<Folders>""" zopeFolder = self.findZopeFolder(resourceType, currentFolder) for (name, o) in zopeFolder.objectItems(["Folder"]): s += """<Folder name="%s" />""" % ( convertToXmlAttribute(name) ) # Close the folders node s += """</Folders>""" return s def getZopeFoldersAndFiles(self, resourceType, currentFolder): folders = self.getZopeFolders(resourceType, currentFolder) files = self.getZopeFiles(resourceType, currentFolder) s = folders + files return s def getZopeFiles(self, resourceType, currentFolder): # Open the files node s = "" s += """<Files>""" zopeFolder = self.findZopeFolder(resourceType, currentFolder) for (name, o) in zopeFolder.objectItems(["File","Image"]): s += """<File name="%s" size="%s" />""" % ( convertToXmlAttribute(name), ((o.get_size() / 1024) + 1) ) # Close the files node s += """</Files>""" return s def findZopeFolder(self, resourceType, folderName): # returns the context of the resource / folder zopeFolder = self.getZopeUploadContext() folderName = self.removeFromStart(folderName, "/") folderName = self.removeFromEnd(folderName, "/") if (resourceType <> ""): try: zopeFolder = zopeFolder[resourceType] except: zopeFolder.manage_addProduct["OFSP"].manage_addFolder(id=resourceType, title=resourceType) zopeFolder = zopeFolder[resourceType] if (folderName <> ""): folderNames = folderName.split("/") for folderName in folderNames: zopeFolder = zopeFolder[folderName] return zopeFolder def createFolder(self, resourceType, currentFolder): # Find out where we are zopeFolder = self.findZopeFolder(resourceType, currentFolder) errorNo = 0 errorMsg = "" if self.request.has_key("NewFolderName"): newFolder = self.request.get("NewFolderName", None) zopeFolder.manage_addProduct["OFSP"].manage_addFolder(id=newFolder, title=newFolder) else: errorNo = 102 return self.sendErrorNode ( errorNo, errorMsg ) def uploadFile(self, resourceType, currentFolder, count=None): zopeFolder = self.findZopeFolder(resourceType, currentFolder) file = self.request.get("NewFile", None) fileName = self.getFileName(file.filename) fileNameOnly = self.removeExtension(fileName) fileExtension = self.getExtension(fileName).lower() if (count): nid = "%s.%s.%s" % (fileNameOnly, count, fileExtension) else: nid = fileName title = nid try: zopeFolder.manage_addProduct['OFSP'].manage_addFile( id=nid, title=title, file=file.read() ) except: if (count): count += 1 else: count = 1 return self.zopeFileUpload(resourceType, currentFolder, count) return self.sendUploadResults( 0 ) class FCKeditorRequest(object): "A wrapper around the request object" def __init__(self, context=None): r = context.REQUEST self.request = r def has_key(self, key): return self.request.has_key(key) def get(self, key, default=None): return self.request.get(key, default) """ Running from zope, you will need to modify this connector. If you have uploaded the FCKeditor into Zope (like me), you need to move this connector out of Zope, and replace the "connector" with an alias as below. The key to it is to pass the Zope context in, as we then have a like to the Zope context. ## Script (Python) "connector.py" ##bind container=container ##bind context=context ##bind namespace= ##bind script=script ##bind subpath=traverse_subpath ##parameters=*args, **kws ##title=ALIAS ## import Products.zope as connector return connector.FCKeditorConnectorZope(context=context).doResponse() """
Python
#!/usr/bin/env python """ FCKeditor - The text editor for Internet - http://www.fckeditor.net Copyright (C) 2003-2008 Frederico Caldeira Knabben == BEGIN LICENSE == Licensed under the terms of any of the following licenses at your choice: - GNU General Public License Version 2 or later (the "GPL") http://www.gnu.org/licenses/gpl.html - GNU Lesser General Public License Version 2.1 or later (the "LGPL") http://www.gnu.org/licenses/lgpl.html - Mozilla Public License Version 1.1 or later (the "MPL") http://www.mozilla.org/MPL/MPL-1.1.html == END LICENSE == Connector for Python (CGI and WSGI). """ from time import gmtime, strftime import string def escape(text, replace=string.replace): """ Converts the special characters '<', '>', and '&'. RFC 1866 specifies that these characters be represented in HTML as &lt; &gt; and &amp; respectively. In Python 1.5 we use the new string.replace() function for speed. """ text = replace(text, '&', '&amp;') # must be done 1st text = replace(text, '<', '&lt;') text = replace(text, '>', '&gt;') text = replace(text, '"', '&quot;') return text def convertToXmlAttribute(value): if (value is None): value = "" return escape(value) class BaseHttpMixin(object): def setHttpHeaders(self, content_type='text/xml'): "Purpose: to prepare the headers for the xml to return" # Prevent the browser from caching the result. # Date in the past self.setHeader('Expires','Mon, 26 Jul 1997 05:00:00 GMT') # always modified self.setHeader('Last-Modified',strftime("%a, %d %b %Y %H:%M:%S GMT", gmtime())) # HTTP/1.1 self.setHeader('Cache-Control','no-store, no-cache, must-revalidate') self.setHeader('Cache-Control','post-check=0, pre-check=0') # HTTP/1.0 self.setHeader('Pragma','no-cache') # Set the response format. self.setHeader( 'Content-Type', content_type + '; charset=utf-8' ) return class BaseXmlMixin(object): def createXmlHeader(self, command, resourceType, currentFolder, url): "Purpose: returns the xml header" self.setHttpHeaders() # Create the XML document header s = """<?xml version="1.0" encoding="utf-8" ?>""" # Create the main connector node s += """<Connector command="%s" resourceType="%s">""" % ( command, resourceType ) # Add the current folder node s += """<CurrentFolder path="%s" url="%s" />""" % ( convertToXmlAttribute(currentFolder), convertToXmlAttribute(url), ) return s def createXmlFooter(self): "Purpose: returns the xml footer" return """</Connector>""" def sendError(self, number, text): "Purpose: in the event of an error, return an xml based error" self.setHttpHeaders() return ("""<?xml version="1.0" encoding="utf-8" ?>""" + """<Connector>""" + self.sendErrorNode (number, text) + """</Connector>""" ) def sendErrorNode(self, number, text): return """<Error number="%s" text="%s" />""" % (number, convertToXmlAttribute(text)) class BaseHtmlMixin(object): def sendUploadResults( self, errorNo = 0, fileUrl = '', fileName = '', customMsg = '' ): self.setHttpHeaders("text/html") "This is the function that sends the results of the uploading process" "Minified version of the document.domain automatic fix script (#1919)." "The original script can be found at _dev/domain_fix_template.js" return """<script type="text/javascript"> (function(){var d=document.domain;while (true){try{var A=window.parent.document.domain;break;}catch(e) {};d=d.replace(/.*?(?:\.|$)/,'');if (d.length==0) break;try{document.domain=d;}catch (e){break;}}})(); window.parent.OnUploadCompleted(%(errorNumber)s,"%(fileUrl)s","%(fileName)s","%(customMsg)s"); </script>""" % { 'errorNumber': errorNo, 'fileUrl': fileUrl.replace ('"', '\\"'), 'fileName': fileName.replace ( '"', '\\"' ) , 'customMsg': customMsg.replace ( '"', '\\"' ), }
Python
#!/usr/bin/env python """ * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2008 Frederico Caldeira Knabben * * == BEGIN LICENSE == * * Licensed under the terms of any of the following licenses at your * choice: * * - GNU General Public License Version 2 or later (the "GPL") * http://www.gnu.org/licenses/gpl.html * * - GNU Lesser General Public License Version 2.1 or later (the "LGPL") * http://www.gnu.org/licenses/lgpl.html * * - Mozilla Public License Version 1.1 or later (the "MPL") * http://www.mozilla.org/MPL/MPL-1.1.html * * == END LICENSE == * * Configuration file for the File Manager Connector for Python """ # INSTALLATION NOTE: You must set up your server environment accordingly to run # python scripts. This connector requires Python 2.4 or greater. # # Supported operation modes: # * WSGI (recommended): You'll need apache + mod_python + modpython_gateway # or any web server capable of the WSGI python standard # * Plain Old CGI: Any server capable of running standard python scripts # (although mod_python is recommended for performance) # This was the previous connector version operation mode # # If you're using Apache web server, replace the htaccess.txt to to .htaccess, # and set the proper options and paths. # For WSGI and mod_python, you may need to download modpython_gateway from: # http://projects.amor.org/misc/svn/modpython_gateway.py and copy it in this # directory. # SECURITY: You must explicitly enable this "connector". (Set it to "True"). # WARNING: don't just set "ConfigIsEnabled = True", you must be sure that only # authenticated users can access this file or use some kind of session checking. Enabled = False # Path to user files relative to the document root. UserFilesPath = '/userfiles/' # Fill the following value it you prefer to specify the absolute path for the # user files directory. Useful if you are using a virtual directory, symbolic # link or alias. Examples: 'C:\\MySite\\userfiles\\' or '/root/mysite/userfiles/'. # Attention: The above 'UserFilesPath' must point to the same directory. # WARNING: GetRootPath may not work in virtual or mod_python configurations, and # may not be thread safe. Use this configuration parameter instead. UserFilesAbsolutePath = '' # Due to security issues with Apache modules, it is recommended to leave the # following setting enabled. ForceSingleExtension = True # What the user can do with this connector ConfigAllowedCommands = [ 'QuickUpload', 'FileUpload', 'GetFolders', 'GetFoldersAndFiles', 'CreateFolder' ] # Allowed Resource Types ConfigAllowedTypes = ['File', 'Image', 'Flash', 'Media'] # After file is uploaded, sometimes it is required to change its permissions # so that it was possible to access it at the later time. # If possible, it is recommended to set more restrictive permissions, like 0755. # Set to 0 to disable this feature. # Note: not needed on Windows-based servers. ChmodOnUpload = 0755 # See comments above. # Used when creating folders that does not exist. ChmodOnFolderCreate = 0755 # Do not touch this 3 lines, see "Configuration settings for each Resource Type" AllowedExtensions = {}; DeniedExtensions = {}; FileTypesPath = {}; FileTypesAbsolutePath = {}; QuickUploadPath = {}; QuickUploadAbsolutePath = {}; # Configuration settings for each Resource Type # # - AllowedExtensions: the possible extensions that can be allowed. # If it is empty then any file type can be uploaded. # - DeniedExtensions: The extensions that won't be allowed. # If it is empty then no restrictions are done here. # # For a file to be uploaded it has to fulfill both the AllowedExtensions # and DeniedExtensions (that's it: not being denied) conditions. # # - FileTypesPath: the virtual folder relative to the document root where # these resources will be located. # Attention: It must start and end with a slash: '/' # # - FileTypesAbsolutePath: the physical path to the above folder. It must be # an absolute path. # If it's an empty string then it will be autocalculated. # Useful if you are using a virtual directory, symbolic link or alias. # Examples: 'C:\\MySite\\userfiles\\' or '/root/mysite/userfiles/'. # Attention: The above 'FileTypesPath' must point to the same directory. # Attention: It must end with a slash: '/' # # # - QuickUploadPath: the virtual folder relative to the document root where # these resources will be uploaded using the Upload tab in the resources # dialogs. # Attention: It must start and end with a slash: '/' # # - QuickUploadAbsolutePath: the physical path to the above folder. It must be # an absolute path. # If it's an empty string then it will be autocalculated. # Useful if you are using a virtual directory, symbolic link or alias. # Examples: 'C:\\MySite\\userfiles\\' or '/root/mysite/userfiles/'. # Attention: The above 'QuickUploadPath' must point to the same directory. # Attention: It must end with a slash: '/' AllowedExtensions['File'] = ['7z','aiff','asf','avi','bmp','csv','doc','fla','flv','gif','gz','gzip','jpeg','jpg','mid','mov','mp3','mp4','mpc','mpeg','mpg','ods','odt','pdf','png','ppt','pxd','qt','ram','rar','rm','rmi','rmvb','rtf','sdc','sitd','swf','sxc','sxw','tar','tgz','tif','tiff','txt','vsd','wav','wma','wmv','xls','xml','zip'] DeniedExtensions['File'] = [] FileTypesPath['File'] = UserFilesPath + 'file/' FileTypesAbsolutePath['File'] = (not UserFilesAbsolutePath == '') and (UserFilesAbsolutePath + 'file/') or '' QuickUploadPath['File'] = FileTypesPath['File'] QuickUploadAbsolutePath['File'] = FileTypesAbsolutePath['File'] AllowedExtensions['Image'] = ['bmp','gif','jpeg','jpg','png'] DeniedExtensions['Image'] = [] FileTypesPath['Image'] = UserFilesPath + 'image/' FileTypesAbsolutePath['Image'] = (not UserFilesAbsolutePath == '') and UserFilesAbsolutePath + 'image/' or '' QuickUploadPath['Image'] = FileTypesPath['Image'] QuickUploadAbsolutePath['Image']= FileTypesAbsolutePath['Image'] AllowedExtensions['Flash'] = ['swf','flv'] DeniedExtensions['Flash'] = [] FileTypesPath['Flash'] = UserFilesPath + 'flash/' FileTypesAbsolutePath['Flash'] = ( not UserFilesAbsolutePath == '') and UserFilesAbsolutePath + 'flash/' or '' QuickUploadPath['Flash'] = FileTypesPath['Flash'] QuickUploadAbsolutePath['Flash']= FileTypesAbsolutePath['Flash'] AllowedExtensions['Media'] = ['aiff','asf','avi','bmp','fla', 'flv','gif','jpeg','jpg','mid','mov','mp3','mp4','mpc','mpeg','mpg','png','qt','ram','rm','rmi','rmvb','swf','tif','tiff','wav','wma','wmv'] DeniedExtensions['Media'] = [] FileTypesPath['Media'] = UserFilesPath + 'media/' FileTypesAbsolutePath['Media'] = ( not UserFilesAbsolutePath == '') and UserFilesAbsolutePath + 'media/' or '' QuickUploadPath['Media'] = FileTypesPath['Media'] QuickUploadAbsolutePath['Media']= FileTypesAbsolutePath['Media']
Python
#!/usr/bin/env python """ FCKeditor - The text editor for Internet - http://www.fckeditor.net Copyright (C) 2003-2008 Frederico Caldeira Knabben == BEGIN LICENSE == Licensed under the terms of any of the following licenses at your choice: - GNU General Public License Version 2 or later (the "GPL") http://www.gnu.org/licenses/gpl.html - GNU Lesser General Public License Version 2.1 or later (the "LGPL") http://www.gnu.org/licenses/lgpl.html - Mozilla Public License Version 1.1 or later (the "MPL") http://www.mozilla.org/MPL/MPL-1.1.html == END LICENSE == Base Connector for Python (CGI and WSGI). See config.py for configuration settings """ import cgi, os from fckutil import * from fckcommands import * # default command's implementation from fckoutput import * # base http, xml and html output mixins import config as Config class FCKeditorConnectorBase( object ): "The base connector class. Subclass it to extend functionality (see Zope example)" def __init__(self, environ=None): "Constructor: Here you should parse request fields, initialize variables, etc." self.request = FCKeditorRequest(environ) # Parse request self.headers = [] # Clean Headers if environ: self.environ = environ else: self.environ = os.environ # local functions def setHeader(self, key, value): self.headers.append ((key, value)) return class FCKeditorRequest(object): "A wrapper around the request object" def __init__(self, environ): if environ: # WSGI self.request = cgi.FieldStorage(fp=environ['wsgi.input'], environ=environ, keep_blank_values=1) self.environ = environ else: # plain old cgi self.environ = os.environ self.request = cgi.FieldStorage() if 'REQUEST_METHOD' in self.environ and 'QUERY_STRING' in self.environ: if self.environ['REQUEST_METHOD'].upper()=='POST': # we are in a POST, but GET query_string exists # cgi parses by default POST data, so parse GET QUERY_STRING too self.get_request = cgi.FieldStorage(fp=None, environ={ 'REQUEST_METHOD':'GET', 'QUERY_STRING':self.environ['QUERY_STRING'], }, ) else: self.get_request={} def has_key(self, key): return self.request.has_key(key) or self.get_request.has_key(key) def get(self, key, default=None): if key in self.request.keys(): field = self.request[key] elif key in self.get_request.keys(): field = self.get_request[key] else: return default if hasattr(field,"filename") and field.filename: #file upload, do not convert return value return field else: return field.value
Python
#!/usr/bin/env python """ FCKeditor - The text editor for Internet - http://www.fckeditor.net Copyright (C) 2003-2008 Frederico Caldeira Knabben == BEGIN LICENSE == Licensed under the terms of any of the following licenses at your choice: - GNU General Public License Version 2 or later (the "GPL") http://www.gnu.org/licenses/gpl.html - GNU Lesser General Public License Version 2.1 or later (the "LGPL") http://www.gnu.org/licenses/lgpl.html - Mozilla Public License Version 1.1 or later (the "MPL") http://www.mozilla.org/MPL/MPL-1.1.html == END LICENSE == Connector for Python (CGI and WSGI). See config.py for configuration settings """ import os from fckutil import * from fckcommands import * # default command's implementation from fckoutput import * # base http, xml and html output mixins from fckconnector import FCKeditorConnectorBase # import base connector import config as Config class FCKeditorConnector( FCKeditorConnectorBase, GetFoldersCommandMixin, GetFoldersAndFilesCommandMixin, CreateFolderCommandMixin, UploadFileCommandMixin, BaseHttpMixin, BaseXmlMixin, BaseHtmlMixin ): "The Standard connector class." def doResponse(self): "Main function. Process the request, set headers and return a string as response." s = "" # Check if this connector is disabled if not(Config.Enabled): return self.sendError(1, "This connector is disabled. Please check the connector configurations in \"editor/filemanager/connectors/py/config.py\" and try again.") # Make sure we have valid inputs for key in ("Command","Type","CurrentFolder"): if not self.request.has_key (key): return # Get command, resource type and current folder command = self.request.get("Command") resourceType = self.request.get("Type") currentFolder = getCurrentFolder(self.request.get("CurrentFolder")) # Check for invalid paths if currentFolder is None: return self.sendError(102, "") # Check if it is an allowed command if ( not command in Config.ConfigAllowedCommands ): return self.sendError( 1, 'The %s command isn\'t allowed' % command ) if ( not resourceType in Config.ConfigAllowedTypes ): return self.sendError( 1, 'Invalid type specified' ) # Setup paths if command == "QuickUpload": self.userFilesFolder = Config.QuickUploadAbsolutePath[resourceType] self.webUserFilesFolder = Config.QuickUploadPath[resourceType] else: self.userFilesFolder = Config.FileTypesAbsolutePath[resourceType] self.webUserFilesFolder = Config.FileTypesPath[resourceType] if not self.userFilesFolder: # no absolute path given (dangerous...) self.userFilesFolder = mapServerPath(self.environ, self.webUserFilesFolder) # Ensure that the directory exists. if not os.path.exists(self.userFilesFolder): try: self.createServerFoldercreateServerFolder( self.userFilesFolder ) except: return self.sendError(1, "This connector couldn\'t access to local user\'s files directories. Please check the UserFilesAbsolutePath in \"editor/filemanager/connectors/py/config.py\" and try again. ") # File upload doesn't have to return XML, so intercept here if (command == "FileUpload"): return self.uploadFile(resourceType, currentFolder) # Create Url url = combinePaths( self.webUserFilesFolder, currentFolder ) # Begin XML s += self.createXmlHeader(command, resourceType, currentFolder, url) # Execute the command selector = {"GetFolders": self.getFolders, "GetFoldersAndFiles": self.getFoldersAndFiles, "CreateFolder": self.createFolder, } s += selector[command](resourceType, currentFolder) s += self.createXmlFooter() return s # Running from command line (plain old CGI) if __name__ == '__main__': try: # Create a Connector Instance conn = FCKeditorConnector() data = conn.doResponse() for header in conn.headers: print '%s: %s' % header print print data except: print "Content-Type: text/plain" print import cgi cgi.print_exception()
Python
#!/usr/bin/env python """ FCKeditor - The text editor for Internet - http://www.fckeditor.net Copyright (C) 2003-2008 Frederico Caldeira Knabben == BEGIN LICENSE == Licensed under the terms of any of the following licenses at your choice: - GNU General Public License Version 2 or later (the "GPL") http://www.gnu.org/licenses/gpl.html - GNU Lesser General Public License Version 2.1 or later (the "LGPL") http://www.gnu.org/licenses/lgpl.html - Mozilla Public License Version 1.1 or later (the "MPL") http://www.mozilla.org/MPL/MPL-1.1.html == END LICENSE == Utilitys functions for the File Manager Connector for Python """ import string, re import os import config as Config # Generic manipulation functions def removeExtension(fileName): index = fileName.rindex(".") newFileName = fileName[0:index] return newFileName def getExtension(fileName): index = fileName.rindex(".") + 1 fileExtension = fileName[index:] return fileExtension def removeFromStart(string, char): return string.lstrip(char) def removeFromEnd(string, char): return string.rstrip(char) # Path functions def combinePaths( basePath, folder ): return removeFromEnd( basePath, '/' ) + '/' + removeFromStart( folder, '/' ) def getFileName(filename): " Purpose: helper function to extrapolate the filename " for splitChar in ["/", "\\"]: array = filename.split(splitChar) if (len(array) > 1): filename = array[-1] return filename def sanitizeFolderName( newFolderName ): "Do a cleanup of the folder name to avoid possible problems" # Remove . \ / | : ? * " < > and control characters return re.sub( '(?u)\\.|\\\\|\\/|\\||\\:|\\?|\\*|"|<|>|[^\u0000-\u001f\u007f-\u009f]', '_', newFolderName ) def sanitizeFileName( newFileName ): "Do a cleanup of the file name to avoid possible problems" # Replace dots in the name with underscores (only one dot can be there... security issue). if ( Config.ForceSingleExtension ): # remove dots newFileName = re.sub ( '/\\.(?![^.]*$)/', '_', newFileName ) ; newFileName = newFileName.replace('\\','/') # convert windows to unix path newFileName = os.path.basename (newFileName) # strip directories # Remove \ / | : ? * return re.sub ( '(?u)/\\\\|\\/|\\||\\:|\\?|\\*|"|<|>|[^\u0000-\u001f\u007f-\u009f]/', '_', newFileName ) def getCurrentFolder(currentFolder): if not currentFolder: currentFolder = '/' # Check the current folder syntax (must begin and end with a slash). if (currentFolder[-1] <> "/"): currentFolder += "/" if (currentFolder[0] <> "/"): currentFolder = "/" + currentFolder # Ensure the folder path has no double-slashes while '//' in currentFolder: currentFolder = currentFolder.replace('//','/') # Check for invalid folder paths (..) if '..' in currentFolder or '\\' in currentFolder: return None return currentFolder def mapServerPath( environ, url): " Emulate the asp Server.mapPath function. Given an url path return the physical directory that it corresponds to " # This isn't correct but for the moment there's no other solution # If this script is under a virtual directory or symlink it will detect the problem and stop return combinePaths( getRootPath(environ), url ) def mapServerFolder(resourceTypePath, folderPath): return combinePaths ( resourceTypePath , folderPath ) def getRootPath(environ): "Purpose: returns the root path on the server" # WARNING: this may not be thread safe, and doesn't work w/ VirtualServer/mod_python # Use Config.UserFilesAbsolutePath instead if environ.has_key('DOCUMENT_ROOT'): return environ['DOCUMENT_ROOT'] else: realPath = os.path.realpath( './' ) selfPath = environ['SCRIPT_FILENAME'] selfPath = selfPath [ : selfPath.rfind( '/' ) ] selfPath = selfPath.replace( '/', os.path.sep) position = realPath.find(selfPath) # This can check only that this script isn't run from a virtual dir # But it avoids the problems that arise if it isn't checked raise realPath if ( position < 0 or position <> len(realPath) - len(selfPath) or realPath[ : position ]==''): raise Exception('Sorry, can\'t map "UserFilesPath" to a physical path. You must set the "UserFilesAbsolutePath" value in "editor/filemanager/connectors/py/config.py".') return realPath[ : position ]
Python
#!/usr/bin/env python """ FCKeditor - The text editor for Internet - http://www.fckeditor.net Copyright (C) 2003-2008 Frederico Caldeira Knabben == BEGIN LICENSE == Licensed under the terms of any of the following licenses at your choice: - GNU General Public License Version 2 or later (the "GPL") http://www.gnu.org/licenses/gpl.html - GNU Lesser General Public License Version 2.1 or later (the "LGPL") http://www.gnu.org/licenses/lgpl.html - Mozilla Public License Version 1.1 or later (the "MPL") http://www.mozilla.org/MPL/MPL-1.1.html == END LICENSE == Connector for Python (CGI and WSGI). """ from time import gmtime, strftime import string def escape(text, replace=string.replace): """ Converts the special characters '<', '>', and '&'. RFC 1866 specifies that these characters be represented in HTML as &lt; &gt; and &amp; respectively. In Python 1.5 we use the new string.replace() function for speed. """ text = replace(text, '&', '&amp;') # must be done 1st text = replace(text, '<', '&lt;') text = replace(text, '>', '&gt;') text = replace(text, '"', '&quot;') return text def convertToXmlAttribute(value): if (value is None): value = "" return escape(value) class BaseHttpMixin(object): def setHttpHeaders(self, content_type='text/xml'): "Purpose: to prepare the headers for the xml to return" # Prevent the browser from caching the result. # Date in the past self.setHeader('Expires','Mon, 26 Jul 1997 05:00:00 GMT') # always modified self.setHeader('Last-Modified',strftime("%a, %d %b %Y %H:%M:%S GMT", gmtime())) # HTTP/1.1 self.setHeader('Cache-Control','no-store, no-cache, must-revalidate') self.setHeader('Cache-Control','post-check=0, pre-check=0') # HTTP/1.0 self.setHeader('Pragma','no-cache') # Set the response format. self.setHeader( 'Content-Type', content_type + '; charset=utf-8' ) return class BaseXmlMixin(object): def createXmlHeader(self, command, resourceType, currentFolder, url): "Purpose: returns the xml header" self.setHttpHeaders() # Create the XML document header s = """<?xml version="1.0" encoding="utf-8" ?>""" # Create the main connector node s += """<Connector command="%s" resourceType="%s">""" % ( command, resourceType ) # Add the current folder node s += """<CurrentFolder path="%s" url="%s" />""" % ( convertToXmlAttribute(currentFolder), convertToXmlAttribute(url), ) return s def createXmlFooter(self): "Purpose: returns the xml footer" return """</Connector>""" def sendError(self, number, text): "Purpose: in the event of an error, return an xml based error" self.setHttpHeaders() return ("""<?xml version="1.0" encoding="utf-8" ?>""" + """<Connector>""" + self.sendErrorNode (number, text) + """</Connector>""" ) def sendErrorNode(self, number, text): return """<Error number="%s" text="%s" />""" % (number, convertToXmlAttribute(text)) class BaseHtmlMixin(object): def sendUploadResults( self, errorNo = 0, fileUrl = '', fileName = '', customMsg = '' ): self.setHttpHeaders("text/html") "This is the function that sends the results of the uploading process" "Minified version of the document.domain automatic fix script (#1919)." "The original script can be found at _dev/domain_fix_template.js" return """<script type="text/javascript"> (function(){var d=document.domain;while (true){try{var A=window.parent.document.domain;break;}catch(e) {};d=d.replace(/.*?(?:\.|$)/,'');if (d.length==0) break;try{document.domain=d;}catch (e){break;}}})(); window.parent.OnUploadCompleted(%(errorNumber)s,"%(fileUrl)s","%(fileName)s","%(customMsg)s"); </script>""" % { 'errorNumber': errorNo, 'fileUrl': fileUrl.replace ('"', '\\"'), 'fileName': fileName.replace ( '"', '\\"' ) , 'customMsg': customMsg.replace ( '"', '\\"' ), }
Python
#!/usr/bin/env python """ FCKeditor - The text editor for Internet - http://www.fckeditor.net Copyright (C) 2003-2008 Frederico Caldeira Knabben == BEGIN LICENSE == Licensed under the terms of any of the following licenses at your choice: - GNU General Public License Version 2 or later (the "GPL") http://www.gnu.org/licenses/gpl.html - GNU Lesser General Public License Version 2.1 or later (the "LGPL") http://www.gnu.org/licenses/lgpl.html - Mozilla Public License Version 1.1 or later (the "MPL") http://www.mozilla.org/MPL/MPL-1.1.html == END LICENSE == Connector/QuickUpload for Python (WSGI wrapper). See config.py for configuration settings """ from connector import FCKeditorConnector from upload import FCKeditorQuickUpload import cgitb from cStringIO import StringIO # Running from WSGI capable server (recomended) def App(environ, start_response): "WSGI entry point. Run the connector" if environ['SCRIPT_NAME'].endswith("connector.py"): conn = FCKeditorConnector(environ) elif environ['SCRIPT_NAME'].endswith("upload.py"): conn = FCKeditorQuickUpload(environ) else: start_response ("200 Ok", [('Content-Type','text/html')]) yield "Unknown page requested: " yield environ['SCRIPT_NAME'] return try: # run the connector data = conn.doResponse() # Start WSGI response: start_response ("200 Ok", conn.headers) # Send response text yield data except: start_response("500 Internal Server Error",[("Content-type","text/html")]) file = StringIO() cgitb.Hook(file = file).handle() yield file.getvalue()
Python
#!/usr/bin/env python """ FCKeditor - The text editor for Internet - http://www.fckeditor.net Copyright (C) 2003-2008 Frederico Caldeira Knabben == BEGIN LICENSE == Licensed under the terms of any of the following licenses at your choice: - GNU General Public License Version 2 or later (the "GPL") http://www.gnu.org/licenses/gpl.html - GNU Lesser General Public License Version 2.1 or later (the "LGPL") http://www.gnu.org/licenses/lgpl.html - Mozilla Public License Version 1.1 or later (the "MPL") http://www.mozilla.org/MPL/MPL-1.1.html == END LICENSE == This is the "File Uploader" for Python """ import os from fckutil import * from fckcommands import * # default command's implementation from fckconnector import FCKeditorConnectorBase # import base connector import config as Config class FCKeditorQuickUpload( FCKeditorConnectorBase, UploadFileCommandMixin, BaseHttpMixin, BaseHtmlMixin): def doResponse(self): "Main function. Process the request, set headers and return a string as response." # Check if this connector is disabled if not(Config.Enabled): return self.sendUploadResults(1, "This file uploader is disabled. Please check the \"editor/filemanager/connectors/py/config.py\"") command = 'QuickUpload' # The file type (from the QueryString, by default 'File'). resourceType = self.request.get('Type','File') currentFolder = getCurrentFolder(self.request.get("CurrentFolder","")) # Check for invalid paths if currentFolder is None: return self.sendUploadResults(102, '', '', "") # Check if it is an allowed command if ( not command in Config.ConfigAllowedCommands ): return self.sendUploadResults( 1, '', '', 'The %s command isn\'t allowed' % command ) if ( not resourceType in Config.ConfigAllowedTypes ): return self.sendUploadResults( 1, '', '', 'Invalid type specified' ) # Setup paths self.userFilesFolder = Config.QuickUploadAbsolutePath[resourceType] self.webUserFilesFolder = Config.QuickUploadPath[resourceType] if not self.userFilesFolder: # no absolute path given (dangerous...) self.userFilesFolder = mapServerPath(self.environ, self.webUserFilesFolder) # Ensure that the directory exists. if not os.path.exists(self.userFilesFolder): try: self.createServerFoldercreateServerFolder( self.userFilesFolder ) except: return self.sendError(1, "This connector couldn\'t access to local user\'s files directories. Please check the UserFilesAbsolutePath in \"editor/filemanager/connectors/py/config.py\" and try again. ") # File upload doesn't have to return XML, so intercept here return self.uploadFile(resourceType, currentFolder) # Running from command line (plain old CGI) if __name__ == '__main__': try: # Create a Connector Instance conn = FCKeditorQuickUpload() data = conn.doResponse() for header in conn.headers: if not header is None: print '%s: %s' % header print print data except: print "Content-Type: text/plain" print import cgi cgi.print_exception()
Python
#!/usr/bin/env python """ FCKeditor - The text editor for Internet - http://www.fckeditor.net Copyright (C) 2003-2008 Frederico Caldeira Knabben == BEGIN LICENSE == Licensed under the terms of any of the following licenses at your choice: - GNU General Public License Version 2 or later (the "GPL") http://www.gnu.org/licenses/gpl.html - GNU Lesser General Public License Version 2.1 or later (the "LGPL") http://www.gnu.org/licenses/lgpl.html - Mozilla Public License Version 1.1 or later (the "MPL") http://www.mozilla.org/MPL/MPL-1.1.html == END LICENSE == Connector for Python and Zope. This code was not tested at all. It just was ported from pre 2.5 release, so for further reference see \editor\filemanager\browser\default\connectors\py\connector.py in previous releases. """ from fckutil import * from connector import * import config as Config class FCKeditorConnectorZope(FCKeditorConnector): """ Zope versiof FCKeditorConnector """ # Allow access (Zope) __allow_access_to_unprotected_subobjects__ = 1 def __init__(self, context=None): """ Constructor """ FCKeditorConnector.__init__(self, environ=None) # call superclass constructor # Instance Attributes self.context = context self.request = FCKeditorRequest(context) def getZopeRootContext(self): if self.zopeRootContext is None: self.zopeRootContext = self.context.getPhysicalRoot() return self.zopeRootContext def getZopeUploadContext(self): if self.zopeUploadContext is None: folderNames = self.userFilesFolder.split("/") c = self.getZopeRootContext() for folderName in folderNames: if (folderName <> ""): c = c[folderName] self.zopeUploadContext = c return self.zopeUploadContext def setHeader(self, key, value): self.context.REQUEST.RESPONSE.setHeader(key, value) def getFolders(self, resourceType, currentFolder): # Open the folders node s = "" s += """<Folders>""" zopeFolder = self.findZopeFolder(resourceType, currentFolder) for (name, o) in zopeFolder.objectItems(["Folder"]): s += """<Folder name="%s" />""" % ( convertToXmlAttribute(name) ) # Close the folders node s += """</Folders>""" return s def getZopeFoldersAndFiles(self, resourceType, currentFolder): folders = self.getZopeFolders(resourceType, currentFolder) files = self.getZopeFiles(resourceType, currentFolder) s = folders + files return s def getZopeFiles(self, resourceType, currentFolder): # Open the files node s = "" s += """<Files>""" zopeFolder = self.findZopeFolder(resourceType, currentFolder) for (name, o) in zopeFolder.objectItems(["File","Image"]): s += """<File name="%s" size="%s" />""" % ( convertToXmlAttribute(name), ((o.get_size() / 1024) + 1) ) # Close the files node s += """</Files>""" return s def findZopeFolder(self, resourceType, folderName): # returns the context of the resource / folder zopeFolder = self.getZopeUploadContext() folderName = self.removeFromStart(folderName, "/") folderName = self.removeFromEnd(folderName, "/") if (resourceType <> ""): try: zopeFolder = zopeFolder[resourceType] except: zopeFolder.manage_addProduct["OFSP"].manage_addFolder(id=resourceType, title=resourceType) zopeFolder = zopeFolder[resourceType] if (folderName <> ""): folderNames = folderName.split("/") for folderName in folderNames: zopeFolder = zopeFolder[folderName] return zopeFolder def createFolder(self, resourceType, currentFolder): # Find out where we are zopeFolder = self.findZopeFolder(resourceType, currentFolder) errorNo = 0 errorMsg = "" if self.request.has_key("NewFolderName"): newFolder = self.request.get("NewFolderName", None) zopeFolder.manage_addProduct["OFSP"].manage_addFolder(id=newFolder, title=newFolder) else: errorNo = 102 return self.sendErrorNode ( errorNo, errorMsg ) def uploadFile(self, resourceType, currentFolder, count=None): zopeFolder = self.findZopeFolder(resourceType, currentFolder) file = self.request.get("NewFile", None) fileName = self.getFileName(file.filename) fileNameOnly = self.removeExtension(fileName) fileExtension = self.getExtension(fileName).lower() if (count): nid = "%s.%s.%s" % (fileNameOnly, count, fileExtension) else: nid = fileName title = nid try: zopeFolder.manage_addProduct['OFSP'].manage_addFile( id=nid, title=title, file=file.read() ) except: if (count): count += 1 else: count = 1 return self.zopeFileUpload(resourceType, currentFolder, count) return self.sendUploadResults( 0 ) class FCKeditorRequest(object): "A wrapper around the request object" def __init__(self, context=None): r = context.REQUEST self.request = r def has_key(self, key): return self.request.has_key(key) def get(self, key, default=None): return self.request.get(key, default) """ Running from zope, you will need to modify this connector. If you have uploaded the FCKeditor into Zope (like me), you need to move this connector out of Zope, and replace the "connector" with an alias as below. The key to it is to pass the Zope context in, as we then have a like to the Zope context. ## Script (Python) "connector.py" ##bind container=container ##bind context=context ##bind namespace= ##bind script=script ##bind subpath=traverse_subpath ##parameters=*args, **kws ##title=ALIAS ## import Products.zope as connector return connector.FCKeditorConnectorZope(context=context).doResponse() """
Python
#!/usr/bin/env python """ FCKeditor - The text editor for internet Copyright (C) 2003-2006 Frederico Caldeira Knabben Licensed under the terms of the GNU Lesser General Public License: http://www.opensource.org/licenses/lgpl-license.php For further information visit: http://www.fckeditor.net/ "Support Open Source software. What about a donation today?" File Name: connector.py Connector for Python. Tested With: Standard: Python 2.3.3 Zope: Zope Version: (Zope 2.8.1-final, python 2.3.5, linux2) Python Version: 2.3.5 (#4, Mar 10 2005, 01:40:25) [GCC 3.3.3 20040412 (Red Hat Linux 3.3.3-7)] System Platform: linux2 File Authors: Andrew Liu (andrew@liuholdings.com) """ """ Author Notes (04 December 2005): This module has gone through quite a few phases of change. Obviously, I am only supporting that part of the code that I use. Initially I had the upload directory as a part of zope (ie. uploading files directly into Zope), before realising that there were too many complex intricacies within Zope to deal with. Zope is one ugly piece of code. So I decided to complement Zope by an Apache server (which I had running anyway, and doing nothing). So I mapped all uploads from an arbitrary server directory to an arbitrary web directory. All the FCKeditor uploading occurred this way, and I didn't have to stuff around with fiddling with Zope objects and the like (which are terribly complex and something you don't want to do - trust me). Maybe a Zope expert can touch up the Zope components. In the end, I had FCKeditor loaded in Zope (probably a bad idea as well), and I replaced the connector.py with an alias to a server module. Right now, all Zope components will simple remain as is because I've had enough of Zope. See notes right at the end of this file for how I aliased out of Zope. Anyway, most of you probably wont use Zope, so things are pretty simple in that regard. Typically, SERVER_DIR is the root of WEB_DIR (not necessarily). Most definitely, SERVER_USERFILES_DIR points to WEB_USERFILES_DIR. """ import cgi import re import os import string """ escape Converts the special characters '<', '>', and '&'. RFC 1866 specifies that these characters be represented in HTML as &lt; &gt; and &amp; respectively. In Python 1.5 we use the new string.replace() function for speed. """ def escape(text, replace=string.replace): text = replace(text, '&', '&amp;') # must be done 1st text = replace(text, '<', '&lt;') text = replace(text, '>', '&gt;') text = replace(text, '"', '&quot;') return text """ getFCKeditorConnector Creates a new instance of an FCKeditorConnector, and runs it """ def getFCKeditorConnector(context=None): # Called from Zope. Passes the context through connector = FCKeditorConnector(context=context) return connector.run() """ FCKeditorRequest A wrapper around the request object Can handle normal CGI request, or a Zope request Extend as required """ class FCKeditorRequest(object): def __init__(self, context=None): if (context is not None): r = context.REQUEST else: r = cgi.FieldStorage() self.context = context self.request = r def isZope(self): if (self.context is not None): return True return False def has_key(self, key): return self.request.has_key(key) def get(self, key, default=None): value = None if (self.isZope()): value = self.request.get(key, default) else: if key in self.request.keys(): value = self.request[key].value else: value = default return value """ FCKeditorConnector The connector class """ class FCKeditorConnector(object): # Configuration for FCKEditor # can point to another server here, if linked correctly #WEB_HOST = "http://127.0.0.1/" WEB_HOST = "" SERVER_DIR = "/var/www/html/" WEB_USERFILES_FOLDER = WEB_HOST + "upload/" SERVER_USERFILES_FOLDER = SERVER_DIR + "upload/" # Allow access (Zope) __allow_access_to_unprotected_subobjects__ = 1 # Class Attributes parentFolderRe = re.compile("[\/][^\/]+[\/]?$") """ Constructor """ def __init__(self, context=None): # The given root path will NOT be shown to the user # Only the userFilesPath will be shown # Instance Attributes self.context = context self.request = FCKeditorRequest(context=context) self.rootPath = self.SERVER_DIR self.userFilesFolder = self.SERVER_USERFILES_FOLDER self.webUserFilesFolder = self.WEB_USERFILES_FOLDER # Enables / Disables the connector self.enabled = False # Set to True to enable this connector # These are instance variables self.zopeRootContext = None self.zopeUploadContext = None # Copied from php module =) self.allowedExtensions = { "File": None, "Image": None, "Flash": None, "Media": None } self.deniedExtensions = { "File": [ "php","php2","php3","php4","php5","phtml","pwml","inc","asp","aspx","ascx","jsp","cfm","cfc","pl","bat","exe","com","dll","vbs","js","reg","cgi","htaccess" ], "Image": [ "php","php2","php3","php4","php5","phtml","pwml","inc","asp","aspx","ascx","jsp","cfm","cfc","pl","bat","exe","com","dll","vbs","js","reg","cgi","htaccess" ], "Flash": [ "php","php2","php3","php4","php5","phtml","pwml","inc","asp","aspx","ascx","jsp","cfm","cfc","pl","bat","exe","com","dll","vbs","js","reg","cgi","htaccess" ], "Media": [ "php","php2","php3","php4","php5","phtml","pwml","inc","asp","aspx","ascx","jsp","cfm","cfc","pl","bat","exe","com","dll","vbs","js","reg","cgi","htaccess" ] } """ Zope specific functions """ def isZope(self): # The context object is the zope object if (self.context is not None): return True return False def getZopeRootContext(self): if self.zopeRootContext is None: self.zopeRootContext = self.context.getPhysicalRoot() return self.zopeRootContext def getZopeUploadContext(self): if self.zopeUploadContext is None: folderNames = self.userFilesFolder.split("/") c = self.getZopeRootContext() for folderName in folderNames: if (folderName <> ""): c = c[folderName] self.zopeUploadContext = c return self.zopeUploadContext """ Generic manipulation functions """ def getUserFilesFolder(self): return self.userFilesFolder def getWebUserFilesFolder(self): return self.webUserFilesFolder def getAllowedExtensions(self, resourceType): return self.allowedExtensions[resourceType] def getDeniedExtensions(self, resourceType): return self.deniedExtensions[resourceType] def removeFromStart(self, string, char): return string.lstrip(char) def removeFromEnd(self, string, char): return string.rstrip(char) def convertToXmlAttribute(self, value): if (value is None): value = "" return escape(value) def convertToPath(self, path): if (path[-1] <> "/"): return path + "/" else: return path def getUrlFromPath(self, resourceType, path): if (resourceType is None) or (resourceType == ''): url = "%s%s" % ( self.removeFromEnd(self.getUserFilesFolder(), '/'), path ) else: url = "%s%s%s" % ( self.getUserFilesFolder(), resourceType, path ) return url def getWebUrlFromPath(self, resourceType, path): if (resourceType is None) or (resourceType == ''): url = "%s%s" % ( self.removeFromEnd(self.getWebUserFilesFolder(), '/'), path ) else: url = "%s%s%s" % ( self.getWebUserFilesFolder(), resourceType, path ) return url def removeExtension(self, fileName): index = fileName.rindex(".") newFileName = fileName[0:index] return newFileName def getExtension(self, fileName): index = fileName.rindex(".") + 1 fileExtension = fileName[index:] return fileExtension def getParentFolder(self, folderPath): parentFolderPath = self.parentFolderRe.sub('', folderPath) return parentFolderPath """ serverMapFolder Purpose: works out the folder map on the server """ def serverMapFolder(self, resourceType, folderPath): # Get the resource type directory resourceTypeFolder = "%s%s/" % ( self.getUserFilesFolder(), resourceType ) # Ensure that the directory exists self.createServerFolder(resourceTypeFolder) # Return the resource type directory combined with the # required path return "%s%s" % ( resourceTypeFolder, self.removeFromStart(folderPath, '/') ) """ createServerFolder Purpose: physically creates a folder on the server """ def createServerFolder(self, folderPath): # Check if the parent exists parentFolderPath = self.getParentFolder(folderPath) if not(os.path.exists(parentFolderPath)): errorMsg = self.createServerFolder(parentFolderPath) if errorMsg is not None: return errorMsg # Check if this exists if not(os.path.exists(folderPath)): os.mkdir(folderPath) os.chmod(folderPath, 0755) errorMsg = None else: if os.path.isdir(folderPath): errorMsg = None else: raise "createServerFolder: Non-folder of same name already exists" return errorMsg """ getRootPath Purpose: returns the root path on the server """ def getRootPath(self): return self.rootPath """ setXmlHeaders Purpose: to prepare the headers for the xml to return """ def setXmlHeaders(self): #now = self.context.BS_get_now() #yesterday = now - 1 self.setHeader("Content-Type", "text/xml") #self.setHeader("Expires", yesterday) #self.setHeader("Last-Modified", now) #self.setHeader("Cache-Control", "no-store, no-cache, must-revalidate") self.printHeaders() return def setHeader(self, key, value): if (self.isZope()): self.context.REQUEST.RESPONSE.setHeader(key, value) else: print "%s: %s" % (key, value) return def printHeaders(self): # For non-Zope requests, we need to print an empty line # to denote the end of headers if (not(self.isZope())): print "" """ createXmlFooter Purpose: returns the xml header """ def createXmlHeader(self, command, resourceType, currentFolder): self.setXmlHeaders() s = "" # Create the XML document header s += """<?xml version="1.0" encoding="utf-8" ?>""" # Create the main connector node s += """<Connector command="%s" resourceType="%s">""" % ( command, resourceType ) # Add the current folder node s += """<CurrentFolder path="%s" url="%s" />""" % ( self.convertToXmlAttribute(currentFolder), self.convertToXmlAttribute( self.getWebUrlFromPath( resourceType, currentFolder ) ), ) return s """ createXmlFooter Purpose: returns the xml footer """ def createXmlFooter(self): s = """</Connector>""" return s """ sendError Purpose: in the event of an error, return an xml based error """ def sendError(self, number, text): self.setXmlHeaders() s = "" # Create the XML document header s += """<?xml version="1.0" encoding="utf-8" ?>""" s += """<Connector>""" s += """<Error number="%s" text="%s" />""" % (number, text) s += """</Connector>""" return s """ getFolders Purpose: command to recieve a list of folders """ def getFolders(self, resourceType, currentFolder): if (self.isZope()): return self.getZopeFolders(resourceType, currentFolder) else: return self.getNonZopeFolders(resourceType, currentFolder) def getZopeFolders(self, resourceType, currentFolder): # Open the folders node s = "" s += """<Folders>""" zopeFolder = self.findZopeFolder(resourceType, currentFolder) for (name, o) in zopeFolder.objectItems(["Folder"]): s += """<Folder name="%s" />""" % ( self.convertToXmlAttribute(name) ) # Close the folders node s += """</Folders>""" return s def getNonZopeFolders(self, resourceType, currentFolder): # Map the virtual path to our local server serverPath = self.serverMapFolder(resourceType, currentFolder) # Open the folders node s = "" s += """<Folders>""" for someObject in os.listdir(serverPath): someObjectPath = os.path.join(serverPath, someObject) if os.path.isdir(someObjectPath): s += """<Folder name="%s" />""" % ( self.convertToXmlAttribute(someObject) ) # Close the folders node s += """</Folders>""" return s """ getFoldersAndFiles Purpose: command to recieve a list of folders and files """ def getFoldersAndFiles(self, resourceType, currentFolder): if (self.isZope()): return self.getZopeFoldersAndFiles(resourceType, currentFolder) else: return self.getNonZopeFoldersAndFiles(resourceType, currentFolder) def getNonZopeFoldersAndFiles(self, resourceType, currentFolder): # Map the virtual path to our local server serverPath = self.serverMapFolder(resourceType, currentFolder) # Open the folders / files node folders = """<Folders>""" files = """<Files>""" for someObject in os.listdir(serverPath): someObjectPath = os.path.join(serverPath, someObject) if os.path.isdir(someObjectPath): folders += """<Folder name="%s" />""" % ( self.convertToXmlAttribute(someObject) ) elif os.path.isfile(someObjectPath): size = os.path.getsize(someObjectPath) files += """<File name="%s" size="%s" />""" % ( self.convertToXmlAttribute(someObject), os.path.getsize(someObjectPath) ) # Close the folders / files node folders += """</Folders>""" files += """</Files>""" # Return it s = folders + files return s def getZopeFoldersAndFiles(self, resourceType, currentFolder): folders = self.getZopeFolders(resourceType, currentFolder) files = self.getZopeFiles(resourceType, currentFolder) s = folders + files return s def getZopeFiles(self, resourceType, currentFolder): # Open the files node s = "" s += """<Files>""" zopeFolder = self.findZopeFolder(resourceType, currentFolder) for (name, o) in zopeFolder.objectItems(["File","Image"]): s += """<File name="%s" size="%s" />""" % ( self.convertToXmlAttribute(name), ((o.get_size() / 1024) + 1) ) # Close the files node s += """</Files>""" return s def findZopeFolder(self, resourceType, folderName): # returns the context of the resource / folder zopeFolder = self.getZopeUploadContext() folderName = self.removeFromStart(folderName, "/") folderName = self.removeFromEnd(folderName, "/") if (resourceType <> ""): try: zopeFolder = zopeFolder[resourceType] except: zopeFolder.manage_addProduct["OFSP"].manage_addFolder(id=resourceType, title=resourceType) zopeFolder = zopeFolder[resourceType] if (folderName <> ""): folderNames = folderName.split("/") for folderName in folderNames: zopeFolder = zopeFolder[folderName] return zopeFolder """ createFolder Purpose: command to create a new folder """ def createFolder(self, resourceType, currentFolder): if (self.isZope()): return self.createZopeFolder(resourceType, currentFolder) else: return self.createNonZopeFolder(resourceType, currentFolder) def createZopeFolder(self, resourceType, currentFolder): # Find out where we are zopeFolder = self.findZopeFolder(resourceType, currentFolder) errorNo = 0 errorMsg = "" if self.request.has_key("NewFolderName"): newFolder = self.request.get("NewFolderName", None) zopeFolder.manage_addProduct["OFSP"].manage_addFolder(id=newFolder, title=newFolder) else: errorNo = 102 error = """<Error number="%s" originalDescription="%s" />""" % ( errorNo, self.convertToXmlAttribute(errorMsg) ) return error def createNonZopeFolder(self, resourceType, currentFolder): errorNo = 0 errorMsg = "" if self.request.has_key("NewFolderName"): newFolder = self.request.get("NewFolderName", None) currentFolderPath = self.serverMapFolder( resourceType, currentFolder ) try: newFolderPath = currentFolderPath + newFolder errorMsg = self.createServerFolder(newFolderPath) if (errorMsg is not None): errorNo = 110 except: errorNo = 103 else: errorNo = 102 error = """<Error number="%s" originalDescription="%s" />""" % ( errorNo, self.convertToXmlAttribute(errorMsg) ) return error """ getFileName Purpose: helper function to extrapolate the filename """ def getFileName(self, filename): for splitChar in ["/", "\\"]: array = filename.split(splitChar) if (len(array) > 1): filename = array[-1] return filename """ fileUpload Purpose: command to upload files to server """ def fileUpload(self, resourceType, currentFolder): if (self.isZope()): return self.zopeFileUpload(resourceType, currentFolder) else: return self.nonZopeFileUpload(resourceType, currentFolder) def zopeFileUpload(self, resourceType, currentFolder, count=None): zopeFolder = self.findZopeFolder(resourceType, currentFolder) file = self.request.get("NewFile", None) fileName = self.getFileName(file.filename) fileNameOnly = self.removeExtension(fileName) fileExtension = self.getExtension(fileName).lower() if (count): nid = "%s.%s.%s" % (fileNameOnly, count, fileExtension) else: nid = fileName title = nid try: zopeFolder.manage_addProduct['OFSP'].manage_addFile( id=nid, title=title, file=file.read() ) except: if (count): count += 1 else: count = 1 self.zopeFileUpload(resourceType, currentFolder, count) return def nonZopeFileUpload(self, resourceType, currentFolder): errorNo = 0 errorMsg = "" if self.request.has_key("NewFile"): # newFile has all the contents we need newFile = self.request.get("NewFile", "") # Get the file name newFileName = newFile.filename newFileNameOnly = self.removeExtension(newFileName) newFileExtension = self.getExtension(newFileName).lower() allowedExtensions = self.getAllowedExtensions(resourceType) deniedExtensions = self.getDeniedExtensions(resourceType) if (allowedExtensions is not None): # Check for allowed isAllowed = False if (newFileExtension in allowedExtensions): isAllowed = True elif (deniedExtensions is not None): # Check for denied isAllowed = True if (newFileExtension in deniedExtensions): isAllowed = False else: # No extension limitations isAllowed = True if (isAllowed): if (self.isZope()): # Upload into zope self.zopeFileUpload(resourceType, currentFolder) else: # Upload to operating system # Map the virtual path to the local server path currentFolderPath = self.serverMapFolder( resourceType, currentFolder ) i = 0 while (True): newFilePath = "%s%s" % ( currentFolderPath, newFileName ) if os.path.exists(newFilePath): i += 1 newFilePath = "%s%s(%s).%s" % ( currentFolderPath, newFileNameOnly, i, newFileExtension ) errorNo = 201 break else: fileHandle = open(newFilePath,'w') linecount = 0 while (1): #line = newFile.file.readline() line = newFile.readline() if not line: break fileHandle.write("%s" % line) linecount += 1 os.chmod(newFilePath, 0777) break else: newFileName = "Extension not allowed" errorNo = 203 else: newFileName = "No File" errorNo = 202 string = """ <script type="text/javascript"> window.parent.frames["frmUpload"].OnUploadCompleted(%s,"%s"); </script> """ % ( errorNo, newFileName.replace('"',"'") ) return string def run(self): s = "" try: # Check if this is disabled if not(self.enabled): return self.sendError(1, "This connector is disabled. Please check the connector configurations and try again") # Make sure we have valid inputs if not( (self.request.has_key("Command")) and (self.request.has_key("Type")) and (self.request.has_key("CurrentFolder")) ): return # Get command command = self.request.get("Command", None) # Get resource type resourceType = self.request.get("Type", None) # folder syntax must start and end with "/" currentFolder = self.request.get("CurrentFolder", None) if (currentFolder[-1] <> "/"): currentFolder += "/" if (currentFolder[0] <> "/"): currentFolder = "/" + currentFolder # Check for invalid paths if (".." in currentFolder): return self.sendError(102, "") # File upload doesn't have to return XML, so intercept # her:e if (command == "FileUpload"): return self.fileUpload(resourceType, currentFolder) # Begin XML s += self.createXmlHeader(command, resourceType, currentFolder) # Execute the command if (command == "GetFolders"): f = self.getFolders elif (command == "GetFoldersAndFiles"): f = self.getFoldersAndFiles elif (command == "CreateFolder"): f = self.createFolder else: f = None if (f is not None): s += f(resourceType, currentFolder) s += self.createXmlFooter() except Exception, e: s = "ERROR: %s" % e return s # Running from command line if __name__ == '__main__': # To test the output, uncomment the standard headers #print "Content-Type: text/html" #print "" print getFCKeditorConnector() """ Running from zope, you will need to modify this connector. If you have uploaded the FCKeditor into Zope (like me), you need to move this connector out of Zope, and replace the "connector" with an alias as below. The key to it is to pass the Zope context in, as we then have a like to the Zope context. ## Script (Python) "connector.py" ##bind container=container ##bind context=context ##bind namespace= ##bind script=script ##bind subpath=traverse_subpath ##parameters=*args, **kws ##title=ALIAS ## import Products.connector as connector return connector.getFCKeditorConnector(context=context).run() """
Python
#!/usr/bin/env python """ FCKeditor - The text editor for internet Copyright (C) 2003-2006 Frederico Caldeira Knabben Licensed under the terms of the GNU Lesser General Public License: http://www.opensource.org/licenses/lgpl-license.php For further information visit: http://www.fckeditor.net/ "Support Open Source software. What about a donation today?" File Name: connector.py Connector for Python. Tested With: Standard: Python 2.3.3 Zope: Zope Version: (Zope 2.8.1-final, python 2.3.5, linux2) Python Version: 2.3.5 (#4, Mar 10 2005, 01:40:25) [GCC 3.3.3 20040412 (Red Hat Linux 3.3.3-7)] System Platform: linux2 File Authors: Andrew Liu (andrew@liuholdings.com) """ """ Author Notes (04 December 2005): This module has gone through quite a few phases of change. Obviously, I am only supporting that part of the code that I use. Initially I had the upload directory as a part of zope (ie. uploading files directly into Zope), before realising that there were too many complex intricacies within Zope to deal with. Zope is one ugly piece of code. So I decided to complement Zope by an Apache server (which I had running anyway, and doing nothing). So I mapped all uploads from an arbitrary server directory to an arbitrary web directory. All the FCKeditor uploading occurred this way, and I didn't have to stuff around with fiddling with Zope objects and the like (which are terribly complex and something you don't want to do - trust me). Maybe a Zope expert can touch up the Zope components. In the end, I had FCKeditor loaded in Zope (probably a bad idea as well), and I replaced the connector.py with an alias to a server module. Right now, all Zope components will simple remain as is because I've had enough of Zope. See notes right at the end of this file for how I aliased out of Zope. Anyway, most of you probably wont use Zope, so things are pretty simple in that regard. Typically, SERVER_DIR is the root of WEB_DIR (not necessarily). Most definitely, SERVER_USERFILES_DIR points to WEB_USERFILES_DIR. """ import cgi import re import os import string """ escape Converts the special characters '<', '>', and '&'. RFC 1866 specifies that these characters be represented in HTML as &lt; &gt; and &amp; respectively. In Python 1.5 we use the new string.replace() function for speed. """ def escape(text, replace=string.replace): text = replace(text, '&', '&amp;') # must be done 1st text = replace(text, '<', '&lt;') text = replace(text, '>', '&gt;') text = replace(text, '"', '&quot;') return text """ getFCKeditorConnector Creates a new instance of an FCKeditorConnector, and runs it """ def getFCKeditorConnector(context=None): # Called from Zope. Passes the context through connector = FCKeditorConnector(context=context) return connector.run() """ FCKeditorRequest A wrapper around the request object Can handle normal CGI request, or a Zope request Extend as required """ class FCKeditorRequest(object): def __init__(self, context=None): if (context is not None): r = context.REQUEST else: r = cgi.FieldStorage() self.context = context self.request = r def isZope(self): if (self.context is not None): return True return False def has_key(self, key): return self.request.has_key(key) def get(self, key, default=None): value = None if (self.isZope()): value = self.request.get(key, default) else: if key in self.request.keys(): value = self.request[key].value else: value = default return value """ FCKeditorConnector The connector class """ class FCKeditorConnector(object): # Configuration for FCKEditor # can point to another server here, if linked correctly #WEB_HOST = "http://127.0.0.1/" WEB_HOST = "" SERVER_DIR = "/var/www/html/" WEB_USERFILES_FOLDER = WEB_HOST + "upload/" SERVER_USERFILES_FOLDER = SERVER_DIR + "upload/" # Allow access (Zope) __allow_access_to_unprotected_subobjects__ = 1 # Class Attributes parentFolderRe = re.compile("[\/][^\/]+[\/]?$") """ Constructor """ def __init__(self, context=None): # The given root path will NOT be shown to the user # Only the userFilesPath will be shown # Instance Attributes self.context = context self.request = FCKeditorRequest(context=context) self.rootPath = self.SERVER_DIR self.userFilesFolder = self.SERVER_USERFILES_FOLDER self.webUserFilesFolder = self.WEB_USERFILES_FOLDER # Enables / Disables the connector self.enabled = False # Set to True to enable this connector # These are instance variables self.zopeRootContext = None self.zopeUploadContext = None # Copied from php module =) self.allowedExtensions = { "File": None, "Image": None, "Flash": None, "Media": None } self.deniedExtensions = { "File": [ "php","php2","php3","php4","php5","phtml","pwml","inc","asp","aspx","ascx","jsp","cfm","cfc","pl","bat","exe","com","dll","vbs","js","reg","cgi","htaccess" ], "Image": [ "php","php2","php3","php4","php5","phtml","pwml","inc","asp","aspx","ascx","jsp","cfm","cfc","pl","bat","exe","com","dll","vbs","js","reg","cgi","htaccess" ], "Flash": [ "php","php2","php3","php4","php5","phtml","pwml","inc","asp","aspx","ascx","jsp","cfm","cfc","pl","bat","exe","com","dll","vbs","js","reg","cgi","htaccess" ], "Media": [ "php","php2","php3","php4","php5","phtml","pwml","inc","asp","aspx","ascx","jsp","cfm","cfc","pl","bat","exe","com","dll","vbs","js","reg","cgi","htaccess" ] } """ Zope specific functions """ def isZope(self): # The context object is the zope object if (self.context is not None): return True return False def getZopeRootContext(self): if self.zopeRootContext is None: self.zopeRootContext = self.context.getPhysicalRoot() return self.zopeRootContext def getZopeUploadContext(self): if self.zopeUploadContext is None: folderNames = self.userFilesFolder.split("/") c = self.getZopeRootContext() for folderName in folderNames: if (folderName <> ""): c = c[folderName] self.zopeUploadContext = c return self.zopeUploadContext """ Generic manipulation functions """ def getUserFilesFolder(self): return self.userFilesFolder def getWebUserFilesFolder(self): return self.webUserFilesFolder def getAllowedExtensions(self, resourceType): return self.allowedExtensions[resourceType] def getDeniedExtensions(self, resourceType): return self.deniedExtensions[resourceType] def removeFromStart(self, string, char): return string.lstrip(char) def removeFromEnd(self, string, char): return string.rstrip(char) def convertToXmlAttribute(self, value): if (value is None): value = "" return escape(value) def convertToPath(self, path): if (path[-1] <> "/"): return path + "/" else: return path def getUrlFromPath(self, resourceType, path): if (resourceType is None) or (resourceType == ''): url = "%s%s" % ( self.removeFromEnd(self.getUserFilesFolder(), '/'), path ) else: url = "%s%s%s" % ( self.getUserFilesFolder(), resourceType, path ) return url def getWebUrlFromPath(self, resourceType, path): if (resourceType is None) or (resourceType == ''): url = "%s%s" % ( self.removeFromEnd(self.getWebUserFilesFolder(), '/'), path ) else: url = "%s%s%s" % ( self.getWebUserFilesFolder(), resourceType, path ) return url def removeExtension(self, fileName): index = fileName.rindex(".") newFileName = fileName[0:index] return newFileName def getExtension(self, fileName): index = fileName.rindex(".") + 1 fileExtension = fileName[index:] return fileExtension def getParentFolder(self, folderPath): parentFolderPath = self.parentFolderRe.sub('', folderPath) return parentFolderPath """ serverMapFolder Purpose: works out the folder map on the server """ def serverMapFolder(self, resourceType, folderPath): # Get the resource type directory resourceTypeFolder = "%s%s/" % ( self.getUserFilesFolder(), resourceType ) # Ensure that the directory exists self.createServerFolder(resourceTypeFolder) # Return the resource type directory combined with the # required path return "%s%s" % ( resourceTypeFolder, self.removeFromStart(folderPath, '/') ) """ createServerFolder Purpose: physically creates a folder on the server """ def createServerFolder(self, folderPath): # Check if the parent exists parentFolderPath = self.getParentFolder(folderPath) if not(os.path.exists(parentFolderPath)): errorMsg = self.createServerFolder(parentFolderPath) if errorMsg is not None: return errorMsg # Check if this exists if not(os.path.exists(folderPath)): os.mkdir(folderPath) os.chmod(folderPath, 0755) errorMsg = None else: if os.path.isdir(folderPath): errorMsg = None else: raise "createServerFolder: Non-folder of same name already exists" return errorMsg """ getRootPath Purpose: returns the root path on the server """ def getRootPath(self): return self.rootPath """ setXmlHeaders Purpose: to prepare the headers for the xml to return """ def setXmlHeaders(self): #now = self.context.BS_get_now() #yesterday = now - 1 self.setHeader("Content-Type", "text/xml") #self.setHeader("Expires", yesterday) #self.setHeader("Last-Modified", now) #self.setHeader("Cache-Control", "no-store, no-cache, must-revalidate") self.printHeaders() return def setHeader(self, key, value): if (self.isZope()): self.context.REQUEST.RESPONSE.setHeader(key, value) else: print "%s: %s" % (key, value) return def printHeaders(self): # For non-Zope requests, we need to print an empty line # to denote the end of headers if (not(self.isZope())): print "" """ createXmlFooter Purpose: returns the xml header """ def createXmlHeader(self, command, resourceType, currentFolder): self.setXmlHeaders() s = "" # Create the XML document header s += """<?xml version="1.0" encoding="utf-8" ?>""" # Create the main connector node s += """<Connector command="%s" resourceType="%s">""" % ( command, resourceType ) # Add the current folder node s += """<CurrentFolder path="%s" url="%s" />""" % ( self.convertToXmlAttribute(currentFolder), self.convertToXmlAttribute( self.getWebUrlFromPath( resourceType, currentFolder ) ), ) return s """ createXmlFooter Purpose: returns the xml footer """ def createXmlFooter(self): s = """</Connector>""" return s """ sendError Purpose: in the event of an error, return an xml based error """ def sendError(self, number, text): self.setXmlHeaders() s = "" # Create the XML document header s += """<?xml version="1.0" encoding="utf-8" ?>""" s += """<Connector>""" s += """<Error number="%s" text="%s" />""" % (number, text) s += """</Connector>""" return s """ getFolders Purpose: command to recieve a list of folders """ def getFolders(self, resourceType, currentFolder): if (self.isZope()): return self.getZopeFolders(resourceType, currentFolder) else: return self.getNonZopeFolders(resourceType, currentFolder) def getZopeFolders(self, resourceType, currentFolder): # Open the folders node s = "" s += """<Folders>""" zopeFolder = self.findZopeFolder(resourceType, currentFolder) for (name, o) in zopeFolder.objectItems(["Folder"]): s += """<Folder name="%s" />""" % ( self.convertToXmlAttribute(name) ) # Close the folders node s += """</Folders>""" return s def getNonZopeFolders(self, resourceType, currentFolder): # Map the virtual path to our local server serverPath = self.serverMapFolder(resourceType, currentFolder) # Open the folders node s = "" s += """<Folders>""" for someObject in os.listdir(serverPath): someObjectPath = os.path.join(serverPath, someObject) if os.path.isdir(someObjectPath): s += """<Folder name="%s" />""" % ( self.convertToXmlAttribute(someObject) ) # Close the folders node s += """</Folders>""" return s """ getFoldersAndFiles Purpose: command to recieve a list of folders and files """ def getFoldersAndFiles(self, resourceType, currentFolder): if (self.isZope()): return self.getZopeFoldersAndFiles(resourceType, currentFolder) else: return self.getNonZopeFoldersAndFiles(resourceType, currentFolder) def getNonZopeFoldersAndFiles(self, resourceType, currentFolder): # Map the virtual path to our local server serverPath = self.serverMapFolder(resourceType, currentFolder) # Open the folders / files node folders = """<Folders>""" files = """<Files>""" for someObject in os.listdir(serverPath): someObjectPath = os.path.join(serverPath, someObject) if os.path.isdir(someObjectPath): folders += """<Folder name="%s" />""" % ( self.convertToXmlAttribute(someObject) ) elif os.path.isfile(someObjectPath): size = os.path.getsize(someObjectPath) files += """<File name="%s" size="%s" />""" % ( self.convertToXmlAttribute(someObject), os.path.getsize(someObjectPath) ) # Close the folders / files node folders += """</Folders>""" files += """</Files>""" # Return it s = folders + files return s def getZopeFoldersAndFiles(self, resourceType, currentFolder): folders = self.getZopeFolders(resourceType, currentFolder) files = self.getZopeFiles(resourceType, currentFolder) s = folders + files return s def getZopeFiles(self, resourceType, currentFolder): # Open the files node s = "" s += """<Files>""" zopeFolder = self.findZopeFolder(resourceType, currentFolder) for (name, o) in zopeFolder.objectItems(["File","Image"]): s += """<File name="%s" size="%s" />""" % ( self.convertToXmlAttribute(name), ((o.get_size() / 1024) + 1) ) # Close the files node s += """</Files>""" return s def findZopeFolder(self, resourceType, folderName): # returns the context of the resource / folder zopeFolder = self.getZopeUploadContext() folderName = self.removeFromStart(folderName, "/") folderName = self.removeFromEnd(folderName, "/") if (resourceType <> ""): try: zopeFolder = zopeFolder[resourceType] except: zopeFolder.manage_addProduct["OFSP"].manage_addFolder(id=resourceType, title=resourceType) zopeFolder = zopeFolder[resourceType] if (folderName <> ""): folderNames = folderName.split("/") for folderName in folderNames: zopeFolder = zopeFolder[folderName] return zopeFolder """ createFolder Purpose: command to create a new folder """ def createFolder(self, resourceType, currentFolder): if (self.isZope()): return self.createZopeFolder(resourceType, currentFolder) else: return self.createNonZopeFolder(resourceType, currentFolder) def createZopeFolder(self, resourceType, currentFolder): # Find out where we are zopeFolder = self.findZopeFolder(resourceType, currentFolder) errorNo = 0 errorMsg = "" if self.request.has_key("NewFolderName"): newFolder = self.request.get("NewFolderName", None) zopeFolder.manage_addProduct["OFSP"].manage_addFolder(id=newFolder, title=newFolder) else: errorNo = 102 error = """<Error number="%s" originalDescription="%s" />""" % ( errorNo, self.convertToXmlAttribute(errorMsg) ) return error def createNonZopeFolder(self, resourceType, currentFolder): errorNo = 0 errorMsg = "" if self.request.has_key("NewFolderName"): newFolder = self.request.get("NewFolderName", None) currentFolderPath = self.serverMapFolder( resourceType, currentFolder ) try: newFolderPath = currentFolderPath + newFolder errorMsg = self.createServerFolder(newFolderPath) if (errorMsg is not None): errorNo = 110 except: errorNo = 103 else: errorNo = 102 error = """<Error number="%s" originalDescription="%s" />""" % ( errorNo, self.convertToXmlAttribute(errorMsg) ) return error """ getFileName Purpose: helper function to extrapolate the filename """ def getFileName(self, filename): for splitChar in ["/", "\\"]: array = filename.split(splitChar) if (len(array) > 1): filename = array[-1] return filename """ fileUpload Purpose: command to upload files to server """ def fileUpload(self, resourceType, currentFolder): if (self.isZope()): return self.zopeFileUpload(resourceType, currentFolder) else: return self.nonZopeFileUpload(resourceType, currentFolder) def zopeFileUpload(self, resourceType, currentFolder, count=None): zopeFolder = self.findZopeFolder(resourceType, currentFolder) file = self.request.get("NewFile", None) fileName = self.getFileName(file.filename) fileNameOnly = self.removeExtension(fileName) fileExtension = self.getExtension(fileName).lower() if (count): nid = "%s.%s.%s" % (fileNameOnly, count, fileExtension) else: nid = fileName title = nid try: zopeFolder.manage_addProduct['OFSP'].manage_addFile( id=nid, title=title, file=file.read() ) except: if (count): count += 1 else: count = 1 self.zopeFileUpload(resourceType, currentFolder, count) return def nonZopeFileUpload(self, resourceType, currentFolder): errorNo = 0 errorMsg = "" if self.request.has_key("NewFile"): # newFile has all the contents we need newFile = self.request.get("NewFile", "") # Get the file name newFileName = newFile.filename newFileNameOnly = self.removeExtension(newFileName) newFileExtension = self.getExtension(newFileName).lower() allowedExtensions = self.getAllowedExtensions(resourceType) deniedExtensions = self.getDeniedExtensions(resourceType) if (allowedExtensions is not None): # Check for allowed isAllowed = False if (newFileExtension in allowedExtensions): isAllowed = True elif (deniedExtensions is not None): # Check for denied isAllowed = True if (newFileExtension in deniedExtensions): isAllowed = False else: # No extension limitations isAllowed = True if (isAllowed): if (self.isZope()): # Upload into zope self.zopeFileUpload(resourceType, currentFolder) else: # Upload to operating system # Map the virtual path to the local server path currentFolderPath = self.serverMapFolder( resourceType, currentFolder ) i = 0 while (True): newFilePath = "%s%s" % ( currentFolderPath, newFileName ) if os.path.exists(newFilePath): i += 1 newFilePath = "%s%s(%s).%s" % ( currentFolderPath, newFileNameOnly, i, newFileExtension ) errorNo = 201 break else: fileHandle = open(newFilePath,'w') linecount = 0 while (1): #line = newFile.file.readline() line = newFile.readline() if not line: break fileHandle.write("%s" % line) linecount += 1 os.chmod(newFilePath, 0777) break else: newFileName = "Extension not allowed" errorNo = 203 else: newFileName = "No File" errorNo = 202 string = """ <script type="text/javascript"> window.parent.frames["frmUpload"].OnUploadCompleted(%s,"%s"); </script> """ % ( errorNo, newFileName.replace('"',"'") ) return string def run(self): s = "" try: # Check if this is disabled if not(self.enabled): return self.sendError(1, "This connector is disabled. Please check the connector configurations and try again") # Make sure we have valid inputs if not( (self.request.has_key("Command")) and (self.request.has_key("Type")) and (self.request.has_key("CurrentFolder")) ): return # Get command command = self.request.get("Command", None) # Get resource type resourceType = self.request.get("Type", None) # folder syntax must start and end with "/" currentFolder = self.request.get("CurrentFolder", None) if (currentFolder[-1] <> "/"): currentFolder += "/" if (currentFolder[0] <> "/"): currentFolder = "/" + currentFolder # Check for invalid paths if (".." in currentFolder): return self.sendError(102, "") # File upload doesn't have to return XML, so intercept # her:e if (command == "FileUpload"): return self.fileUpload(resourceType, currentFolder) # Begin XML s += self.createXmlHeader(command, resourceType, currentFolder) # Execute the command if (command == "GetFolders"): f = self.getFolders elif (command == "GetFoldersAndFiles"): f = self.getFoldersAndFiles elif (command == "CreateFolder"): f = self.createFolder else: f = None if (f is not None): s += f(resourceType, currentFolder) s += self.createXmlFooter() except Exception, e: s = "ERROR: %s" % e return s # Running from command line if __name__ == '__main__': # To test the output, uncomment the standard headers #print "Content-Type: text/html" #print "" print getFCKeditorConnector() """ Running from zope, you will need to modify this connector. If you have uploaded the FCKeditor into Zope (like me), you need to move this connector out of Zope, and replace the "connector" with an alias as below. The key to it is to pass the Zope context in, as we then have a like to the Zope context. ## Script (Python) "connector.py" ##bind container=container ##bind context=context ##bind namespace= ##bind script=script ##bind subpath=traverse_subpath ##parameters=*args, **kws ##title=ALIAS ## import Products.connector as connector return connector.getFCKeditorConnector(context=context).run() """
Python
import os, sqlite3, logging from Tkinter import * class TKView: def __init__(self,pid,env): self.pid = pid self.env = env self.root = Tk() self.toolbar = Frame(self.root) self.toolbar.pack(side=TOP, fill=X) self.badd = Button(self.toolbar, text="Add", command=self._add) self.badd.pack(side=LEFT) self.brem = Button(self.toolbar, text="Remove", command=self._rem) self.brem.pack(side=LEFT) def _add(self, *args): logging.debug(str(args)) def _rem(self, *args): logging.debug(str(args)) def Run(pid,env): tv = TKView(pid,env) mainloop() if __name__ == "__main__": env = {} env['PORT'] = 6899 env['CONFIGDIR'] = '~/.config/' env['CONFIGLOC'] = 'ffshare' env['DBNAME'] = 'files.db' env['DOWNLOADTO'] = '~/Dekstop/' env['DBTABLE'] = env['CONFIGLOC']+'_files' env['SELECT_ALL_PATHS'] = 'select path from ' + env['DBTABLE'] + ';' Run(0, env)
Python
import pybonjour import threading, os, sys, signal, select import logging class listener(threading.Thread): def __init__(self, protocol, callback, fail_cb): self.callback = callback self.timeout = 5 self.resolved = [] self.protocol = protocol self.failed = fail_cb def mini_cb(self, *args): logging.info(str(args)) def run(self): browse_sdRef = pybonjour.DNSServiceBrowse(regtype = self.protocol, callBack = self.mini_cb) try: while True: rdy = select.select([browse_sdRef], [], []) if browse_sdRef in rdy: pybonjour.DNSServiceProcessResult(browse_sdRef) finally: browse_sdRef.close() wx.CallAfter(self.failed)
Python
import wx import os, sqlite3, logging, copy import httplib, select, threading, signal from simple_parser import SimpleParser def getFileList(name,address,ip,port,callback): """ Gets a file listing from the specified computer, does a wxWidgets thread safe call to the last argument, 'callback' """ con = httplib.HTTPConnection(ip, port) con.request("GET", "/") content = con.getresponse() try: ps = SimpleParser(content) ps.parse() paths = ps.getPaths() wx.CallAfter(callback, paths, address) except ExpatError, e: logging.warning('parsing failed'+str(e)) except ParseError, e: logging.warning('parsing failed'+str(e)) def downloadFile(ip, port, path, destination_dir, chunk, completed): """ Downloads the specified file to destination_dir, calls 'chunk' per kilobyte, calls completed when done. All callbacks are done using wx.CallAfter """ dest = None if len(os.path.basename(path)): dest = file(os.path.join(destination_dir, os.path.basename(path)),'w') else: dest = file(os.tempnam(destination_dir),'w') logging.debug('Starting download') con = httplib.HTTPConnection(ip, port) con.request("GET", path) response = con.getresponse() for chunk in range(0, response.length, 1024): next = response.read(1024) dest.write(next) wx.CallAfter(chunk) dest.close() wx.CallAfter(completed) class Main(wx.Frame): def __init__(self, parent, id, title, pid, env): wx.Frame.__init__(self,parent,wx.ID_ANY,title, size=(700,400), style=wx.NO_FULL_REPAINT_ON_RESIZE | wx.DEFAULT_FRAME_STYLE) self.pid = pid self.env = env self.Show(True) self.menu = wx.Menu() self.current_directory = os.getcwd() self.toolbar = wx.ToolBar(self,style=wx.TB_HORIZONTAL|wx.TB_TEXT|wx.TB_TOP) self.bv_sizer = wx.BoxSizer(wx.VERTICAL) self.bh_sizer = wx.BoxSizer(wx.HORIZONTAL) self.browse_tree = wx.TreeCtrl(self,style=wx.BORDER_SUNKEN|wx.TR_HIDE_ROOT) self.share_tree = wx.TreeCtrl(self,style=wx.BORDER_SUNKEN) self.progress = wx.ListCtrl(self, style=wx.LC_REPORT) self.art = wx.ArtProvider() self.SetSizer(self.bv_sizer) self.bv_sizer.Add(self.toolbar,0, wx.ALIGN_TOP) self.bv_sizer.Add(self.bh_sizer,2,wx.EXPAND) self.bv_sizer.Add(self.progress,1,wx.ALIGN_BOTTOM|wx.EXPAND) self.bh_sizer.Add(self.share_tree,1,wx.EXPAND|wx.ALIGN_LEFT) self.bh_sizer.Add(self.browse_tree,1,wx.EXPAND|wx.ALIGN_RIGHT) self.share_tree.AddRoot('Shared Files') # XXX self.browse_tree.AddRoot('') # XXX self.progress.InsertColumn(0,"File") self.progress.InsertColumn(1,"Progress") ## # self.toolbar.AddLabelTool(self, id, label, bitmap ## self.DOWNBUT_ID = wx.NewId() self.toolbar.AddLabelTool(self.DOWNBUT_ID, "Download", self.art.GetBitmap(wx.ART_GO_DOWN)) self.ADDBUT_ID = wx.NewId() self.toolbar.AddLabelTool(self.ADDBUT_ID, "Share File", self.art.GetBitmap(wx.ART_NEW)) self.DELBUT_ID = wx.NewId() self.toolbar.AddLabelTool(self.DELBUT_ID, "Stop Sharing", self.art.GetBitmap(wx.ART_DELETE)) self.QBUT_ID = wx.NewId() self.toolbar.AddLabelTool(self.QBUT_ID, "Quit", self.art.GetBitmap(wx.ART_QUIT)) self.Bind(wx.EVT_TOOL, self.quit, id=self.QBUT_ID) self.Bind(wx.EVT_CLOSE, self.quit) self.Bind(wx.EVT_TOOL, self._add_file, id=self.ADDBUT_ID) self.Bind(wx.EVT_TOOL, self._rem_file, id=self.DELBUT_ID) self.Bind(wx.EVT_TOOL, self.download, id=self.DOWNBUT_ID) self.browse_tree.Bind(wx.EVT_TREE_SEL_CHANGED, self._b_t_change, id=self.browse_tree.Id) self.share_tree.Bind(wx.EVT_TREE_SEL_CHANGED, self._s_t_change, id=self.share_tree.Id) self.Layout() self.prepopulate() self.start_zeroconf() def FIXME(self, *args): logging.debug("FIXME called: %s" % args) def download(self, *args): logging.debug("Download button args: %s" % args) def _add_file(self, *args): logging.debug("Add file called: %s" % args) chooser = wx.FileDialog(self, "Add files", self.current_directory, "", "*", wx.OPEN) if chooser.ShowModal() == wx.ID_OK: path = chooser.GetPath() if os.path.exists(path): self.current_directory = os.path.dirname(path) if os.path.isdir(path): logging.error("%s is a directory, which we can't add yet" % path) else: conn = sqlite3.connect(os.path.join(self.env.get('CONFIGDIR'), self.env.get('CONFIGLOC'), self.env.get('DBNAME')) ) cursor = conn.cursor() # FIXME: this bit is getting copied and pasted around in the various # GUIs, add it to the 'env'? cursor.execute('INSERT INTO ' + self.env.get('DBTABLE') + ' values ( ?, ?, ? ) ', (path, False, False)) conn.commit() self.share_tree.AppendItem(self.share_tree.RootItem, path) else: logging.error("%s is not a proper location, what went wrong?" % path) chooser.Destroy() def _rem_file(self, *args): logging.debug("Rem file called: %s" % args) def _s_t_change(self, event): logging.debug("share_tree" % event) def _b_t_change(self, event): logging.debug("browse_tree" % event) def _avahi_add_server(self, name, address, ip, port): t=threading.Thread(target=getFileList,args=(name,address,ip,port, self._add_remote_files)) t.setDaemon(True) t.start() def _add_remote_files(self, paths, address): root = self.browse_tree.AppendItem(self.browse_tree.RootItem, address) for path in paths: self.browse_tree.AppendItem(root, path) logging.debug("added %s" % path) self.browse_tree.ExpandAll() def start_zeroconf(self): try: from avahi_search import AvahiSearch import gobject, dbus.glib gobject.threads_init() dbus.glib.threads_init() self.search = AvahiSearch('_fhttp._tcp') self.search.register_service_handler(self._avahi_add_server) except ImportError, e: logging.error(str(e)+"\tStarting pybonjour") try: import zero_listener except ImportError: logging.critical("Couldn't connect to zeroconf, sorry") def prepopulate(self): conn = sqlite3.connect( os.path.expanduser(os.path.join(self.env.get('CONFIGDIR'), self.env.get('CONFIGLOC'), self.env.get('DBNAME'))) ) cursor = conn.cursor() paths = [x[0] for x in cursor.execute(self.env.get('SELECT_ALL_PATHS')).fetchall()] for path in paths: self.share_tree.AppendItem(self.share_tree.RootItem, path) self.share_tree.ExpandAll() # Show def quit(self,*args): self.Destroy() os.kill(self.pid, signal.SIGTERM) def Run(pid,env): """ Start the wx GUI """ app = wx.App(0) frame = Main(None, 100, "Share Files", pid, copy.deepcopy(env)) app.MainLoop() if __name__ == "__main__": env = {} env['PORT'] = 6899 env['CONFIGDIR'] = '~/.config/' env['CONFIGLOC'] = 'ffshare' env['DBNAME'] = 'files.db' env['DOWNLOADTO'] = '~/Desktop/' env['DBTABLE'] = env['CONFIGLOC']+'_files' env['SELECT_ALL_PATHS'] = 'select path from ' + env['DBTABLE'] + ';' Run(0, env)
Python
#!/usr/bin/env python import sys, os import logging import sqlite3 from optparse import OptionParser """ Simple cross platform file sharing application. Uses Zeroconf for discovery, http for transport, and comes with a variety of GUI implementations. @author: Henry Finucane @organization: TC Productions @copyright: Copyright 2008 Henry Finucane @contact: h.finucane NOSPAM_AT GMAIL [dot] com """ if sys.platform == 'win32': try: from wx_gui import gui except ImportError, e: import tk_gui as gui except Exception, e: print "Couldn't start GUI" print e exit(-1) else: try: from gtk_gui import gui except ImportError, e: print e import tk_gui as gui except Exception, e: print "Couldn't start GUI" print e exit(-1) try: import cherrypy_server except ImportError, e: print "Need CherryPy: ", e exit(-1) except Exception, e: print "Couldn't import CherryPy, something seems broken." print e exit(-1) if __name__ == "__main__": parser = OptionParser() parser.add_option("-p", "--port", dest="PORT", help="server port", default=6899) parser.add_option("-c", "--configdir", dest="CONFIGDIR", help="Configuration file directory", default=os.path.expanduser(r"~/.config/")) parser.add_option("-D", "--dbname", dest="DBNAME", help="Database file name", default="files.db") parser.add_option("-d", "--destination", dest="DOWNLOADTO", help="Download to this directory", default=os.path.expanduser("~/Desktop/")) parser.add_option("-v", "--debug", "--verbose", dest="DEBUG", help="Be noisy about what's going on", action="store_true", default=False) parser.add_option("--wxpython", dest="USEWX", help="Use wxPython UI", action="store_true", default=False) (env, args) = parser.parse_args() # Fake a dictionary: env.__getitem__ = lambda x: getattr(env,x) env.get = env.__getitem__ env.__setitem__ = lambda y,z: setattr(env,y,z) env['CONFIGLOC'] = 'ffshare' env['DBTABLE'] = env['CONFIGLOC']+'_files' env['SELECT_ALL_PATHS'] = 'select path from ' + env['DBTABLE'] + ';' if env.get('DEBUG'): logging.basicConfig(level=logging.DEBUG) else: logging.basicConfig(level=logging.WARNING) if env.get('USEWX'): try: from wx_gui import gui except Exception, e: logging.critical("Cannot import wxPython layer because:\n%s" % e) # If configuration directory isn't there, create it if not os.path.isdir(env['CONFIGDIR']): os.mkdir(env['CONFIGDIR']) if not os.path.isdir( os.path.join(env.get('CONFIGDIR'), env.get('CONFIGLOC')) ): os.mkdir( os.path.join(env.get('CONFIGDIR'), env.get('CONFIGLOC')) ) # If database is empty, create the schema conn = sqlite3.connect(os.path.join(env.get('CONFIGDIR'), env.get('CONFIGLOC'), env.get('DBNAME'))) cursor = conn.cursor() if not cursor.execute('SELECT * FROM sqlite_master').fetchall(): cursor.execute("""CREATE TABLE %s ( path TEXT , dir BOOL , descend BOOL ) ; """ % (env['DBTABLE'])) conn.commit() pid = os.fork() if pid == 0 : gui.Run(pid,env) else: cherrypy_server.server(env)
Python
import sys, os, sqlite3, logging, socket import cherrypy from cherrypy.lib.static import serve_file import mimetypes from avahi_service import AvahiService def server(env): """ Runs a cherrypy http server for files you want to share. """ def formatter(pathlist): ret = '' for p in pathlist: ret += '<li><a href="%s">%s</a></li>' % (p,p) return ret class FileServer(object): def index(self): # connections are dubiously threadsafe conn = sqlite3.connect( os.path.join(env.get('CONFIGDIR'), env.get('CONFIGLOC'), env.get('DBNAME')) ) cursor = conn.cursor() paths = [x[0] for x in cursor.execute(env.get('SELECT_ALL_PATHS')).fetchall()] # FIXME: This whole thing seems like bad practice: template = file(os.path.join('templates', 'homepage.html'),'r').read() return template % ( formatter(paths) ) def default(self,*path): prelim = os.path.join(path[0], *path[1:]) # evil syntax if sys.platform == 'win32': prelim = 'C:\\' + prelim else: prelim = '/' + prelim conn = sqlite3.connect( os.path.join(env.get('CONFIGDIR'), env.get('CONFIGLOC'), env.get('DBNAME')) ) cursor = conn.cursor() if cursor.execute('SELECT path FROM ffshare_files WHERE path == ?;', (prelim,)).fetchall(): # FIXME if os.path.exists(prelim) and os.access(prelim, os.R_OK) and not os.path.isdir(prelim): mime = mimetypes.guess_type(prelim) if mime[0]: return serve_file(prelim, mime[0], "attachment") else: return serve_file(prelim, "application/x-download", "attachment") else: logging.error('invalid file or didn\'t have access') else: logging.error('cursor not found') cherrypy.response.status = 404 return self.index() default.exposed = True index.exposed = True cherrypy.config['server.socket_port'] = env.get('PORT') avs = AvahiService('FFShare-%s' % socket.gethostname(), '_fhttp._tcp', env.get('PORT')) avs.start() cherrypy.quickstart(FileServer())
Python
try: import xml.etree.cElementTree as ET except ImportError: import cElementTree as ET except ImportError: import xml.etree.ElementTree as ET except ImportError: import elementtree.ElementTree as ET except Exception, e: print "Can't import an ElementTree- python libraries messed up?" raise e class SimpleParser: """ Very simple class to extract paths from the very simple ad-hoc html sharing spec. >>> ps = SimpleParser() >>> # nasty process for generating a fixture: >>> root = ET.Element('html') >>> head = ET.SubElement(root,'head') >>> body = ET.SubElement(root,'body') >>> body.text = 'obfuscate' >>> h1 = ET.SubElement(body,'h1') >>> ul = ET.SubElement(body,'ul') >>> li1 = ET.SubElement(ul,'li') >>> link1 = ET.SubElement(li1,'a') >>> link1.set('href','foo/bar') >>> ps.ET = ET.ElementTree(root) >>> ps.parse() >>> ps.getPaths() ['foo/bar'] >>> link2 = ET.SubElement(li1,'a') >>> link2.set('href','bar/baz') >>> ps.ET = ET.ElementTree(root) >>> ps.parse() >>> ps.getPaths() ['foo/bar', 'bar/baz'] >>> li2 = ET.SubElement(ul,'li') >>> link2 = ET.SubElement(li2, 'a') >>> link2.set('href','qux/kang') >>> ps.ET = ET.ElementTree(root) >>> ps.parse() >>> ps.getPaths() ['foo/bar', 'bar/baz', 'qux/kang'] """ def __init__(self,target=None): if target is not None: self.ET = ET.parse(target) self.root = self.ET.getroot() else: self.ET = None self.root = None self.paths = [] def parse(self): self.paths = [] if self.ET is not None: self.root = self.ET.getroot() for item in self.root.findall('body/ul/li'): for link in item.findall('a'): self.paths.append(link.get('href')) else: raise Exception('Nothing to parse') def getPaths(self): return self.paths def _test(): import doctest doctest.testmod() if __name__ == "__main__": _test()
Python
#!/usr/bin/env python import sys, os import logging import sqlite3 from optparse import OptionParser """ Simple cross platform file sharing application. Uses Zeroconf for discovery, http for transport, and comes with a variety of GUI implementations. @author: Henry Finucane @organization: TC Productions @copyright: Copyright 2008 Henry Finucane @contact: h.finucane NOSPAM_AT GMAIL [dot] com """ if sys.platform == 'win32': try: from wx_gui import gui except ImportError, e: import tk_gui as gui except Exception, e: print "Couldn't start GUI" print e exit(-1) else: try: from gtk_gui import gui except ImportError, e: print e import tk_gui as gui except Exception, e: print "Couldn't start GUI" print e exit(-1) try: import cherrypy_server except ImportError, e: print "Need CherryPy: ", e exit(-1) except Exception, e: print "Couldn't import CherryPy, something seems broken." print e exit(-1) if __name__ == "__main__": parser = OptionParser() parser.add_option("-p", "--port", dest="PORT", help="server port", default=6899) parser.add_option("-c", "--configdir", dest="CONFIGDIR", help="Configuration file directory", default=os.path.expanduser(r"~/.config/")) parser.add_option("-D", "--dbname", dest="DBNAME", help="Database file name", default="files.db") parser.add_option("-d", "--destination", dest="DOWNLOADTO", help="Download to this directory", default=os.path.expanduser("~/Desktop/")) parser.add_option("-v", "--debug", "--verbose", dest="DEBUG", help="Be noisy about what's going on", action="store_true", default=False) parser.add_option("--wxpython", dest="USEWX", help="Use wxPython UI", action="store_true", default=False) (env, args) = parser.parse_args() # Fake a dictionary: env.__getitem__ = lambda x: getattr(env,x) env.get = env.__getitem__ env.__setitem__ = lambda y,z: setattr(env,y,z) env['CONFIGLOC'] = 'ffshare' env['DBTABLE'] = env['CONFIGLOC']+'_files' env['SELECT_ALL_PATHS'] = 'select path from ' + env['DBTABLE'] + ';' if env.get('DEBUG'): logging.basicConfig(level=logging.DEBUG) else: logging.basicConfig(level=logging.WARNING) if env.get('USEWX'): try: from wx_gui import gui except Exception, e: logging.critical("Cannot import wxPython layer because:\n%s" % e) # If configuration directory isn't there, create it if not os.path.isdir(env['CONFIGDIR']): os.mkdir(env['CONFIGDIR']) if not os.path.isdir( os.path.join(env.get('CONFIGDIR'), env.get('CONFIGLOC')) ): os.mkdir( os.path.join(env.get('CONFIGDIR'), env.get('CONFIGLOC')) ) # If database is empty, create the schema conn = sqlite3.connect(os.path.join(env.get('CONFIGDIR'), env.get('CONFIGLOC'), env.get('DBNAME'))) cursor = conn.cursor() if not cursor.execute('SELECT * FROM sqlite_master').fetchall(): cursor.execute("""CREATE TABLE %s ( path TEXT , dir BOOL , descend BOOL ) ; """ % (env['DBTABLE'])) conn.commit() pid = os.fork() if pid == 0 : gui.Run(pid,env) else: cherrypy_server.server(env)
Python
import dbus, gobject, avahi from dbus import DBusException from dbus.mainloop.glib import DBusGMainLoop import logging class AvahiSearch: def __init__(self, type, domain='local', flags=dbus.UInt32(0), protocol=avahi.PROTO_UNSPEC, interface=avahi.IF_UNSPEC, mainloop=DBusGMainLoop, callback=None): self.loop = mainloop() self.bus = dbus.SystemBus(mainloop=self.loop) self.server = dbus.Interface( self.bus.get_object(avahi.DBUS_NAME, avahi.DBUS_PATH_SERVER), avahi.DBUS_INTERFACE_SERVER) self.type = type self.domain = domain self.flags = flags self.protocol = protocol self.interface = interface self.callback = callback # init self._register() def _register(self): self.sbrowser = dbus.Interface(self.bus.get_object(avahi.DBUS_NAME, self.server.ServiceBrowserNew(self.interface, self.protocol, self.type, self.domain, self.flags)), avahi.DBUS_INTERFACE_SERVICE_BROWSER) self.sbrowser.connect_to_signal("ItemNew", self._firsthandler) def register_service_handler(self, callback): # FIXME: check if callback has proper interface self.callback = callback def _firsthandler(self, interface, protocol, name, stype, domain, flags): # FIXME: do some checking if False and flags & avahi.LOOKUP_RESULT_LOCAL: # disabled for now, # for testing # local service, skip print 'found local service: %s %s' % (name, stype) pass else: self.server.ResolveService(interface, protocol, name, stype, domain, avahi.PROTO_UNSPEC, dbus.UInt32(0), reply_handler=self._finalhandler, error_handler=self._errorhandler) def _errorhandler(self, *args): logging.warning(str(args)) print args def _finalhandler(self, *args): if self.callback is not None: self.callback(args[2],args[5],args[7],args[8])
Python
import gobject, gtk import threading, os, httplib from simple_parser import SimpleParser import logging class FileDownload(threading.Thread, gobject.GObject): __gsignals__ = { "file-downloaded" : ( gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, [gobject.TYPE_STRING]), "chunk-downloaded" : ( gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, [gobject.TYPE_STRING]), } def __init__(self, ip, port, path, destination_dir): threading.Thread.__init__(self) gobject.GObject.__init__(self) self.ip = ip self.port = port self.path = path name = os.path.basename(path) if len(name): self.dest = file( os.path.join(destination_dir, name), 'w') else: self.dest = file( os.tempnam(destination_dir), 'w') def run(self): logging.info("Download thread running") self.con = httplib.HTTPConnection(self.ip, self.port) self.con.request("GET", self.path) self.resp = self.con.getresponse() for chunk in range(0, self.resp.length, 1024): next = self.resp.read(1024) self.dest.write(next) self.emit('chunk-downloaded',self.path) self.dest.close() self.emit('file-downloaded', self.path) def emit(self, *args): gobject.idle_add(gobject.GObject.emit,self,*args) class ServerQuery(threading.Thread, gobject.GObject): __gsignals__ = { "download-completed" : ( gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, [gobject.TYPE_PYOBJECT]), } def __init__(self, address, ip, port, *args): threading.Thread.__init__(self) gobject.GObject.__init__(self) self.address = address self.ip = ip self.port = port self.paths = None self.piter = args[0] def run(self): con = httplib.HTTPConnection(self.address, self.port) con.request('GET','/') content = con.getresponse() try: ps = SimpleParser(content) ps.parse() self.paths = ps.getPaths() self.emit("download-completed", self.paths) except ExpatError, e: logging.warning('parsing failed'+str(e)) except ParseError, e: logging.warning('parsing failed'+str(e)) def emit(self, *args): gobject.idle_add(gobject.GObject.emit,self,*args) class DownloadManager(): def __init__(self, maxThreads): self.maxThreads = maxThreads self.threads = {} self.pendingThreads = [] self.running = 0 def _thread_completed(self, thread, *args): self.running -= 1 try: del(self.threads[(thread.ip, thread.port, thread.path)]) logging.info("thing deleted") except KeyError, e: logging.debug('thread %s not found to delete. ??' % str(thread)) if self.running < self.maxThreads and self.pendingThreads: self.pendingThreads.pop().start() self.running += 1 def add_download(self, where, to, callback, callback_chunk): if self.threads.get(where) is None: nt = FileDownload(where[0], where[1], where[2], to) self.threads[where] = nt nt.connect("file-downloaded", callback, []) nt.connect("chunk-downloaded", callback_chunk, []) nt.connect("file-downloaded", self._thread_completed, []) #nt.connect("chunk-completed", chunk_callback, []) self.pendingThreads.append(nt) if self.running < self.maxThreads: self.pendingThreads.pop().start() logging.info('thread started') self.running += 1 class QueryManager(): def __init__(self, maxThreads): self.maxThreads = maxThreads self.threads = {} self.pendingThreads = [] self.running = 0 def _thread_completed(self, thread, *args): self.running -= 1 try: del(self.threads[(thread.address, thread.ip, thread.port)]) except KeyError, e: logging.debug('thread %s not found to delete. ??' % str(thread)) if self.running < self.maxThreads and self.pendingThreads: self.pendingThreads.pop().start() self.running += 1 def add_server_query(self, where, callback): if self.threads.get(where) is None: nt = ServerQuery(where[0], where[1], where[2], where[3]) self.threads[where] = nt nt.connect("download-completed", callback, []) nt.connect("download-completed", self._thread_completed, []) self.pendingThreads.append(nt) if self.running < self.maxThreads: self.pendingThreads.pop().start() self.running += 1
Python
import os, sqlite3, logging, socket #from avahi_service import AvahiService from avahi_search import AvahiSearch from simple_parser import SimpleParser import download_thread, signal import pygtk pygtk.require('2.0') import gtk import gobject class GView: def __init__(self,pid,env): self.pid = pid self.env = env self.window = gtk.Window(gtk.WINDOW_TOPLEVEL) self.vbox = gtk.VBox() self.hbox = gtk.HBox() self.sidebar = gtk.VBox() self.toolbar = gtk.Toolbar() self.toolbar.set_style(gtk.TOOLBAR_BOTH) self.netviewport = gtk.ScrolledWindow() self.netviewport.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC) self.localviewport = gtk.ScrolledWindow() self.localviewport.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC) ############## self.nettreestore = gtk.TreeStore(str,str,str) self.nettreeview = gtk.TreeView(self.nettreestore) self.nettvcolumn = gtk.TreeViewColumn('Other Computers') self.nettreeview.append_column(self.nettvcolumn) self.nettvcell = gtk.CellRendererText() self.nettvcolumn.pack_start(self.nettvcell, True) self.nettvcolumn.add_attribute(self.nettvcell, 'text', 0) self.nettvcolumn.set_sort_column_id(0) self.nettreeview.set_search_column(0) self.nettreeview.set_reorderable(True) ############## self.localtreestore = gtk.TreeStore(str) self.localtreeview = gtk.TreeView(self.localtreestore) self.localtvcolumn = gtk.TreeViewColumn('Shared') self.localtreeview.append_column(self.localtvcolumn) self.localtvcell = gtk.CellRendererText() self.localtvcolumn.pack_start(self.localtvcell, True) self.localtvcolumn.add_attribute( self.localtvcell, 'text', 0 ) self.localtvcolumn.set_sort_column_id(0) self.localtreeview.set_search_column(0) self.localtreeview.set_reorderable(True) ############## self.progressStore = gtk.ListStore(int, str) self.progressStore.map = {} self.progressTree = gtk.TreeView(self.progressStore) self.ptvcolumnName = gtk.TreeViewColumn('File', gtk.CellRendererText(), text=1) self.ptvcolumnState = gtk.TreeViewColumn('Finished', gtk.CellRendererProgress(), text=1, value=0, pulse=0) #self.ptvcolumnState.add_attribute(self.ptvcellName, 'progress', 1) self.progressTree.append_column(self.ptvcolumnName) self.progressTree.append_column(self.ptvcolumnState) self.dbut = gtk.ToolButton('Download') self.dbut.set_stock_id(gtk.STOCK_GO_DOWN) self.addbut = gtk.ToolButton('Add') self.addbut.set_stock_id(gtk.STOCK_ADD) self.rembut = gtk.ToolButton('Remove') self.rembut.set_stock_id(gtk.STOCK_REMOVE) self.qbut = gtk.ToolButton('Quit') self.qbut.set_stock_id(gtk.STOCK_QUIT) self.avsearch = AvahiSearch('_fhttp._tcp') #FIXME: hardcoded == bad self.QM = download_thread.QueryManager(5) #FIXME: hardcoded == bad self.DM = download_thread.DownloadManager(5) # signals self.avsearch.register_service_handler(self._add_server) self.qbut.connect("clicked", self.delete_event) self.addbut.connect("clicked", self.add_path) self.rembut.connect("clicked", self.rem_path) self.dbut.connect("clicked", self.download_path) self.window.connect("destroy", self.delete_event) # Construct layout self.window.add(self.vbox) self.localviewport.add_with_viewport(self.localtreeview) self.netviewport.add_with_viewport(self.nettreeview) self.vbox.pack_start(self.toolbar, expand=False) self.vbox.pack_start(self.hbox, expand=True) self.vbox.pack_end(self.progressTree,expand=False) self.hbox.pack_start(self.netviewport, expand=True) self.hbox.pack_end(self.localviewport, expand=True) self.toolbar.add(self.dbut) self.toolbar.add(self.addbut) self.toolbar.add(self.rembut) self.toolbar.add(self.qbut) self.window.set_size_request(500,500) self.window.show_all() self.prepopulate() def _add_server(self, name, address, ip, port): piter = self.nettreestore.append(None,row=(name+'@'+ip,str(ip),str(port))) self.QM.add_server_query((address,ip,port,piter), self.__add_net_paths) def __add_net_paths(self, *args): for path in args[0].paths: self.nettreestore.append(args[0].piter, [path, args[0].ip, str(args[0].port)]) def _rem_path(self, treemodel, path, iter): conn = sqlite3.connect( os.path.join(self.env.get('CONFIGDIR'), self.env.get('CONFIGLOC'), self.env.get('DBNAME')) ) cursor = conn.cursor() cursor.execute("DELETE FROM "+self.env.get('DBTABLE')+" WHERE path = ? ;" , (treemodel[0][0],)) conn.commit() self.localtreestore.remove(iter) def _download_completed(self, dthread, path, *args): logging.debug("MAP->"+str(self.progressStore.map)) logging.info('finished download: '+str(args)) piter = self.progressStore.map.get(path,False) if piter: self.progressStore.remove(piter) del(self.progressStore.map[path]) else: logging.warning("Bad download completed path?") logging.info("Path %s and dict %s" % (path, str(self.progressStore.map))) def _chunk_completed(self, thread, path, *args): piter = self.progressStore.map.get(path, False) if piter: old = self.progressStore.get_value(piter,0) self.progressStore.set_value(piter,0,old+1) else: logging.info("Bad chunk path?") def _download_path(self, treemodel, path, iter): dpath = treemodel.get(iter,0)[0] dip = treemodel.get(iter,1)[0] dport = treemodel.get(iter,2)[0] logging.info("Download started") self.DM.add_download((dip, dport, dpath), self.env['DOWNLOADTO'], self._download_completed, self._chunk_completed) piter = self.progressStore.append(row=(0,dpath)) self.progressStore.map[dpath] = piter logging.debug("MAP->"+str(self.progressStore.map)) def delete_event(self, widget, event=None, data=None): # On the whole, this may be a bad idea gtk.main_quit() os.kill(self.pid, signal.SIGTERM) # cleanup other process return False def rem_path(self, widget): selected = self.localtreeview.get_selection() selected.selected_foreach(self._rem_path) def download_path(self, widget): selected = self.nettreeview.get_selection() selected.selected_foreach(self._download_path) def add_path(self, widget): chooser = gtk.FileChooserDialog(title='Add file or folder', buttons=(gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_OPEN, gtk.RESPONSE_OK)) response = chooser.run() if response == gtk.RESPONSE_OK: if os.path.exists( chooser.get_filename() ): if os.path.isdir( chooser.get_filename()): logging.error('ERROR: full paths not yet implemented, just files, sorry') else: conn = sqlite3.connect( os.path.join(self.env.get('CONFIGDIR'), self.env.get('CONFIGLOC'), self.env.get('DBNAME')) ) cursor = conn.cursor() # FIXME: Deal with multiple selected files? # Add to DB cursor.execute('INSERT INTO ' + self.env.get('DBTABLE') + ' values ( ?, ?, ? ) ', (chooser.get_filename(), False, False)) conn.commit() # Add to GUI self.localtreestore.append(None, row=(chooser.get_filename(),) ) chooser.destroy() def prepopulate(self): conn = sqlite3.connect( os.path.join(self.env.get('CONFIGDIR'), self.env.get('CONFIGLOC'), self.env.get('DBNAME')) ) cursor = conn.cursor() paths = [x[0] for x in cursor.execute(self.env.get('SELECT_ALL_PATHS')).fetchall()] for path in paths: self.localtreestore.append(None, row=(path,)) def Run(pid,env): """ Provides a gtk gui to edit files you serve and find other files on the network """ gobject.threads_init() # So gtk doesn't clobber itself view = GView(pid,env) gtk.main()
Python
import gtk, gobject
Python
import dbus, dbus.mainloop.glib from dbus import DBusException import gobject import avahi import logging class AvahiService: def __init__(self, sName, sType, sPort, sTXT="dummy", domain="local", host="", rename_count=10, mainloop=dbus.mainloop.glib.DBusGMainLoop()): self.serviceName = sName self.serviceType = sType self.servicePort = sPort self.serviceTXT = sTXT self.domain = domain self.host = host self.bus = None self.server = None self.rc = rename_count self.loop = mainloop def start(self): dbus.set_default_main_loop(self.loop) self.bus = dbus.SystemBus() self.server = dbus.Interface( self.bus.get_object( avahi.DBUS_NAME, avahi.DBUS_PATH_SERVER ), avahi.DBUS_INTERFACE_SERVER ) self.server.connect_to_signal( 'StateChanged' , self.__server_state_changed) # Actually start self.__server_state_changed( self.server.GetState() ) def __add_service(self): if getattr(self,'group', 2) == 2: self.group = dbus.Interface( self.bus.get_object( avahi.DBUS_NAME, self.server.EntryGroupNew() ), avahi.DBUS_INTERFACE_ENTRY_GROUP) self.group.connect_to_signal('StateChanged', self.__entry_group_state_changed) # Fraught with peril self.group.AddService( avahi.IF_UNSPEC, # i avahi.PROTO_UNSPEC, # i dbus.UInt32(0), # u self.serviceName, # s self.serviceType, # s self.domain, # s self.host, # s dbus.UInt16(self.servicePort), # q avahi.string_array_to_txt_array(self.serviceTXT) ) self.group.Commit() def __remove_service(self): if getattr(self,'group', False) and self.group: self.group.Reset() def __server_state_changed(self,state): if state == avahi.SERVER_COLLISION: logging.error(" Server name collision ") self.__remove_service() else: self.__add_service() def __entry_group_state_changed(self, state, error): if state == avahi.ENTRY_GROUP_COLLISION: logging.warning("Avahi service name collision, trying to fix") rc -= 1 if rename_count > 0: name = self.server.GetAlternateServiceName(name) self.__remove_service() self.__add_service() else: logging.critical("No suitable service name found") raise Exception("Can't start avahi service") elif state == avahi.ENTRY_GROUP_FAILURE: logging.critical("Error in group state: %s" % error) raise Exception("Poorly understood dbus group failure")
Python
import sys, clr clr.AddReference("System.Windows.Forms") clr.AddReference("System.Drawing") clr.AddReference("Mono.Zeroconf") from System.Drawing import Point import System.Windows.Forms as wf import Mono.Zeroconf from Mono.Zeroconf import ServiceBrowser class WView(wf.Form): def __init__(self): self.Text = "Share Files" self.Height = 500 self.Width = 500 self.OutermostContainer = wf.FlowLayoutPanel() self.OutermostContainer.FlowDirection = wf.FlowDirection.TopDown self.Panel = wf.FlowLayoutPanel() self.Panel.FlowDirection = wf.FlowDirection.LeftToRight self.GridContainer = wf.FlowLayoutPanel() self.GridContainer.FlowDirection = wf.FlowDirection.LeftToRight self.OutermostContainer.Width = self.Width self.OutermostContainer.Height = self.Height self.GridContainer.Width = self.OutermostContainer.Width self.Panel.Width = self.OutermostContainer.Width self.OutermostContainer.Dock=wf.DockStyle.Fill self.OutermostContainer.AutoSize = True self.OutermostContainer.AutoSizeMode = wf.AutoSizeMode.GrowAndShrink #self.GridContainer.Dock = wf.DockStyle.Fill self.GridContainer.AutoSize = True self.GridContainer.AutoSizeMode = wf.AutoSizeMode.GrowAndShrink #self.Panel.AutoSize = True #self.Panel.AutoSizeMode = wf.AutoSizeMode.GrowAndShrink self.addbut = wf.Button(Text="Add") self.addbut.Click += self._add self.rembut = wf.Button(Text="Remove") self.rembut.Click +=self._rem self.qbut = wf.Button(Text="Quit") self.qbut.Click += self._quit self.Panel.Controls.Add(self.addbut) self.Panel.Controls.Add(self.rembut) self.Panel.Controls.Add(self.qbut) self.lnet = wf.ListView() self.lnet.View = wf.View.Details self.lnet.LabelEdit = False self.filev = wf.ListView() self.filev.View = wf.View.Details self.filev.LabelEdit = False # I have no idea why -2 self.lnet.Columns.Add("Browsing:", -2, wf.HorizontalAlignment.Center) self.GridContainer.Controls.Add(self.lnet) self.filev.Columns.Add("Files:", -2, wf.HorizontalAlignment.Center) self.GridContainer.Controls.Add(self.filev) self.OutermostContainer.Controls.Add(self.Panel) self.OutermostContainer.Controls.Add(self.GridContainer) self.Controls.Add(self.OutermostContainer) browser = ServiceBrowser() browser.ServiceAdded += lambda x,y: sys.stderr.write(str(args)) browser.Browse('_fhttp._tcp','local') def _quit(self,*args): wf.Application.Exit() def _add(self, button, event): print "{stub for adding file}" def _rem(self, *args): print "{stub for removing file}" def gcall(*args): print "Called w\:", str(args) if __name__ == "__main__": gui = WView() wf.Application.Run(gui)
Python
# http://www.packtpub.com/article/writing-a-package-in-python from setuptools import setup, Command # adapted from Apache libcloud setup.py class DocsCommand(Command): description = "generate API documentation" user_options = [] def initialize_options(self): pass def finalize_options(self): pass def run(self): import os import pydoc todo = [] modlist = ['fgcp', 'tests'] for curmod in modlist: pydoc.writedoc(curmod) todo.append(curmod) for root, dirs, files in os.walk(curmod): for name in files: if name.startswith('__'): continue if not name.endswith('.py'): continue #modname = '%s.%s' % (curmod, name.replace('.py', '')) filepath = os.path.join(root, name) modname = filepath.replace('/', '.').replace('\\', '.').replace('.py', '') pydoc.writedoc(modname) todo.append(modname) import re # replace file:/// link with link to google code def clean_link(match): parts = match.group(1).split('/') file = parts.pop() dir = parts.pop() return '"http://code.google.com/p/fgcp-client-api/source/browse/%s/%s"' % (dir, file) p1 = re.compile('"(file:[^"]+)"') # replace c:\... file with local file def clean_file(match): name = match.group(1).split('\\').pop() return '>%s<' % name p2 = re.compile('>(\w:[^<]+)<') for modname in todo: filename = modname + '.html' if not os.path.exists(filename): continue print filename f = open(filename) lines = f.read() f.close() lines = p1.sub(clean_link, lines) lines = p2.sub(clean_file, lines) # write new file in docs f = open(os.path.join('docs', filename), 'w') f.write(lines) f.close() # get latest version of project pages self.get_project_pages('fgcp-client-api', ['ClientMethods', 'ResourceActions', 'APICommands', 'ClassDiagrams', 'TestServer', 'RelayServer'], modlist) def get_project_pages(self, project, wikilist, modlist): footerlinks = [] pages = {'index.html': 'http://code.google.com/p/%s/' % project} # add links to project pages for file in pages: footerlinks.append('<a href="%s">%s</a>' % (file, file.replace('.html',''))) wikipages = {} wikireplace = {} # define wiki pages + add links to them for wiki in wikilist: file = '%s.html' % wiki url = 'http://code.google.com/p/%s/wiki/%s' % (project, wiki) link = '/p/%s/wiki/%s' % (project, wiki) wikipages[file] = url wikireplace[link] = file footerlinks.append('<a href="%s">%s</a>' % (file, wiki)) # add links to module documentation for mod in modlist: footerlinks.append('<a href="%s">pydoc %s</a>' % ('%s.html' % mod, mod)) # build footer footer = '<p>Content: %s</p></body></html>' % '&nbsp;&nbsp;'.join(footerlinks) # get project pages for file in pages: self.get_html(file, pages[file], '<td id="wikicontent" class="psdescription">', '</td>', wikireplace, footer) # get wiki pages for file in wikipages: self.get_html(file, wikipages[file], '<div class="vt" id="wikimaincol">', '</div>', wikireplace, footer) def get_html(self, file, url, start_seq='<body>', end_seq='</body>', links={}, footer='<br /></body></html>'): print file import urllib2 f = urllib2.urlopen(url) lines = f.read() f.close() # remove start_seq m = lines.find(start_seq) if m > 0: m += len(start_seq) lines = lines[m:] # remove end_seq m = lines.find(end_seq) if m > 0: lines = lines[:m] lines += footer # replace title import re def add_title(match): title = match.group(1) title = re.sub('<a [^>]+></a>', '', title) return '<html><head><title>%s</title></head><body><h1>%s</h1>' % (title, title) lines = re.sub('<h1>(.+)</h1>', add_title, lines) # replace links for link in links: lines = lines.replace(link, links[link]) # write new file in docs import os f = open(os.path.join('docs', file), 'w') f.write(lines) f.close() class Pep8Command(Command): description = "run pep8 script" user_options = [] def initialize_options(self): pass def finalize_options(self): pass def run(self): import sys try: import pep8 pep8 except ImportError: print ('Missing "pep8" library. You can install it using pip: ' 'pip install pep8') sys.exit(1) import os import subprocess cwd = os.getcwd() retcode = subprocess.call(('pep8 --show-source --ignore=E501 --filename=*.py %s/fgcp/ %s/tests/ %s/fgcp_demo.py' % (cwd, cwd, cwd)).split(' ')) sys.exit(retcode) f = open('README.txt') long_description = f.read() f.close() setup( name='fgcp-client-api', description='Client API Library for the Fujitsu Global Cloud Platform (FGCP)', version='1.3.2', author='mikespub', author_email='fgcp@mikespub.net', packages=['fgcp'], license='Apache License 2.0', url='http://code.google.com/p/fgcp-client-api/', long_description=long_description, entry_points = { 'distutils.commands': [ 'docs = DocsCommand' ] }, cmdclass={ 'docs': DocsCommand, 'pep8': Pep8Command, }, classifiers=[ 'Topic :: Software Development :: Libraries :: Python Modules', 'Environment :: Console', 'Environment :: Web Environment', 'Development Status :: 4 - Beta', 'Intended Audience :: System Administrators', 'Intended Audience :: Developers', 'License :: OSI Approved :: Apache Software License', 'Operating System :: OS Independent', 'Programming Language :: Python', ] )
Python
#!/usr/bin/python # # Copyright (C) 2011 Michel Dalle # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ This is a really basic CGI server that allows you to test the really basic Relay CGI script, by specifying the following region in your scripts: region='relay=http://localhost:8000/cgi-bin/fgcp_relay.py' In order to use this CGI server for relay testing, you need to adapt the lines pem_file = '../client.pem' region = 'de' at the bottom of this script, and specify your own certificate and region there """ import CGIHTTPServer class FGCPRelayConfig: """The actual relay configuration is specified at startup""" key_file = 'client.pem' region = 'uk' FGCP_RELAY_CONFIG = FGCPRelayConfig() class FGCPRelayHTTPRequestHandler(CGIHTTPServer.CGIHTTPRequestHandler): """Override the default CGIHTTPRequestHandler to run the relay script here""" _relay = None def do_POST(self): """Version of do_POST() that runs the relay script in place""" if self.is_cgi(): #return self.run_cgi() return self.run_cgi_local() else: self.send_error(501, "Can only POST to CGI scripts") def send_head(self): """Version of send_head() that only supports CGI scripts""" if self.is_cgi(): #return self.run_cgi() return self.run_cgi_local() else: self.send_error(501, "Can only access CGI scripts") def is_cgi(self): """Version of is_cgi() that only supports the relay CGI script""" if self.path != '/cgi-bin/fgcp_relay.py': return False return CGIHTTPServer.CGIHTTPRequestHandler.is_cgi(self) def run_cgi_local(self): """Version of run_cgi() that runs the relay script in place""" env = {} env['REQUEST_METHOD'] = self.command if self.headers.typeheader is None: env['CONTENT_TYPE'] = self.headers.type else: env['CONTENT_TYPE'] = self.headers.typeheader length = self.headers.getheader('content-length') if length: env['CONTENT_LENGTH'] = length ua = self.headers.getheader('user-agent') if ua: env['HTTP_USER_AGENT'] = ua if self._relay is None: # initialize class variable with relay instance from fgcp_relay import FGCPRelayCGIScript FGCPRelayHTTPRequestHandler._relay = FGCPRelayCGIScript(FGCP_RELAY_CONFIG.key_file, FGCP_RELAY_CONFIG.region) self.log_message("Initialize relay with key_file '%s' and region '%s'" % (FGCP_RELAY_CONFIG.key_file, FGCP_RELAY_CONFIG.region)) try: # set filepointers and environment self._relay.set_fp(self.rfile, self.wfile, self.wfile) self._relay.set_environ(env) # run relay script self.send_response(200, "Script output follows") self._relay.run() except: self.send_response(501, "Script error follows") self.wfile.write('An error occured') self.log_message("Script exited with error") def run_relay_server(key_file, region): # initialize relay config FGCP_RELAY_CONFIG.key_file = key_file FGCP_RELAY_CONFIG.region = region # override default CGIHTTPRequestHandler CGIHTTPServer.test(HandlerClass=FGCPRelayHTTPRequestHandler) if __name__ == "__main__": import os.path import sys parent = os.path.dirname(__file__) sys.path.append(parent) sys.path.append(os.path.join(parent, 'cgi-bin')) print """ This is a really basic CGI server that allows you to test the really basic Relay CGI script, by specifying the following region in your scripts: region='relay=http://localhost:8000/cgi-bin/fgcp_relay.py' """ pem_file = '../client.pem' region = 'de' run_relay_server(pem_file, region)
Python
#!/usr/bin/python # # Copyright (C) 2012 Michel Dalle # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ Resource Actions on the Fujitsu Global Cloud Platform (FGCP) Example: [see tests/test_resource.py for more examples] # Connect with your client certificate to region 'uk' from fgcp.resource import FGCPVDataCenter vdc = FGCPVDataCenter('client.pem', 'uk') # Do typical actions on resources vsystem = vdc.get_vsystem('Python API Demo System') vsystem.show_status() for vserver in vsystem.vservers: result = vserver.backup(wait=True) ... """ import time from fgcp import FGCPError class FGCPResourceError(FGCPError): """ Exception class for FGCP Resource Errors """ def __init__(self, status, message, resource=None): self.status = status self.message = message self.resource = resource def __str__(self): return '\nStatus: %s\nMessage: %s\nResource: %s' % (self.status, self.message, repr(self.resource)) class FGCPElement(object): def __init__(self, **kwargs): # initialize object attributes, cfr. FGCPDesign().load() for key in kwargs.keys(): setattr(self, key, kwargs[key]) def __repr__(self): return '<%s>' % type(self).__name__ #========================================================================= def pformat(self, what, depth=0): prefix = ' ' * depth #if what is None: # return '%sNone' % prefix if isinstance(what, str): return "%s'%s'" % (prefix, what) CRLF = '\r\n' L = [] if isinstance(what, list): L.append('%s[' % prefix) for val in what: L.append(self.pformat(val, depth + 1) + ',') L.append('%s]' % prefix) return CRLF.join(L) # initialize object attributes, cfr. FGCPDesign().save() L.append('%s%s(' % (prefix, type(what).__name__)) depth += 1 prefix = ' ' * depth for key in what.__dict__: # TODO: skip _caller and _parent for output later ? if key == '_caller' or key == '_parent' or key == '_status': if isinstance(what.__dict__[key], FGCPResource): L.append("%s%s='%s'," % (prefix, key, repr(what.__dict__[key]))) elif isinstance(what.__dict__[key], str): L.append("%s%s='%s'," % (prefix, key, what.__dict__[key])) else: L.append('%s%s=%s,' % (prefix, key, what.__dict__[key])) # TODO: skip _proxy for output later ? elif key == '_proxy': #if what.__dict__[key] is not None: # L.append("%s%s='%s'," % (prefix, key, repr(what.__dict__[key]))) #else: # L.append('%s%s=None,' % (prefix, key)) pass # CHECKME: skip all the others, e.g. _get_handler from FW and SLB elif key.startswith('_'): pass elif isinstance(what.__dict__[key], FGCPElement): L.append('%s%s=' % (prefix, key)) L.append(self.pformat(what.__dict__[key], depth + 1) + ',') elif isinstance(what.__dict__[key], list): L.append('%s%s=[' % (prefix, key)) for val in what.__dict__[key]: L.append(self.pformat(val, depth + 1) + ',') L.append('%s],' % prefix) elif isinstance(what.__dict__[key], str): L.append("%s%s='%s'," % (prefix, key, what.__dict__[key])) elif isinstance(what.__dict__[key], int) or isinstance(what.__dict__[key], float): L.append("%s%s=%s," % (prefix, key, what.__dict__[key])) elif what.__dict__[key] is None: #L.append("%s%s=None," % (prefix, key)) pass else: L.append("%s%s='?%s?'," % (prefix, key, what.__dict__[key])) depth -= 1 prefix = ' ' * depth L.append('%s)' % prefix) return CRLF.join(L) def pprint(self): """ Show dump of the FGCP Element for development """ print self.pformat(self) #========================================================================= def reset_attr(self, what): if hasattr(self, what): setattr(self, what, None) class FGCPResponse(FGCPElement): """ FGCP Response """ _caller = None def __repr__(self): if self._caller is not None: return '<%s:%s>' % (type(self).__name__, repr(self._caller)) else: return '<%s:%s>' % (type(self).__name__, '') class FGCPResource(FGCPElement): """ Generic FGCP Resource """ _idname = None _parent = None _proxy = None #_actions = {} def __init__(self, **kwargs): # initialize object attributes, cfr. FGCPDesign().load() for key in kwargs.keys(): setattr(self, key, kwargs[key]) # CHECKME: special case for id=123 and/or parentid=12 ? if hasattr(self, 'id') and self._idname is not None: # CHECKME: set the _idname to the 'id' value if self._idname != 'id' and getattr(self, self._idname, None) is None: setattr(self, self._idname, getattr(self, 'id')) def __repr__(self): return '<%s:%s>' % (type(self).__name__, self.getid()) #========================================================================= def create(self, wait=None): return self.getid() def retrieve(self, refresh=None): return self def update(self): return """ def replace(self): return """ def destroy(self): return """ def status(self): return 'UNKNOWN' """ #def action(self, who=None, what=None, where=None, when=None, why=None, how=None): # pass #========================================================================= def check_status(self, in_state=[], out_state=[]): status = self.status() if status in out_state: # we're already in the expected outcome state for the action return status elif status in in_state: # we're still in the expected input state for the action return else: # we're in some unexpected state for the action raise FGCPResourceError('ILLEGAL_STATE', 'Invalid status %s' % status, self) def wait_for_status(self, in_state=[], out_state=[], timeout=900): start_time = time.time() stop_time = time.time() while stop_time < start_time + timeout: # wait 10 seconds before checking status again time.sleep(10) done = self.check_status(in_state, out_state) if done: # we're already in the expected outcome state for the action return done # we're still in the expected input state for the action stop_time = time.time() raise FGCPResourceError('TIMEOUT', 'Expected status %s not reached' % out_state, self) def show_output(self, text=''): # CHECKME: keep track of verbose ourselves - in all resource objects ??? if self._proxy is not None: if self._proxy.verbose > 0: print text #========================================================================= def getid(self): if self._idname is not None and getattr(self, self._idname, None) is not None: return getattr(self, self._idname) def getparentid(self): if self._parent is not None: if isinstance(self._parent, FGCPResource): return self._parent.getid() elif isinstance(self._parent, str): return self._parent def setparent(self, parent): self._parent = parent # CHECKME: set the proxy to the parent's proxy too if parent is not None and hasattr(parent, '_proxy'): self._proxy = parent._proxy def getproxy(self): if self._proxy is not None: # CHECKME: set the caller here for use in FGCPResponseParser !? self._proxy._caller = self return self._proxy def merge_attr(self, partial): # set missing parts of self with information from partial - do not overwrite for key in partial.__dict__: if key.startswith('_') and key != '_status': continue if getattr(self, key, None) is None: setattr(self, key, partial.__dict__[key]) #========================================================================= # convert *args and **kwargs from other method to dict def _args2dict(self, argslist=[], kwargsdict={}, allowed=None): tododict = {} if len(argslist) == 2: # CHECKME: we assume a key, val pair - cfr. attributeName, attributeValue etc. !? tododict[argslist[0]] = argslist[1] elif len(argslist) == 1: # CHECKME: we got an object, use its __dict__ if isinstance(argslist[0], FGCPResource): tododict = argslist[0].__dict__ # CHECKME: we got key, val pairs elif isinstance(argslist[0], dict): tododict = argslist[0] elif isinstance(argslist[0], list): # now what ? return argslist[0] else: # now what ? return argslist[0] if len(kwargsdict) > 0: tododict.update(kwargsdict) # TODO: sanitize dict by removing _* + the _idname, and diff the rest with current values ? if len(allowed) > 0 and len(tododict) > 0: newdict = {} for key in allowed: if key in tododict: newdict[key] = tododict[key] tododict = newdict return tododict """ # CHECKME: no longer needed since we do it in FGCPResponseParser() based on conn._caller def _reparent(self, child=None, parent=None): if child is None: return child elif isinstance(child, str): return child elif isinstance(child, list): new_child = [] for item in child: new_child.append(self._reparent(item, parent)) return new_child elif isinstance(child, dict): new_child = {} for key, val in child: new_child[key] = self._reparent(val, parent) return new_child elif isinstance(child, FGCPResponse): child._caller = parent for key, val in child.__dict__: if key == '_caller': continue # CHECKME: use caller as parent here setattr(child, key, self._reparent(val, parent)) return child elif isinstance(child, FGCPResource): child._parent = parent for key, val in child.__dict__: if key == '_parent' or key == '_proxy': continue # CHECKME: use child as parent here setattr(child, key, self._reparent(val, child)) return child else: return child """ class FGCPVDataCenter(FGCPResource): """ FGCP VDataCenter """ _idname = 'config' config = None vsystems = None publicips = None addressranges = None vsysdescriptors = None diskimages = None servertypes = None def __init__(self, key_file=None, region=None, verbose=0, debug=0): """ Use the same PEM file for SSL client certificate and RSA key signature Note: to convert your .p12 or .pfx file to unencrypted PEM format, you can use the following 'openssl' command: openssl pkcs12 -in UserCert.p12 -out client.pem -nodes """ # initialize proxy if necessary if key_file is not None and region is not None: self.config = '%s:%s' % (region, key_file) #from fgcp.client import FGCPClient #self._proxy = FGCPClient(key_file, region, verbose, debug) from fgcp.command import FGCPCommand self._proxy = FGCPCommand(key_file, region, verbose, debug) #========================================================================= def status(self): return 'Connection: %s\nResource: %s' % (repr(self._proxy), repr(self)) #========================================================================= def list_vsystems(self): if getattr(self, 'vsystems', None) is None: setattr(self, 'vsystems', self.getproxy().ListVSYS()) return getattr(self, 'vsystems') def get_vsystem(self, vsysName): # support resource, name or id if isinstance(vsysName, FGCPVSystem): return vsysName.retrieve() vsystems = self.list_vsystems() for vsystem in vsystems: if vsysName == vsystem.vsysName: # CHECKME: get detailed configuration now ? #vsystem.retrieve() return vsystem elif vsysName == vsystem.vsysId: # CHECKME: get detailed configuration now ? #vsystem.retrieve() return vsystem raise FGCPResourceError('ILLEGAL_VSYSTEM', 'Invalid vsysName %s' % vsysName, self) def create_vsystem(self, vsysName, vsysdescriptor, wait=None): vsysdescriptor = self.get_vsysdescriptor(vsysdescriptor) # let the vsysdescriptor handle it return vsysdescriptor.create_vsystem(vsysName, wait) def destroy_vsystem(self, vsysName, wait=None): vsystem = self.get_vsystem(vsysName) if wait: # make sure the vsystem is stopped first result = vsystem.stop(wait) # make sure the vsystem is shutdown first result = vsystem.shutdown(wait) # let the vsystem handle it return vsystem.destroy() #========================================================================= def list_publicips(self): if getattr(self, 'publicips', None) is None: setattr(self, 'publicips', self.getproxy().ListPublicIP()) return getattr(self, 'publicips') def get_publicip(self, publicipAddress): # support resource or address (=id) if isinstance(publicipAddress, FGCPPublicIP): return publicipAddress.retrieve() publicips = self.list_publicips() for publicip in publicips: if publicipAddress == publicip.address: return publicip.retrieve() raise FGCPResourceError('ILLEGAL_ADDRESS', 'Invalid publicipAddress %s' % publicipAddress, self) #========================================================================= def list_addressranges(self): if getattr(self, 'addressranges', None) is None: setattr(self, 'addressranges', self.getproxy().GetAddressRange()) return getattr(self, 'addressranges') def create_addresspool(self, pipFrom=None, pipTo=None): return self.getproxy().CreateAddressPool(pipFrom, pipTo) def add_addressrange(self, pipFrom, pipTo): return self.getproxy().AddAddressRange(pipFrom, pipTo) def delete_addressrange(self, pipFrom, pipTo): return self.getproxy().DeleteAddressRange(pipFrom, pipTo) #========================================================================= def list_vsysdescriptors(self): if getattr(self, 'vsysdescriptors', None) is None: setattr(self, 'vsysdescriptors', self.getproxy().ListVSYSDescriptor()) return getattr(self, 'vsysdescriptors') def get_vsysdescriptor(self, vsysdescriptorName): # support resource, name or id if isinstance(vsysdescriptorName, FGCPVSysDescriptor): return vsysdescriptorName.retrieve() vsysdescriptors = self.list_vsysdescriptors() for vsysdescriptor in vsysdescriptors: if vsysdescriptorName == vsysdescriptor.vsysdescriptorName: return vsysdescriptor.retrieve() elif vsysdescriptorName == vsysdescriptor.vsysdescriptorId: return vsysdescriptor.retrieve() raise FGCPResourceError('ILLEGAL_VSYSDESCRIPTOR', 'Invalid vsysdescriptorName %s' % vsysdescriptorName, self) #========================================================================= def list_diskimages(self, vsysdescriptor=None, category='GENERAL'): # CHECKME: reversed order of arguments here # get all diskimages if vsysdescriptor is None: if getattr(self, 'diskimages', None) is None: setattr(self, 'diskimages', self.getproxy().ListDiskImage()) return getattr(self, 'diskimages') # get specific diskimages for this vsysdescriptor vsysdescriptor = self.get_vsysdescriptor(vsysdescriptor) # let the vsysdescriptor handle it return vsysdescriptor.list_diskimages(category) def get_diskimage(self, diskimageName): # support resource, name or id if isinstance(diskimageName, FGCPDiskImage): return diskimageName.retrieve() diskimages = self.list_diskimages() for diskimage in diskimages: if diskimageName == diskimage.diskimageName: return diskimage.retrieve() elif diskimageName == diskimage.diskimageId: return diskimage.retrieve() raise FGCPResourceError('ILLEGAL_DISKIMAGE', 'Invalid diskimageName %s' % diskimageName, self) #========================================================================= def list_servertypes(self, diskimage=None): # CHECKME: all diskimages support the same servertypes at the moment !? if getattr(self, 'servertypes', None) is not None: return getattr(self, 'servertypes') # pick the first diskimage that's available if diskimage is None: diskimage = self.list_diskimages()[0] else: diskimage = self.get_diskimage(diskimage) # let the diskimage handle it setattr(self, 'servertypes', diskimage.list_servertypes()) return getattr(self, 'servertypes') def get_servertype(self, servertypeName): # support resource or name (=id) if isinstance(servertypeName, FGCPServerType): return servertypeName.retrieve() servertypes = self.list_servertypes() for servertype in servertypes: if servertypeName == servertype.name: return servertype.retrieve() raise FGCPResourceError('ILLEGAL_SERVERTYPE', 'Invalid servertypeName %s' % servertypeName, self) #========================================================================= def get_vsystem_usage(self, vsysNames=None): if vsysNames is None: return self.getproxy().GetSystemUsage() vsysIds = [] if isinstance(vsysNames, str): vsysNames = [vsysNames] for vsysName in vsysNames: vsystem = self.get_vsystem(vsysName) vsysIds.append(vsystem.vsysId) if len(vsysIds) > 0: vsysIds = ' '.join(vsysIds) else: vsysIds = None return self.getproxy().GetSystemUsage(vsysIds) def show_vsystem_usage(self, vsysNames=None): date, usagelist = self.get_vsystem_usage(vsysNames) print 'Usage Report on %s' % date for usageinfo in usagelist: #entry.pprint() print print 'VSystem: %s [%s]' % (usageinfo.vsysName, usageinfo.vsysId) for product in usageinfo.products: print ' %s:\t%s %s' % (product.productName, product.usedPoints, product.unitName) def show_vsystem_status(self, sep='\t'): for vsystem in self.list_vsystems(): vsystem.show_status(sep) #========================================================================= def get_information(self, all=None, timeZone=None, countryCode=None): return self.getproxy().GetInformation(all, timeZone, countryCode) def get_eventlog(self, all=None, timeZone=None, countryCode=None): return self.getproxy().GetEventLog(all, timeZone, countryCode) #========================================================================= def get_vsystem_design(self, vsystem=None): # get design from existing vsystem if specified if vsystem is not None: vsystem = self.get_vsystem(vsystem) from fgcp.design import FGCPDesign design = FGCPDesign(vsystem=vsystem) # set the parent of the design to this vdatacenter ! design.setparent(self) return design class FGCPVSystem(FGCPResource): _idname = 'vsysId' vsysId = None vsysName = None description = None baseDescriptor = None creator = None cloudCategory = None vservers = None vdisks = None vnets = None publicips = None firewalls = None loadbalancers = None def create(self): # CHECKME: do we want this too ? pass def retrieve(self, refresh=None): # CHECKME: retrieve inventory here ? return self.get_inventory(refresh) def update(self, *args, **kwargs): self.show_output('Updating VSystem %s' % self.vsysName) allowed = ['vsysName', 'cloudCategory'] # convert arguments to dict tododict = self._args2dict(args, kwargs, allowed) # CHECKME: what if we updated the object attributes directly ? result = None # CHECKME: different methods for different fields if 'vsysName' in tododict and tododict['vsysName'] != self.vsysName: result = self.getproxy().UpdateVSYSAttribute(self.getid(), 'vsysName', tododict['vsysName']) if 'cloudCategory' in tododict and tododict['cloudCategory'] != self.cloudCategory: result = self.getproxy().UpdateVSYSConfiguration(self.getid(), 'CLOUD_CATEGORY', tododict['cloudCategory']) self.show_output('Updated VSystem %s' % self.vsysName) return result def destroy(self): self.show_output('Destroying VSystem %s' % self.vsysName) result = self.getproxy().DestroyVSYS(self.getid()) # CHECKME: invalidate list of vsystems in VDataCenter if isinstance(self._parent, FGCPVDataCenter): self._parent.reset_attr('vsystems') self.show_output('Destroyed VSystem %s' % self.vsysName) return result def status(self): status = self.getproxy().GetVSYSStatus(self.getid()) setattr(self, 'vsysStatus', status) return status def boot(self, wait=None): self.show_output('Booting VSystem %s' % self.vsysName) # check if the vsystem is ready todo = self.check_status(['NORMAL'], ['DEPLOYING', 'RECONFIG_ING']) if todo and wait: # wait for the vsystem to be ready result = self.wait_for_status(['DEPLOYING', 'RECONFIG_ING'], ['NORMAL']) elif todo: # we're not ready and won't wait return todo # get system inventory if necessary self.get_inventory() # start all firewalls for firewall in self.firewalls: firewall.start(wait) # attach publicip - cfr. sequence3 in java sdk for publicip in self.publicips: publicip.attach(wait) self.show_output('Booted VSystem %s' % self.vsysName) return def start(self, wait=None): self.show_output('Starting VSystem %s' % self.vsysName) # check if the vsystem is ready self.boot(wait) # start all vservers for vserver in self.vservers: vserver.start(wait) # start all loadbalancers for loadbalancer in self.loadbalancers: loadbalancer.start(wait) self.show_output('Started VSystem %s' % self.vsysName) return def stop(self, wait=None): self.show_output('Stopping VSystem %s' % self.vsysName) # check if the vsystem is ready todo = self.check_status(['NORMAL'], ['DEPLOYING', 'RECONFIG_ING']) if todo and wait: # wait for the vsystem to be ready result = self.wait_for_status(['DEPLOYING', 'RECONFIG_ING'], ['NORMAL']) elif todo: # we're not ready and won't wait return todo # get system inventory if necessary self.get_inventory() # stop all loadbalancers for loadbalancer in self.loadbalancers: loadbalancer.stop(wait) # stop all vservers for vserver in self.vservers: vserver.stop(wait) self.show_output('Stopped VSystem %s' % self.vsysName) return def shutdown(self, wait=None): self.show_output('Shutting down VSystem %s' % self.vsysName) # detach publicip - cfr. sequence3 in java sdk for publicip in self.publicips: publicip.detach(wait) # stop all firewalls for firewall in self.firewalls: firewall.stop(wait) self.show_output('Shut down VSystem %s' % self.vsysName) return #========================================================================= def list_vservers(self): if getattr(self, 'vservers', None) is None: # FIXME: remove firewalls and loadbalancers here too !? setattr(self, 'vservers', self.getproxy().ListVServer(self.getid())) return getattr(self, 'vservers') def get_vserver(self, vserverName): # support resource, name or id if isinstance(vserverName, FGCPVServer): return vserverName.retrieve() vservers = self.list_vservers() for vserver in vservers: if vserverName == vserver.vserverName: return vserver.retrieve() elif vserverName == vserver.vserverId: return vserver.retrieve() raise FGCPResourceError('ILLEGAL_VSERVER', 'Invalid vserverName %s' % vserverName, self) def create_vserver(self, vserverName, servertype, diskimage, vnet, wait=None): # ask the parent VDataCenter to get the right servertype and diskimage servertype = self._parent.get_servertype(servertype) diskimage = self._parent.get_diskimage(diskimage) # get the right vnet ourselves vnet = self.get_vnet(vnet) # make a new vserver with the right attributes - vnet returns a string, so no vnet.getid() needed (for now ?) vserver = FGCPVServer(vserverName=vserverName, vserverType=servertype.getid(), diskimageId=diskimage.getid(), networkId=vnet) # set the parent of the vserver to this vsystem ! vserver.setparent(self) # and now create it :-) return vserver.create(wait) def destroy_vserver(self, vserver, wait=None): vserver = self.get_vserver(vserver) return vserver.destroy(wait) def start_vserver(self, vserver, wait=None): vserver = self.get_vserver(vserver) return vserver.start(wait) def stop_vserver(self, vserver, wait=None, force=None): vserver = self.get_vserver(vserver) return vserver.stop(wait) def reboot_vserver(self, vserver, wait=None, force=None): vserver = self.get_vserver(vserver) return vserver.reboot(wait) #========================================================================= def list_vdisks(self): if getattr(self, 'vdisks', None) is None: setattr(self, 'vdisks', self.getproxy().ListVDisk(self.getid())) return getattr(self, 'vdisks') def get_vdisk(self, vdiskName): # support resource, name or id if isinstance(vdiskName, FGCPVDisk): return vdiskName.retrieve() vdisks = self.list_vdisks() for vdisk in vdisks: if vdiskName == vdisk.vdiskName: return vdisk.retrieve() elif vdiskName == vdisk.vdiskId: return vdisk.retrieve() raise FGCPResourceError('ILLEGAL_VDISK', 'Invalid vdiskName %s' % vdiskName, self) def create_vdisk(self, vdiskName, size, wait=None): # make a new vdisk with the right attributes - note: size is in GB vdisk = FGCPVDisk(vdiskName=vdiskName, size=size) # set the parent of the vdisk to this vsystem ! vdisk.setparent(self) # and now create it :-) return vdisk.create(wait) def destroy_vdisk(self, vdisk, wait=None): vdisk = self.get_vdisk(vdisk) return vdisk.destroy(wait) def attach_vdisk(self, vdisk, vserver, wait=None): vdisk = self.get_vdisk(vdisk) vserver = self.get_vserver(vserver) return vdisk.attach(vserver, wait) def detach_vdisk(self, vdisk, vserver, wait=None): vdisk = self.get_vdisk(vdisk) vserver = self.get_vserver(vserver) return vdisk.detach(vserver, wait) #========================================================================= def list_firewalls(self): if getattr(self, 'firewalls', None) is None: setattr(self, 'firewalls', self.getproxy().ListEFM(self.getid(), "FW")) return getattr(self, 'firewalls') def get_firewall(self, efmName): # support resource, name or id if isinstance(efmName, FGCPFirewall): return efmName.retrieve() firewalls = self.list_firewalls() for firewall in firewalls: if efmName == firewall.efmName: return firewall.retrieve() elif efmName == firewall.efmId: return firewall.retrieve() raise FGCPResourceError('ILLEGAL_FIREWALL', 'Invalid efmName %s' % efmName, self) #========================================================================= def list_loadbalancers(self): if getattr(self, 'loadbalancers', None) is None: setattr(self, 'loadbalancers', self.getproxy().ListEFM(self.getid(), "SLB")) return getattr(self, 'loadbalancers') def get_loadbalancer(self, efmName): # support resource, name or id if isinstance(efmName, FGCPLoadBalancer): return efmName.retrieve() loadbalancers = self.list_loadbalancers() for loadbalancer in loadbalancers: if efmName == loadbalancer.efmName: return loadbalancer.retrieve() elif efmName == loadbalancer.efmId: return loadbalancer.retrieve() raise FGCPResourceError('ILLEGAL_LOADBALANCER', 'Invalid efmName %s' % efmName, self) def create_loadbalancer(self, efmName, vnet, wait=None): # get the right vnet ourselves vnet = self.get_vnet(vnet) # make a new loadbalancer with the right attributes - vnet returns a string, so no vnet.getid() needed (for now ?) loadbalancer = FGCPLoadBalancer(efmName=efmName, networkId=vnet) # set the parent of the loadbalancer to this vsystem ! loadbalancer.setparent(self) # and now create it :-) return loadbalancer.create(wait) #========================================================================= def list_vnets(self): if getattr(self, 'vnets', None) is None: self.retrieve() return getattr(self, 'vnets') def get_vnet(self, vnet): # support vnet vnets = self.list_vnets() # find exact match first - this is a string if vnet in vnets: return vnet # find matching end if we used DMZ, SECURE1, SECURE2 here if len(vnet) < 8: for networkId in vnets: if networkId.endswith('-%s' % vnet): return networkId raise FGCPResourceError('ILLEGAL_VNET', 'Invalid vnet %s' % vnet, self) def get_console_url(self, vnet): vnet = self.get_vnet(vnet) return self.getproxy().StandByConsole(self.getid(), vnet) #========================================================================= def list_publicips(self): if getattr(self, 'publicips', None) is None: setattr(self, 'publicips', self.getproxy().ListPublicIP(self.getid())) return getattr(self, 'publicips') def get_publicip(self, publicipAddress): # support resource or address (=id) if isinstance(publicipAddress, FGCPPublicIP): return publicipAddress.retrieve() publicips = self.list_publicips() for publicip in publicips: if publicipAddress == publicip.address: return publicip.retrieve() raise FGCPResourceError('ILLEGAL_ADDRESS', 'Invalid publicipAddress %s' % publicipAddress, self) def allocate_publicip(self, wait=None): self.show_output('Allocating PublicIP to VSystem %s' % self.vsysName) old_publicips = self.list_publicips() if len(old_publicips) < 1: old_publicips = [] result = self.getproxy().AllocatePublicIP(self.getid()) # CHECKME: invalidate list of publicips self.reset_attr('publicips') if wait: # CHECKME: we need to wait a bit before retrieving the new list ! self.show_output('Please wait for allocation...') time.sleep(30) # update list of publicips new_publicips = self.list_publicips() if len(new_publicips) > len(old_publicips): # CHECKME: will this work on objects ? #diff_publicips = new_publicips.difference(old_publicips) old_ips = [] for publicip in old_publicips: old_ips.append(publicip.address) for publicip in new_publicips: if publicip.address in old_ips: continue # wait until publicip deploying is done result = publicip.wait_for_status(['DEPLOYING'], ['DETACHED', 'ATTACHED']) self.show_output('Allocated PublicIP %s to VSystem %s' % (publicip.address, self.vsysName)) return result raise FGCPResourceError('TIMEOUT', 'Unable to retrieve PublicIP for VSystem %s' % self.vsysName, self) return result #========================================================================= def get_inventory(self, refresh=None): # CHECKME: if we already have the firewall information, we already retrieved the configuration if not refresh and getattr(self, 'firewalls', None) is not None: return self # get configuration for this vsystem vsysconfig = self.getproxy().GetVSYSConfiguration(self.getid()) # CHECKME: copy configuration to self for key in vsysconfig.__dict__: if key.startswith('_'): continue setattr(self, key, vsysconfig.__dict__[key]) seenId = {} # get firewalls self.list_firewalls() for firewall in self.firewalls: seenId[firewall.efmId] = 1 # get loadbalancers self.list_loadbalancers() for loadbalancer in self.loadbalancers: seenId[loadbalancer.efmId] = 1 # CHECKME: remove firewalls and loadbalancers from vservers list todo = [] for vserver in self.vservers: # skip servers we've already seen, i.e. firewalls and loadbalancers if vserver.vserverId in seenId: continue todo.append(vserver) setattr(self, 'vservers', todo) if getattr(self, 'vdisks', None) is None: setattr(self, 'vdisks', []) if getattr(self, 'publicips', None) is None: setattr(self, 'publicips', []) return self def get_status(self, sep='\t'): self.show_output('Status Overview for VSystem %s' % self.vsysName) # get system inventory if necessary self.get_inventory() status = self.status() self.show_output(sep.join(['VSystem', self.vsysName, status])) # get status of public ips for publicip in self.publicips: status = publicip.status() self.show_output(sep.join(['PublicIP', publicip.address, status])) # get status of firewalls for firewall in self.firewalls: status = firewall.status() self.show_output(sep.join(['Firewall', firewall.efmName, status])) # get status of loadbalancers for loadbalancer in self.loadbalancers: status = loadbalancer.status() self.show_output(sep.join(['LoadBalancer', loadbalancer.efmName, loadbalancer.slbVip, status])) # get status of vservers (excl. firewalls and loadbalancers) seenId = {} for vserver in self.vservers: status = vserver.status() self.show_output(sep.join(['VServer', vserver.vserverName, vserver.vnics[0].privateIp, status])) # get status of attached disks for vdisk in vserver.vdisks: status = vdisk.status() self.show_output(sep.join(['', 'VDisk', vdisk.vdiskName, status])) seenId[vdisk.vdiskId] = 1 # get status of unattached disks todo = [] for vdisk in self.vdisks: # skip disks we've already seen, i.e. attached to a server if vdisk.vdiskId in seenId: continue todo.append(vdisk.vdiskId) if len(todo) > 0: self.show_output('Unattached Disks') for vdisk in self.vdisks: # skip disks we've already seen, i.e. attached to a server if vdisk.vdiskId in seenId: continue status = vdisk.status() self.show_output(sep.join(['', 'VDisk', vdisk.vdiskName, status])) seenId[vdisk.vdiskId] = 1 self.show_output('.') return self def show_status(self, sep='\t'): # set output to 1, i.e. don't show the status in the API command old_verbose = self._proxy.set_verbose(1) # get system status self.get_status(sep) # reset output self._proxy.set_verbose(old_verbose) #========================================================================= def register_vsysdescriptor(self, name, description, keyword): return self.getproxy().RegisterPrivateVSYSDescriptor(self.getid(), name, description, keyword, self.vservers) def get_usage(self): return self.getproxy().GetSystemUsage(self.getid()) class FGCPVServer(FGCPResource): _idname = 'vserverId' vserverId = None vserverName = None vserverType = None diskimageId = None creator = None vdisks = None vnics = None image = None backups = None def create(self, wait=None): # CHECKME: simplify vnics[0].getid() issue on create by allowing networkId if getattr(self, 'networkId') is None and getattr(self, 'vnics', None) is not None: setattr(self, 'networkId', self.vnics[0].getid()) self.show_output('Creating VServer %s' % self.vserverName) vserverId = self.getproxy().CreateVServer(self.getparentid(), self.vserverName, self.vserverType, self.diskimageId, self.networkId) # set the vserverId here too setattr(self, 'vserverId', vserverId) # CHECKME: invalidate list of vservers in VSystem if isinstance(self._parent, FGCPVSystem): self._parent.reset_attr('vservers') if wait: # wait for the vserver to be ready self.wait_for_status(['DEPLOYING'], ['STOPPED']) self.show_output('Created VServer %s' % self.vserverName) return vserverId def retrieve(self, refresh=None): # CHECKME: retrieve configuration here ? return self.get_configuration(refresh) def update(self, *args, **kwargs): self.show_output('Updating VServer %s' % self.vserverName) allowed = ['vserverName', 'vserverType'] # convert arguments to dict tododict = self._args2dict(args, kwargs, allowed) # CHECKME: what if we updated the object attributes directly ? result = None for key in tododict: if tododict[key] != getattr(self, key, None): result = self.getproxy().UpdateVServerAttribute(self.getparentid(), self.getid(), key, tododict[key]) self.show_output('Updated VServer %s' % self.vserverName) return result def destroy(self, wait=None): self.show_output('Destroying VServer %s' % self.vserverName) # make sure the server is stopped first result = self.stop(wait) # now destroy the server result = self.getproxy().DestroyVServer(self.getparentid(), self.getid()) # CHECKME: invalidate list of vservers in VSystem if isinstance(self._parent, FGCPVSystem): self._parent.reset_attr('vservers') if wait: # CHECKME: we won't wait for it to be gone here self.show_output('Destroyed VServer %s' % self.vserverName) return result def status(self): status = self.getproxy().GetVServerStatus(self.getparentid(), self.getid()) setattr(self, 'vserverStatus', status) return status def start(self, wait=None): self.show_output('Starting VServer %s' % self.vserverName) done = self.check_status(['STOPPED', 'UNEXPECTED_STOP'], ['RUNNING', 'STARTING']) if done: return done result = self.getproxy().StartVServer(self.getparentid(), self.getid()) if wait: result = self.wait_for_status(['STARTING'], ['RUNNING']) self.show_output('Started VServer %s' % self.vserverName) return result def stop(self, wait=None, force=None): self.show_output('Stopping VServer %s' % self.vserverName) done = self.check_status(['RUNNING'], ['STOPPED', 'UNEXPECTED_STOP', 'STOPPING']) if done: return done result = self.getproxy().StopVServer(self.getparentid(), self.getid(), force) if wait: result = self.wait_for_status(['STOPPING'], ['STOPPED', 'UNEXPECTED_STOP']) self.show_output('Stopped VServer %s' % self.vserverName) return result def reboot(self, wait=None, force=None): result = self.stop(wait, force) result = self.start(wait) return result #========================================================================= def get_configuration(self, refresh=None): # CHECKME: if we already have the vnics information, we already retrieved the configuration if not refresh and getattr(self, 'vnics', None) is not None: return self # get configuration for this vserver config = self.getproxy().GetVServerConfiguration(self.getparentid(), self.getid()) # CHECKME: copy configuration to self for key in config.__dict__: if key.startswith('_'): continue setattr(self, key, config.__dict__[key]) return self def get_password(self): return self.getproxy().GetVServerInitialPassword(self.getparentid(), self.getid()) #========================================================================= def list_vdisks(self): if getattr(self, 'vdisks', None) is None: self.retrieve() return getattr(self, 'vdisks') def get_vdisk(self, vdisk): # let the VSystem get the right disk here, since it might not be attached to this VServer return self._parent.get_vdisk(vdisk) def attach_vdisk(self, vdisk, wait=None): vdisk = self.get_vdisk(vdisk) return vdisk.attach(self, wait) def detach_vdisk(self, vdisk, wait=None): vdisk = self.get_vdisk(vdisk) return vdisk.detach(self, wait) #========================================================================= def list_backups(self, timeZone=None, countryCode=None): if timeZone or countryCode: # Note: the system disk has the same id as the vserver return self.getproxy().ListVDiskBackup(self.getparentid(), self.getid(), timeZone, countryCode) if getattr(self, 'backups', None) is None: # Note: the system disk has the same id as the vserver setattr(self, 'backups', self.getproxy().ListVDiskBackup(self.getparentid(), self.getid(), timeZone, countryCode)) return getattr(self, 'backups') def backup(self, wait=None): self.show_output('Start Backup VServer %s' % self.vserverName) if wait: result = self.stop(wait) # get vserver configuration self.get_configuration() # the system disk has the same id as the vserver vdisk = self.getproxy().GetVDiskAttributes(self.getparentid(), self.getid()) # backup the system disk result = vdisk.backup(wait) # CHECKME: add other disks if necessary ? #for vdisk in self.vdisks: # result = vdisk.backup(wait) if wait: # CHECKME: start vserver again ? #result = self.start(wait) self.show_output('Finish Backup VServer %s' % self.vserverName) return result def restore(self, backup, wait=None): self.show_output('Start Restore %s for VServer %s' % (backup, self.vserverName)) if wait: result = self.stop(wait) # get vserver configuration self.get_configuration() # the system disk has the same id as the vserver vdisk = self.getproxy().GetVDiskAttributes(self.getparentid(), self.getid()) # backup the system disk result = vdisk.restore(backup, wait) # CHECKME: add other disks if necessary ? #for vdisk in self.vdisks: # result = vdisk.backup(wait) if wait: # CHECKME: start vserver again ? #result = self.start(wait) self.show_output('Finish Restore VServer %s' % self.vserverName) return result def cleanup_backups(self, max_num=100, max_age=None): # get vserver configuration self.get_configuration() # the system disk has the same id as the vserver vdisk = self.getproxy().GetVDiskAttributes(self.getparentid(), self.getid()) # let the system disk handle the cleanup return vdisk.cleanup_backups(max_num, max_age) #========================================================================= def list_vnics(self): if getattr(self, 'vnics', None) is None: self.retrieve() return getattr(self, 'vnics') #========================================================================= def register_diskimage(self, name, description): return self.getproxy().RegisterPrivateDiskImage(self.getid(), name, description) #========================================================================= def get_performance(self, interval='hour', dataType=None): return self.getproxy().GetPerformanceInformation(self.getparentid(), self.getid(), interval, dataType) class FGCPVServerImage(FGCPResource): _idname = 'id' id = None cpuBit = None numOfMaxDisk = None numOfMaxNic = None serverApplication = None serverCategory = None softwares = None sysvolSize = None def list_softwares(self): if getattr(self, 'softwares', None) is None: # CHECKME: initialize to None or list here ? setattr(self, 'softwares', []) return getattr(self, 'softwares') class FGCPVDisk(FGCPResource): _idname = 'vdiskId' vdiskId = None vdiskName = None size = None attachedTo = None creator = None backups = None def getparentid(self): # CHECKME: the parent of a vdisk may be a vserver or a vsystem, so we need to override this if self._parent is not None: if isinstance(self._parent, FGCPVServer): # we get the vserver's parent's id here, i.e. the vsystem id return self._parent.getparentid() elif isinstance(self._parent, FGCPResource): # we get the parent's id as usual return self._parent.getid() elif isinstance(self._parent, str): return self._parent def create(self, wait=None): self.show_output('Creating VDisk %s (%s GB)' % (self.vdiskName, self.size)) vdiskId = self.getproxy().CreateVDisk(self.getparentid(), self.vdiskName, self.size) # set the vdiskId here too setattr(self, 'vdiskId', vdiskId) # CHECKME: invalidate list of vdisks in VSystem if isinstance(self._parent, FGCPVSystem): self._parent.reset_attr('vdisks') if wait: # wait for the vdisk to be ready self.wait_for_status(['DEPLOYING'], ['NORMAL']) self.show_output('Created VDisk %s' % self.vdiskName) return vdiskId def retrieve(self, refresh=None): return self def update(self, *args, **kwargs): self.show_output('Updating VDisk %s' % self.vdiskName) allowed = ['vdiskName'] # convert arguments to dict tododict = self._args2dict(args, kwargs, allowed) # CHECKME: what if we updated the object attributes directly ? result = None for key in tododict: if tododict[key] != getattr(self, key, None): result = self.getproxy().UpdateVDiskAttribute(self.getparentid(), self.getid(), key, tododict[key]) self.show_output('Updated VDisk %s' % self.vdiskName) return result def destroy(self): self.show_output('Destroying VDisk %s (%s GB)' % (self.vdiskName, self.size)) vdiskId = self.getproxy().DestroyVDisk(self.getparentid(), self.vdiskId) # CHECKME: invalidate list of vdisks in VSystem if isinstance(self._parent, FGCPVSystem): self._parent.reset_attr('vdisks') self.show_output('Destroyed VDisk %s' % self.vdiskName) return def status(self): status = self.getproxy().GetVDiskStatus(self.getparentid(), self.getid()) setattr(self, 'vdiskStatus', status) return status def attach(self, vserver, wait=None): self.show_output('Attaching VDisk %s to VServer %s' % (self.vdiskName, vserver.vserverName)) done = self.check_status(['NORMAL']) result = self.getproxy().AttachVDisk(self.getparentid(), vserver.getid(), self.getid()) if wait: result = self.wait_for_status(['ATTACHING'], ['NORMAL']) self.show_output('Attached VDisk %s to VServer %s' % (self.vdiskName, vserver.vserverName)) return result def detach(self, vserver, wait=None): self.show_output('Detaching VDisk %s from VServer %s' % (self.vdiskName, vserver.vserverName)) done = self.check_status(['NORMAL']) result = self.getproxy().DetachVDisk(self.getparentid(), vserver.getid(), self.getid()) if wait: result = self.wait_for_status(['DETACHING'], ['NORMAL']) self.show_output('Detached VDisk %s from VServer %s' % (self.vdiskName, vserver.vserverName)) return result #========================================================================= def list_backups(self, timeZone=None, countryCode=None): if timeZone or countryCode: return self.getproxy().ListVDiskBackup(self.getparentid(), self.getid(), timeZone, countryCode) if getattr(self, 'backups', None) is None: setattr(self, 'backups', self.getproxy().ListVDiskBackup(self.getparentid(), self.getid(), timeZone, countryCode)) return getattr(self, 'backups') def get_backup(self, backup): # support resource or id if isinstance(backup, FGCPBackup): return backup.retrieve() backups = self.list_backups() for entry in backups: if backup == entry.backupId: return entry.retrieve() raise FGCPResourceError('ILLEGAL_BACKUP', 'Invalid backup %s' % backup, self) def backup(self, wait=None): self.show_output('Start Backup VDisk %s' % self.vdiskName) # check current status done = self.check_status(['NORMAL', 'STOPPED', 'UNEXPECTED_STOP'], ['BACKUP_ING']) if not done: # backup vdisk now result = self.getproxy().BackupVDisk(self.getparentid(), self.getid()) else: result = done if wait: # wait for the backup to be done result = self.wait_for_status(['BACKUP_ING'], ['STOPPED', 'NORMAL']) self.show_output('Finish Backup VDisk %s' % self.vdiskName) return result def restore(self, backup, wait=None): backup = self.get_backup(backup) self.show_output('Start Restore %s for VDisk %s' % (backup, self.vdiskName)) # check current status done = self.check_status(['NORMAL', 'STOPPED', 'UNEXPECTED_STOP'], ['RESTORING']) if not done: # restore vdisk now - note that we don't need to specify the vdiskId here if isinstance(backup, FGCPResource): result = self.getproxy().RestoreVDisk(self.getparentid(), backup.getid()) else: result = self.getproxy().RestoreVDisk(self.getparentid(), backup) else: result = done if wait: # wait for the backup to be done result = self.wait_for_status(['RESTORING'], ['STOPPED', 'NORMAL']) self.show_output('Finish Restore VDisk %s' % self.vdiskName) return result def cleanup_backups(self, max_num=100, max_age=None): self.show_output('TODO: Start cleaning backups for VDisk %s' % self.vdiskName) self.list_backups() if len(self.backups) < 1: return # Sort list of objects: http://stackoverflow.com/questions/2338531/python-sorting-a-list-of-objects from operator import attrgetter self.backups.sort(key=attrgetter('timeval'), reverse=True) # show last backup oldest = float(self.backups[-1].timeval) # ... # TODO: find matching backups # TODO: destroy matching backups #for backup in todo: # backup.pprint() # backup.destroy() self.show_output('TODO: Stop cleaning backups for VDisk %s' % self.vdiskName) class FGCPBackup(FGCPResource): _idname = 'backupId' backupId = None backupTime = None def getparentid(self): # CHECKME: the parent of a backup is a vdisk, and we need to get the vsystem if self._parent is not None: if isinstance(self._parent, FGCPVDisk): # we get the vdisk's parent's id here, i.e. the vsystem id (see also above) return self._parent.getparentid() elif isinstance(self._parent, FGCPResource): # we get the parent's id as usual return self._parent.getid() elif isinstance(self._parent, str): return self._parent def get_timeval(self): # convert weird time format to time value timeval = time.mktime(time.strptime(self.backupTime, "%b %d, %Y %I:%M:%S %p")) # CHECKME: store as string again ? setattr(self, 'timeval', str(timeval)) return timeval def restore(self, wait=None): self.show_output('Restoring Backup %s' % self.getid()) if isinstance(self._parent, FGCPVDisk): result = self.getproxy().RestoreVDisk(self.getparentid(), self.getid()) elif isinstance(self._parent, FGCPEfm): # grand-parent, parent and current result = self.getproxy().RestoreEFM(self._parent.getparentid(), self.getparentid(), self.getid()) else: result = 'UNKNOWN' # CHECKME: we can't really wait here, because we're not on the vdisk or efm level ? return result def destroy(self): self.show_output('Destroying Backup %s' % self.getid()) if isinstance(self._parent, FGCPVDisk): result = self.getproxy().DestroyVDiskBackup(self.getparentid(), self.getid()) elif isinstance(self._parent, FGCPEfm): # grand-parent, parent and current result = self.getproxy().DestroyEFMBackup(self._parent.getparentid(), self.getparentid(), self.getid()) else: result = 'UNKNOWN' return result class FGCPVNic(FGCPResource): _idname = 'networkId' # CHECKME: or use privateIp ? networkId = None privateIp = None nicNo = None class FGCPEfm(FGCPResource): _idname = 'efmId' efmId = None efmName = None efmType = None creator = None firewall = None loadbalancer = None slbVip = None backups = None def create(self, wait=None): # CHECKME: we use networkId to identify the network here, although this isn't found in the normal object definition !? self.show_output('Creating EFM %s %s' % (self.efmType, self.efmName)) efmId = self.getproxy().CreateEFM(self.getparentid(), self.efmType, self.efmName, self.networkId) # set the efmId here too setattr(self, 'efmId', efmId) # CHECKME: invalidate list of firewalls/loadbalancers in VSystem if isinstance(self._parent, FGCPVSystem): if self.efmType == 'FW': self._parent.reset_attr('firewalls') else: self._parent.reset_attr('loadbalancers') if wait: # wait for the EFM to be ready self.wait_for_status(['DEPLOYING'], ['STOPPED']) self.show_output('Created EFM %s %s' % (self.efmType, self.efmName)) return efmId def retrieve(self): return self def update(self, *args, **kwargs): self.show_output('Updating EFM %s' % self.efmName) allowed = ['efmName'] # convert arguments to dict tododict = self._args2dict(args, kwargs, allowed) # CHECKME: what if we updated the object attributes directly ? result = None for key in tododict: if tododict[key] != getattr(self, key, None): result = self.getproxy().UpdateEFMAttribute(self.getparentid(), self.getid(), key, tododict[key]) self.show_output('Updated EFM %s' % self.efmName) return result def destroy(self): self.show_output('Destroying EFM %s %s' % (self.efmType, self.efmName)) efmId = self.getproxy().DestroyEFM(self.getparentid(), self.efmType, self.efmId) # CHECKME: invalidate list of firewalls/loadbalancers in VSystem if isinstance(self._parent, FGCPVSystem): if self.efmType == 'FW': self._parent.reset_attr('firewalls') else: self._parent.reset_attr('loadbalancers') self.show_output('Destroyed EFM %s %s' % (self.efmType, self.efmName)) return def status(self): status = self.getproxy().GetEFMStatus(self.getparentid(), self.getid()) setattr(self, 'efmStatus', status) return status def start(self, wait=None): self.show_output('Starting EFM %s %s' % (self.efmType, self.efmName)) done = self.check_status(['STOPPED', 'UNEXPECTED_STOP'], ['RUNNING']) if done: return done result = self.getproxy().StartEFM(self.getparentid(), self.getid()) if wait: result = self.wait_for_status(['STARTING'], ['RUNNING']) self.show_output('Started EFM %s %s' % (self.efmType, self.efmName)) return result def stop(self, wait=None): self.show_output('Stopping EFM %s %s' % (self.efmType, self.efmName)) done = self.check_status(['RUNNING'], ['STOPPED', 'UNEXPECTED_STOP']) if done: return done result = self.getproxy().StopEFM(self.getparentid(), self.getid()) if wait: result = self.wait_for_status(['STOPPING'], ['STOPPED', 'UNEXPECTED_STOP']) self.show_output('Stopped EFM %s %s' % (self.efmType, self.efmName)) return result #========================================================================= def list_backups(self, timeZone=None, countryCode=None): if timeZone or countryCode: return self.getproxy().ListEFMBackup(self.getparentid(), self.getid(), timeZone, countryCode) if getattr(self, 'backups', None) is None: setattr(self, 'backups', self.getproxy().ListEFMBackup(self.getparentid(), self.getid(), timeZone, countryCode)) return getattr(self, 'backups') def get_backup(self, backup): # support resource or id if isinstance(backup, FGCPBackup): return backup.retrieve() backups = self.list_backups() for entry in backups: if backup == entry.backupId: return entry.retrieve() raise FGCPResourceError('ILLEGAL_BACKUP', 'Invalid backup %s' % backup, self) def backup(self, wait=None): self.show_output('Start Backup EFM %s' % self.efmName) # check current status done = self.check_status(['RUNNING'], ['BACKUP_ING']) if not done: # backup EFM now result = self.getproxy().BackupEFM(self.getparentid(), self.getid()) else: result = done if wait: # wait for the backup to be done result = self.wait_for_status(['BACKUP_ING'], ['RUNNING']) self.show_output('Finish Backup EFM %s' % self.efmName) return result def restore(self, backup, wait=None): backup = self.get_backup(backup) self.show_output('Start Restore %s for EFM %s' % (backup, self.efmName)) # check current status done = self.check_status(['RUNNING'], ['RESTORING']) if not done: if isinstance(backup, FGCPResource): result = self.getproxy().RestoreEFM(self.getparentid(), self.getid(), backup.getid()) else: result = self.getproxy().RestoreEFM(self.getparentid(), self.getid(), backup) else: result = done if wait: # wait for the backup to be done result = self.wait_for_status(['RESTORING'], ['RUNNING']) self.show_output('Finish Restore EFM %s' % self.efmName) return result #========================================================================= def get_config_handler(self): if getattr(self, '_get_handler', None) is None: setattr(self, '_get_handler', self.getproxy().GetEFMConfigHandler(self.getparentid(), self.getid())) return getattr(self, '_get_handler') def update_config_handler(self): if getattr(self, '_update_handler', None) is None: setattr(self, '_update_handler', self.getproxy().UpdateEFMConfigHandler(self.getparentid(), self.getid())) return getattr(self, '_update_handler') #========================================================================= def get_update_info(self): update_info = self.get_config_handler().fw_update() # CHECKME: merge answer with current firewall/loadbalancer ? self.merge_attr(update_info) return update_info def apply_update(self): return self.update_config_handler().efm_update() def revert_update(self): return self.update_config_handler().efm_backout() #========================================================================= def get_child_object(self): # CHECKME: get child firewall or loadbalancer object and merge EFM attributes if isinstance(self, FGCPFirewall) or isinstance(self, FGCPLoadBalancer): # we're already a firewall or loadbalancer return self if self.efmType == 'FW': if getattr(self, 'firewall', None) is None: # create new firewall setattr(self, 'firewall', FGCPFirewall()) # check if we have the right child object if not isinstance(self.firewall, FGCPFirewall): # return whatever this is, e.g. str for logs or list for limit_policies return self.firewall # set attributes of EFM in firewall for key in self.__dict__: if key == 'firewall': continue setattr(self.firewall, key, self.__dict__[key]) # move one step up in the hierarchy self.firewall.setparent(self._parent) # return firewall return self.firewall elif self.efmType == 'SLB': if getattr(self, 'loadbalancer', None) is None: # create new loadbalancer setattr(self, 'loadbalancer', FGCPLoadBalancer()) if not isinstance(self.loadbalancer, FGCPLoadBalancer): # return whatever this is, e.g. ??? return self.loadbalancer # set attributes of EFM in loadbalancer for key in self.__dict__: if key == 'loadbalancer': continue setattr(self.loadbalancer, key, self.__dict__[key]) # move one step up in the hierarchy self.loadbalancer.setparent(self._parent) # return loadbalancer return self.loadbalancer class FGCPFirewall(FGCPEfm): efmType = 'FW' # CHECKME: this returns an attribute 'status' which is in conflict with the default status() method ! _status = None nat = None dns = None directions = None log = None category = None latestVersion = None comment = None firmUpdateExist = None configUpdateExist = None updateDate = None backout = None currentVersion = None def list_nat_rules(self): if self.nat is None: self.get_nat_rules() return self.nat def get_nat_rules(self): # CHECKME: merge answer with current firewall ? self.nat = self.get_config_handler().fw_nat_rule() if self.nat is None: self.nat = [] return self.nat def set_nat_rules(self, rules=None): result = self.update_config_handler().fw_nat_rule(rules) return result def _add_nat_rule(self, **kwargs): if getattr(self, 'nat', None) is None: self.get_nat_rules() #nat_rule = FGCPNATRule(publicIp='80.70.163.172', snapt='true', privateIp='192.168.0.211') nat_rule = FGCPNATRule(**kwargs) # set the parent of the nat_rule to this firewall #nat_rule.setparent(self) self.nat.append(nat_rule) # TODO: send update to proxy def get_dns(self): # CHECKME: merge answer with current firewall ? self.dns = self.get_config_handler().fw_dns() return self.dns def set_dns(self, dnstype='AUTO', primary=None, secondary=None): result = self.update_config_handler().fw_dns(dnstype, primary, secondary) self.dns = None return result def list_policies(self): if self.directions is None: self.get_policies() return self.directions def get_policies(self, from_zone=None, to_zone=None): if from_zone or to_zone: return self.get_config_handler().fw_policy(from_zone, to_zone) # CHECKME: merge answer with current firewall ? self.directions = self.get_config_handler().fw_policy() return self.directions def set_policies(self, log='On', policies=None): result = self.update_config_handler().fw_policy(log, policies) self.directions = None return result def _add_direction(self, **kwargs): if self.directions is None: self.directions = [] #direction = FGCPFWDirection(from_zone='INTERNET', to_zone='DMZ', policies=[]) direction = FGCPFWDirection(**kwargs) # set the parent of the direction to this firewall #direction.setparent(self) self.directions.append(direction) # TODO: send update to proxy def get_log(self, num=100, orders=None): # FIXME: make log order builder !? return self.get_config_handler().fw_log(num, orders) def get_limit_policies(self, from_zone=None, to_zone=None): return self.get_config_handler().fw_limit_policy(from_zone, to_zone) class FGCPFWNATRule(FGCPResource): _idname = 'publicIp' publicIp = None privateIp = None snapt = None class FGCPFWDns(FGCPResource): _idname = 'type' type = None primary = None secondary = None class FGCPFWDirection(FGCPResource): # CHECKME: this has an attribute 'from' which causes problems for Python ! _idname = None from_zone = None to_zone = None policies = None acceptable = None maxPolicyNum = None prefix = None def getid(self): # get the last part of the direction, i.e. DMZ, SECURE1, SECURE2 etc. from_zone = getattr(self, 'from', '').split('-').pop() to_zone = getattr(self, 'to', '').split('-').pop() return '%s-%s' % (from_zone, to_zone) def _list_policies(self): return getattr(self, 'policies', []) def _add_policy(self, **kwargs): if self.policies is None: self.policies = [] #policy = FGCPFWPolicy(id=123, action='Accept', ...) policy = FGCPFWPolicy(**kwargs) # set the parent of the policy to this direction #direction.setparent(self) self.policies.append(policy) class FGCPFWPolicy(FGCPResource): _idname = 'id' id = None action = None dst = None dstPort = None dstService = None dstType = None log = None protocol = None src = None srcPort = None srcType = None class FGCPFWLogOrder(FGCPResource): _idname = 'prefix' # CHECKME: this has an attribute 'from' which causes problems for Python ! prefix = None value = None from_zone = None to_zone = None def __init__(self, **kwargs): for key in kwargs: # CHECKME: replace from_zone and to_zone, because from=... is restricted setattr(self, key.replace('_zone', ''), kwargs[key]) class FGCPLoadBalancer(FGCPEfm): efmType = 'SLB' ipAddress = None # CHECKME: this returns an attribute 'status' which is in conflict with the default status() method ! _status = None webAccelerator = None groups = None loadStatistics = None errorStatistics = None servercerts = None ccacerts = None srcPort = None srcType = None category = None latestVersion = None comment = None firmUpdateExist = None configUpdateExist = None updateDate = None backout = None currentVersion = None def get_rules(self): # CHECKME: get loadbalancer directly from config_handler ? rules = self.get_config_handler().slb_rule() # CHECKME: merge answer with current loadbalancer ? self.merge_attr(rules) if self.groups is None: self.groups = [] return rules def set_rules(self, groups=None, force=None, webAccelerator=None): """Usage: loadbalancer = vsystem.get_loadbalancer('SLB1') # get all rules rules = loadbalancer.get_rules() # adapt the group list new_groups = [] for group in rules.groups: ... new_groups.append(group) # update all rules result = loadbalancer.set_rules(groups=new_groups, force=None, webAccelerator=None) """ result = self.update_config_handler().slb_rule(groups, force, webAccelerator) # CHECKME: invalidate list of groups to be sure self.groups = None return result def list_groups(self): if self.groups is None: self.get_rules() return self.groups def get_group(self, groupId): # support resource or id if isinstance(groupId, FGCPSLBGroup): return groupId.retrieve() if not isinstance(groupId, str): groupId = str(groupId) groups = self.list_groups() for group in groups: if groupId == group.id: return group.retrieve() raise FGCPResourceError('ILLEGAL_SLB_GROUP', 'Invalid groupId %s' % groupId, self) def add_group(self, **kwargs): """Usage: loadbalancer = vsystem.get_loadbalancer('SLB1') vserver1 = vsystem.get_vserver('WebApp1') vserver2 = vsystem.get_vserver('WebApp2') # add single group loadbalancer.add_group(id=10, protocol='http', targets=[vserver1, vserver2]) """ if self.groups is None: self.get_rules() #group = FGCPSLBGroup(id=10, protocol='http', port1=80, targets=[], ...) group = FGCPSLBGroup(**kwargs) # set the parent of the group to this loadbalancer #group.setparent(self) # CHECKME: set default values depending on protocol group.set_defaults() if len(group.targets) < 1: raise FGCPResourceError('ILLEGAL_SLB_GROUP', 'You need to specify at least one target vserver for this group', self) self.groups.append(group) if len(self.groups) > 0: result = self.set_rules(groups=self.groups, webAccelerator=self.webAccelerator) # CHECKME: invalidate list of groups to be sure self.groups = None return result def _add_group_target(self, groupId, serverId): pass def _delete_group_target(self, groupId, serverId): pass def delete_group(self, groupId): """Usage: loadbalancer = vsystem.get_loadbalancer('SLB1') # list all groups groups = loadbalancer.list_groups() for group in groups: if group.protocol != 'http': continue # delete single group loadbalancer.delete_group(group.id) break """ groupId = self.get_group(groupId).id new_groups = [] for group in self.list_groups(): if groupId != group.id: new_groups.append(group) self.groups = new_groups result = self.set_rules(groups=self.groups, webAccelerator=self.webAccelerator) # CHECKME: invalidate list of groups to be sure self.groups = None return result def get_load_stats(self): load_stats = self.get_config_handler().slb_load() return load_stats def clear_load_stats(self): return self.update_config_handler().slb_load_clear() def get_error_stats(self): error_stats = self.get_config_handler().slb_error() return error_stats def clear_error_stats(self): return self.update_config_handler().slb_error_clear() def list_servercerts(self, detail=None): if detail: return self.get_config_handler().slb_cert_list('server', detail) if self.servercerts is None: self.get_cert_list() return self.servercerts def get_cert_list(self, certCategory=None, detail=None): if certCategory or detail: return self.get_config_handler().slb_cert_list(certCategory, detail) cert_list = self.get_config_handler().slb_cert_list() # CHECKME: merge answer with current loadbalancer ? self.merge_attr(cert_list) if self.servercerts is None: self.servercerts = [] if self.ccacerts is None: self.ccacerts = [] return cert_list def add_cert(self, certNum, filePath, passphrase): result = self.update_config_handler().slb_cert_add(certNum, filePath, passphrase) # CHECKME: invalidate list of servercerts to be sure self.servercerts = None return result def set_cert(self, certNum, groupId): return self.update_config_handler().slb_cert_set(certNum, groupId) def release_cert(self, certNum): return self.update_config_handler().slb_cert_release(certNum) def delete_cert(self, certNum, force=None): result = self.update_config_handler().slb_cert_delete(certNum, force) # CHECKME: invalidate list of servercerts to be sure self.servercerts = None return result def list_ccacerts(self, detail=None): if detail: return self.get_config_handler().slb_cert_list('cca', detail) if self.ccacerts is None: self.get_cert_list() return self.ccacerts def add_cca(self, ccacertNum, filePath): result = self.update_config_handler().slb_cca_add(ccacertNum, filePath) # CHECKME: invalidate list of ccacerts to be sure self.ccacerts = None return result def delete_cca(self, ccacertNum): result = self.update_config_handler().slb_cca_delete(ccacertNum) # CHECKME: invalidate list of ccacerts to be sure self.ccacerts = None return result def start_maintenance(self, groupId, ipAddress, time=None, unit=None): return self.update_config_handler().slb_start_maint(groupId, ipAddress, time, unit) def stop_maintenance(self, groupId, ipAddress): return self.update_config_handler().slb_stop_maint(groupId, ipAddress) class FGCPSLBGroup(FGCPResource): _idname = 'id' id = None protocol = None port1 = None port2 = None certNum = None balanceType = None monitorType = None maxConnection = None uniqueType = None uniqueRetention = None interval = None timeout = None retryCount = None recoveryAction = None targets = None causes = None def set_defaults(self): # CHECKME: set default values depending on protocol if self.protocol is None: self.protocol = 'http' defaults = {'port2': None, 'targets': [], 'interval': 60, 'timeout': 10, 'retryCount': 3, 'monitorType': 'ping', 'balanceType': 'round-robin', 'recoveryAction': 'switch-back'} if self.protocol == 'http+https': defaults['uniqueType'] = 'By IP address' defaults['uniqueRetention'] = 90 defaults['maxConnection'] = 10000 defaults['port1'] = 80 defaults['port2'] = 443 elif self.protocol == 'https': defaults['uniqueType'] = 'By connection' defaults['maxConnection'] = 10000 defaults['port1'] = 443 elif self.protocol == 'http': defaults['uniqueType'] = 'By connection' defaults['maxConnection'] = 58000 defaults['port1'] = 80 else: defaults['uniqueType'] = 'By connection' defaults['maxConnection'] = 58000 for key in defaults: if getattr(self, key, None) is None: setattr(self, key, defaults[key]) new_targets = [] for target in self.targets: if isinstance(target, str): # TODO: find the right serverId target = FGCPSLBTarget(serverId=target) # set the parent of the target to this group #target.setparent(self) elif isinstance(target, FGCPVServer): target = FGCPSLBTarget(serverId=target.vserverId) # set the parent of the target to this group #target.setparent(self) if getattr(target, 'port1', None) is None: setattr(target, 'port1', self.port1) if getattr(target, 'port2', None) is None: setattr(target, 'port2', self.port2) new_targets.append(target) self.id = str(self.id) self.targets = new_targets def _list_targets(self): return getattr(self, 'targets', []) def _get_target(self, serverId): for target in self._list_targets(): if target.serverId == serverId: return target def _add_target(self, **kwargs): if self.targets is None: self.targets = [] #target = FGCPSLBTarget(serverId=serverId, port1=port1, port2=port2) target = FGCPSLBTarget(**kwargs) # set the parent of the target to this group #target.setparent(self) self.targets.append(target) def _delete_target(self, serverId): serverId = self._get_target(serverId).serverId targets = self._list_targets() new_targets = [] for target in targets: if serverId != target.serverId: new_targets.append(target) self.targets = new_targets def _list_causes(self): return getattr(self, 'causes', []) class FGCPSLBTarget(FGCPResource): _idname = 'serverId' serverId = None ipAddress = None serverName = None port1 = None port2 = None # CHECKME: this returns an attribute 'status' which may be in conflict with the default status() method ! status = None peak = None now = None class FGCPSLBCause(FGCPResource): _idname = 'cat' cat = None # CHECKME: this returns an attribute 'status' which may be in conflict with the default status() method ! status = None before = None current = None today = None total = None yesterday = None #filePath = None class FGCPSLBErrorStats(FGCPResource): _idname = None period = None groups = None def list_groups(self): return getattr(self, 'groups', []) class FGCPSLBErrorPeriod(FGCPResource): _idname = None before = None current = None today = None yesterday = None class FGCPSLBServerCert(FGCPResource): _idname = 'certNum' certNum = None subject = None issuer = None validity = None groupId = None detail = None class FGCPSLBCCACert(FGCPResource): _idname = 'ccacertNum' ccacertNum = None subject = None description = None issuer = None validity = None detail = None class FGCPPublicIP(FGCPResource): _idname = 'address' address = None v4v6Flag = None vsysId = None def allocate(self): # see VSystem allocate_publicip pass def retrieve(self, refresh=None): return self.get_attributes(refresh) def status(self): status = self.getproxy().GetPublicIPStatus(self.getid()) setattr(self, 'publicipStatus', status) return status def attach(self, wait=None): self.show_output('Attaching PublicIP %s' % self.address) done = self.check_status(['DETACHED'], ['ATTACHED']) if done: return done result = self.getproxy().AttachPublicIP(self.getparentid(), self.getid()) if wait: result = self.wait_for_status(['ATTACHING'], ['ATTACHED']) self.show_output('Attached PublicIP %s' % self.address) return result def detach(self, wait=None): self.show_output('Detaching PublicIP %s' % self.address) done = self.check_status(['ATTACHED'], ['DETACHED']) if done: return done result = self.getproxy().DetachPublicIP(self.getparentid(), self.getid()) if wait: result = self.wait_for_status(['DETACHING'], ['DETACHED']) self.show_output('Detached PublicIP %s' % self.address) return result def free(self, wait=None): self.show_output('Freeing PublicIP %s' % self.address) # CHECKME: this actually won't work if the publicip has already been freed try: done = self.check_status(['DETACHED'], ['UNDEPLOYING', 'UNDEPLOY']) except: done = 'GONE' if done: return done result = self.getproxy().FreePublicIP(self.getparentid(), self.getid()) if wait: # CHECKME: we won't wait for it to be gone here self.show_output('Free PublicIP %s' % self.address) return result def get_attributes(self, refresh=None): # CHECKME: if we already have the v4v6Flag information, we already retrieved the attributes if not refresh and getattr(self, 'v4v6Flag', None) is not None: return self # get attributes for this publicip publicipattr = self.getproxy().GetPublicIPAttributes(self.getid()) # CHECKME: copy configuration to self for key in publicipattr.__dict__: if key.startswith('_'): continue setattr(self, key, publicipattr.__dict__[key]) return self class FGCPAddressRange(FGCPResource): # CHECKME: this has an attribute 'from' which causes problems for Python ! _idname = None from_ip = None to_ip = None range = None def create_pool(): # see VDataCenter create_addresspool pass def add(): # see VDataCenter add_addressrange pass def delete(): # see VDataCenter delete_addressrange pass class FGCPVSysDescriptor(FGCPResource): _idname = 'vsysdescriptorId' vsysdescriptorId = None vsysdescriptorName = None description = None keyword = None creatorName = None registrant = None vservers = None diskimages = None def register(self): # see VSystem register_vsysdescriptor() pass def retrieve(self, refresh=None): # CHECKME: retrieve configuration here ? return self.get_configuration(refresh) def update(self, *args, **kwargs): self.show_output('Updating VSYSDescriptor %s' % self.vsysdescriptorName) allowed = ['vsysdescriptorName', 'description', 'keyword'] updatename = {'vsysdescriptorName': 'updateName', 'description': 'updateDescription', 'keyword': 'updateKeyword'} # convert arguments to dict tododict = self._args2dict(args, kwargs, allowed) # CHECKME: what if we updated the object attributes directly ? result = None for key in tododict: if tododict[key] != getattr(self, key, None): # CHECKME: updateLcId = 'en' here result = self.getproxy().UpdateVSYSDescriptorAttribute(self.getid(), 'en', updatename[key], tododict[key]) self.show_output('Updated VSYSDescriptor %s' % self.vsysdescriptorName) return result def unregister(self): #return self.getproxy().UnregisterVSYSDescriptor(self.getid()) # CHECKME: only private vsysdescriptors can be unregistered by end-users return self.getproxy().UnregisterPrivateVSYSDescriptor(self.getid()) #========================================================================= def list_diskimages(self, category='GENERAL'): if getattr(self, 'diskimages', None) is None: # CHECKME: reversed order of arguments here setattr(self, 'diskimages', self.getproxy().ListDiskImage(category, self.getid())) return getattr(self, 'diskimages') def get_diskimage(self, diskimageName): # support resource, name or id if isinstance(diskimageName, FGCPDiskImage): return diskimageName.retrieve() diskimages = self.list_diskimages() for diskimage in diskimages: if diskimageName == diskimage.diskimageName: return diskimage.retrieve() elif diskimageName == diskimage.diskimageId: return diskimage.retrieve() raise FGCPResourceError('ILLEGAL_DISKIMAGE', 'Invalid diskimageName %s' % diskimageName, self) #========================================================================= def list_vservers(self): if getattr(self, 'vservers', None) is None: self.retrieve() return getattr(self, 'vservers') #========================================================================= def get_configuration(self, refresh=None): # CHECKME: if we already have the registrant information etc., we already retrieved the attributes # CHECKME: if we already also have the vservers information, we already retrieved the configuration if not refresh and getattr(self, 'registrant', None) is not None: return self # get configuration for this vsysdescriptor config = self.getproxy().GetVSYSDescriptorConfiguration(self.getid()) # CHECKME: copy configuration to self for key in config.__dict__: if key.startswith('_'): continue setattr(self, key, config.__dict__[key]) return self #========================================================================= def create_vsystem(self, vsysName, wait=None): self.show_output('Creating VSystem %s' % vsysName) vsysId = self.getproxy().CreateVSYS(self.getid(), vsysName) # CHECKME: invalidate list of vsystems in VDataCenter if isinstance(self._parent, FGCPVDataCenter): self._parent.reset_attr('vsystems') if wait: # get the newly created vsystem vsystem = self._parent.get_vsystem(vsysName) # wait for the vsystem to be ready vsystem.wait_for_status(['DEPLOYING', 'RECONFIG_ING'], ['NORMAL']) self.show_output('Created VSystem %s' % vsysName) return vsysId class FGCPDiskImage(FGCPResource): _idname = 'diskimageId' diskimageId = None diskimageName = None description = None creatorName = None licenseInfo = None osName = None osType = None registrant = None size = None softwares = None servertypes = None def register(self): # see VServer register_diskimage pass def update(self, *args, **kwargs): self.show_output('Updating DiskImage %s' % self.diskimageName) allowed = ['diskimageName', 'description'] updatename = {'diskimageName': 'updateName', 'description': 'updateDescription'} # convert arguments to dict tododict = self._args2dict(args, kwargs, allowed) # CHECKME: what if we updated the object attributes directly ? result = None for key in tododict: if tododict[key] != getattr(self, key, None): # CHECKME: updateLcId = 'en' here result = self.getproxy().UpdateDiskImageAttribute(self.getid(), 'en', updatename[key], tododict[key]) self.show_output('Updated DiskImage %s' % self.diskimageName) return result def unregister(self): return self.getproxy().UnregisterDiskImage(self.getid()) def list_softwares(self): if getattr(self, 'softwares', None) is None: # CHECKME: initialize to None or list here ? setattr(self, 'softwares', []) return getattr(self, 'softwares') def list_servertypes(self): if getattr(self, 'servertypes', None) is None: setattr(self, 'servertypes', self.getproxy().ListServerType(self.getid())) return getattr(self, 'servertypes') class FGCPImageSoftware(FGCPResource): _idname = 'name' name = None license = None category = None id = None officialVersion = None patch = None support = None version = None class FGCPServerType(FGCPResource): # this is what we actually pass to CreateVServer _idname = 'name' name = None chargeType = None comment = None cpu = None expectedUsage = None id = None label = None memory = None price = None productId = None productName = None disks = None def list_disks(self): # CHEKCME: currently unused ? if getattr(self, 'disks', None) is None: setattr(self, 'disks', []) return getattr(self, 'disks') class FGCPServerTypeCPU(FGCPResource): _idname = None cpuArch = None cpuPerf = None numOfCpu = None class FGCPServerTypeDisk(FGCPResource): # CHEKCME: currently unused ? _idname = None diskSize = None diskType = None diskUsage = None class FGCPUsageInfo(FGCPResource): _idname = 'vsysId' vsysId = None vsysName = None products = None def list_products(self): if getattr(self, 'products', None) is None: setattr(self, 'products', []) return getattr(self, 'products') class FGCPUsageInfoProduct(FGCPResource): _idname = 'productName' productName = None unitName = None usedPoints = None class FGCPInformation(FGCPResource): _idname = 'seqno' entryDate = None expiry = None message = None seqno = None startDate = None title = None class FGCPEventLog(FGCPResource): _idname = None entryDate = None expiry = None message = None startDate = None title = None class FGCPPerformanceInfo(FGCPResource): _idname = None cpuUtilization = None diskReadRequestCount = None diskReadSector = None diskWriteRequestCount = None diskWriteSector = None nicInputByte = None nicInputPacket = None nicOutputByte = None nicOutputPacket = None recordTime = None class FGCPUnknown(FGCPResource): pass
Python
#!/usr/bin/python # # Copyright (C) 2012 Michel Dalle # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ XML-RPC Connection with the Fujitsu Global Cloud Platform (FGCP) API Server Example: [not recommended, use API Commands, Resource Actions and/or Client Methods instead] # Connect with your client certificate to region 'uk' from fgcp.connection import FGCPProxyServer xmlrpc_proxy = FGCPProxyServer('client.pem', 'uk') # Send XML-RPC actions, request parameters and attachments vsystems = xmlrpc_proxy.do_action('ListVSYS') for vsys in vsystems: status = xmlrpc_proxy.do_action('GetVSYSStatus', {'vsysId': vsys.vsysId}) vsysconfig = xmlrpc_proxy.do_action('GetVSYSConfiguration', {'vsysId': vsys.vsysId}) for vserver in vsysconfig.vservers: status = xmlrpc_proxy.do_action('GetVServerStatus', {'vsysId': vsys.vsysId, 'vserverId': vserver.vserverId}) ... """ import time import base64 import os.path try: from gdata.tlslite.utils import keyfactory except: print """Requirements: this module uses gdata.tlslite.utils to create the key signature, see http://code.google.com/p/gdata-python-client/ for download and installation""" exit() from xml.etree import ElementTree from fgcp import FGCPError from fgcp.resource import * class FGCPResponseError(FGCPError): pass class FGCPConnection: """ FGCP XML-RPC Connection """ key_file = 'client.pem' # updated based on key_file argument region = 'de' # updated based on region argument locale = 'en' # TODO: make configurable to 'en' or 'jp' ? timezone = 'Central European Time' # updated based on time.tzname[0] or time.timezone verbose = 0 # normal script output for users: # 0 = quiet # 1 = show user output # 2 = show status output debug = 0 # for development purposes: # 0 = quiet # 1 = show API request # 2 = dump response object # 3 = dump request/response body # 99 = save request/response body for test fixture uri = '/ovissapi/endpoint' # fixed value for the API version #api_version = '2011-01-31' # fixed value for the API version api_version = '2012-02-18' # fixed value for the API version user_agent = 'OViSS-API-CLIENT' # fixed value for the API version _conn = None # actual httplib.HTTPSConnection() or FGCPTestServerWithFixtures() or ... _caller = None # which FGCPResource() is calling _testid = None # test identifier for fixtures def __init__(self, key_file='client.pem', region='de', verbose=0, debug=0, conn=None): """ Use the same PEM file for SSL client certificate and RSA key signature Note: to convert your .p12 or .pfx file to unencrypted PEM format, you can use the following 'openssl' command: openssl pkcs12 -in UserCert.p12 -out client.pem -nodes """ self.key_file = key_file self.region = region self.verbose = verbose self.debug = debug if conn is not None: self._conn = conn # Note: the timezone doesn't seem to matter for the API server, # as long as the expires value is set to the current time self.timezone = time.tzname[0] if len(self.timezone) < 1: offset = int(time.timezone / 3600) if offset > 0: self.timezone = 'Etc/GMT+%s' % offset elif offset < 0: self.timezone = 'Etc/GMT-%s' % offset else: self.timezone = 'Etc/GMT' self._key = None def __repr__(self): return '<%s:%s>' % (self.__class__.__name__, self.region) def set_region(self, region): # reset connection if necessary if self.region != region: self.close() self.region = region def set_key(self, key_string): # Note: we need an unencrypted PEM string for this ! self._key = keyfactory.parsePrivateKey(key_string) def set_conn(self, conn): # CHECKME: set connection from elsewhere, e.g. for integration with Apache Libcloud self._conn = conn def connect(self): if self._conn is None: # get the right server connection from fgcp.server import FGCPGetServerConnection self._conn = FGCPGetServerConnection(key_file=self.key_file, region=self.region) def send(self, method, uri, body, headers): # initialize connection if necessary self.connect() # set testid if necessary if self.region == 'test': self._conn.set_testid(self._testid) # send HTTPS request self._conn.request(method, uri, body, headers) def receive(self): # get HTTPS response resp = self._conn.getresponse() # check response if resp.status != 200: raise FGCPResponseError(repr(resp.status), repr(resp.reason)) # return data return resp.read() def close(self): if self._conn is not None: self._conn.close() self._conn = None def get_headers(self, attachments=None): if attachments is None: return {'User-Agent': self.user_agent} else: # use multipart/form-data return {'User-Agent': self.user_agent, 'Content-Type': 'multipart/form-data; boundary=BOUNDARY'} # see com.fujitsu.oviss.pub.OViSSSignature def get_accesskeyid(self): t = long(time.time() * 1000) acc = base64.b64encode(self.timezone + '&' + str(t) + '&1.0&SHA1withRSA') return acc # see com.fujitsu.oviss.pub.OViSSSignature def get_signature(self, acc=None): if acc is None: acc = self.get_accesskeyid() if self._key is None: # Note: we need an unencrypted PEM file for this ! s = open(self.key_file, 'rb').read() self._key = keyfactory.parsePrivateKey(s) # RSAKey.hashAndSign() creates an RSA/PKCS1-1.5(SHA-1) signature, and does the equivalent of "SHA1withRSA" Signature method in Java # Note: the accesskeyid is already base64-encoded here sig = base64.b64encode(self._key.hashAndSign(acc)) return sig def get_body(self, action, params=None, attachments=None): if self.region == 'test': # sanitize accesskeyid and signature for test fixtures acc = '...' sig = '...' else: acc = self.get_accesskeyid() sig = self.get_signature(acc) CRLF = '\r\n' L = [] if self.region == 'test' or self.debug > 0: self._testid = action L.append('<?xml version="1.0" encoding="UTF-8"?>') L.append('<OViSSRequest>') L.append(' <Action>' + action + '</Action>') L.append(' <Version>' + self.api_version + '</Version>') L.append(' <Locale>' + self.locale + '</Locale>') if params is not None: for key, val in params.items(): extra = self.add_param(key, val, 1) if extra: L.append(extra) L.append(' <AccessKeyId>' + acc + '</AccessKeyId>') L.append(' <Signature>' + sig + '</Signature>') L.append('</OViSSRequest>') body = CRLF.join(L) # add request description file for certain EFM Configuration methods and other API commands if attachments is None: attachments = [] elif len(attachments) > 0 and isinstance(attachments, dict): attachments = [attachments] if len(attachments) > 0: L = [] L.append('--BOUNDARY') L.append('Content-Type: text/xml; charset=UTF-8') L.append('Content-Disposition: form-data; name="Document"') L.append('') L.append(body) L.append('') for attachment in attachments: if 'body' not in attachment: if os.path.exists(attachment['filename']): attachment['body'] = open(attachment['filename'], 'rb').read() else: raise FGCPResponseError('INVALID_PATH', 'Attachment file %s does not exist' % attachment['filename']) elif 'filename' not in attachment: attachment['filename'] = 'extra.xml' L.append('--BOUNDARY') L.append('Content-Type: application/octet-stream') L.append('Content-Disposition: form-data; name="%s"; filename="%s"' % (attachment['name'], attachment['filename'])) L.append('') L.append(attachment['body']) if self.region == 'test' or self.debug > 0: self._testid += '.%s' % attachment['filename'] L.append('--BOUNDARY--') body = CRLF.join(L) #if len(attachments) > 1: # print body # exit() return body def add_param(self, key=None, value=None, depth=0): CRLF = '\r\n' L = [] if key is None: pass elif value is None: # CHECKME: we skip None values too pass elif isinstance(value, str): # <prefix>proto</prefix> L.append(' ' * depth + '<%s>%s</%s>' % (key, value, key)) if self.region == 'test' or self.debug > 0: self._testid += '.%s' % value elif isinstance(value, dict): # <order> # <prefix>proto</proto> # <value>tcp</value> # </order> L.append(' ' * depth + '<%s>' % key) for entry, val in value.items(): extra = self.add_param(entry, val, depth + 1) if extra: L.append(extra) L.append(' ' * depth + '</%s>' % key) elif isinstance(value, list): L.append(' ' * depth + '<%s>' % key) # <orders> # <order> # ... # </order> # <order> # ... # </order> # </orders> for item in value: # CHECKME: item must be a dict of {'entry': val} ! for entry, val in item.items(): extra = self.add_param(entry, val, depth + 1) if extra: L.append(extra) L.append(' ' * depth + '</%s>' % key) else: # <prefix>proto</prefix> L.append(' ' * depth + '<%s>%s</%s>' % (key, value, key)) if self.region == 'test' or self.debug > 0: self._testid += '.%s' % value return CRLF.join(L) def do_action(self, action, params=None, attachments=None): """ Send the XML-RPC request and get the response """ # prepare headers and body headers = self.get_headers(attachments) body = self.get_body(action, params, attachments) if self.debug > 10: print 'Saving request for %s' % self._testid if not hasattr(self, '_tester'): # use test API server for saving tests too from fgcp.server import FGCPTestServerWithFixtures setattr(self, '_tester', FGCPTestServerWithFixtures()) self._tester.save_request(self._testid, body) elif self.debug > 2: print 'XML-RPC Request for %s:' % self._testid print body elif self.debug > 0: print self._testid # send XML-RPC request self.send('POST', self.uri, body, headers) # receive XML-RPC response data = self.receive() if self.debug > 10: print 'Saving response for %s' % self._testid self._tester.save_response(self._testid, data) elif self.debug > 2: print 'XML-RPC Response for %s:' % self._testid print data # analyze XML-RPC response try: resp = FGCPResponseParser().parse_data(data, self) except: print 'Invalid XML-RPC Response:' print data raise if self.debug > 1: print 'FGCP Response for %s:' % action resp.pprint() # CHECKME: raise exception whenever we don't have SUCCESS if resp.responseStatus != 'SUCCESS': raise FGCPResponseError(resp.responseStatus, resp.responseMessage) # return FGCP Response return resp class FGCPProxyServer(FGCPConnection): """ FGCP XML-RPC Proxy Server """ pass class FGCPResponseParser: """ FGCP Response Parser """ _proxy = None # CHECKME: this assumes all tags are unique - otherwise we'll need to use the path _tag2class = { 'vsysdescriptor': FGCPVSysDescriptor, 'publicip': FGCPPublicIP, 'addressrange': FGCPAddressRange, 'diskimage': FGCPDiskImage, 'software': FGCPImageSoftware, 'servertype': FGCPServerType, 'cpu': FGCPServerTypeCPU, 'vsys': FGCPVSystem, 'vserver': FGCPVServer, 'image': FGCPVServerImage, 'vdisk': FGCPVDisk, 'backup': FGCPBackup, 'vnic': FGCPVNic, 'efm': FGCPEfm, 'firewall': FGCPFirewall, 'rule': FGCPFWNATRule, 'dns': FGCPFWDns, 'direction': FGCPFWDirection, 'policy': FGCPFWPolicy, 'order': FGCPFWLogOrder, 'loadbalancer': FGCPLoadBalancer, 'group': FGCPSLBGroup, 'target': FGCPSLBTarget, 'errorStatistics': FGCPSLBErrorStats, 'cause': FGCPSLBCause, 'period': FGCPSLBErrorPeriod, 'servercert': FGCPSLBServerCert, 'ccacert': FGCPSLBCCACert, 'usageinfo': FGCPUsageInfo, 'product': FGCPUsageInfoProduct, 'information': FGCPInformation, 'eventlog': FGCPEventLog, 'performanceinfo': FGCPPerformanceInfo, 'response': FGCPResponse, 'default': FGCPUnknown, } def parse_data(self, data, proxy): """ Load the data as XML ElementTree and convert to FGCP Response """ # keep track of the connection proxy self._proxy = proxy #ElementTree.register_namespace(uri='http://apioviss.jp.fujitsu.com') # initialize the XML Element root = ElementTree.fromstring(data) # convert the XML Element to FGCP Response object - CHECKME: and link to caller !? return self.xmlelement_to_object(root, proxy._caller) def clean_tag(self, tag): """ Return the tag without namespace """ if tag is None: return tag elif tag.startswith('{'): return tag[tag.index('}') + 1:] else: return tag def get_tag_object(self, tag): tag = self.clean_tag(tag) if tag in self._tag2class: return self._tag2class[tag]() elif tag.endswith('Response'): return self._tag2class['response']() else: #print 'CHECKME: unknown tag ' + tag return self._tag2class['default']() # CHECKME: get rid of parent here again, and re-parent in resource itself ? def xmlelement_to_object(self, root=None, parent=None): """ Convert the XML Element to an FGCP Element """ if root is None: return # CHECKME: we don't seem to have any attributes here #for key, val in root.items(): # if key in info: # print "OOPS ! " + key + " attrib is already in " + repr(info) # else: # info[key] = val # No children -> return text if len(root) < 1: if root.text is None: return '' else: return root.text.strip() # One child -> return list !? elif len(root) == 1: info = [] # if the child returns a string, return that too (cfr. ListServerType - servertype - memory - memorySize) for subelem in root: # CHECKME: use grand-parent for the child now ! child = self.xmlelement_to_object(subelem, parent) if isinstance(child, str): return child else: info.append(child) return info # More children -> return dict or list !? #info = {} # FIXME: adapt class based on subelem or tag ? info = self.get_tag_object(root.tag) # add proxy to object info._proxy = self._proxy if isinstance(info, FGCPResource): # CHECKME: add parent and proxy to the FGCP Resource info._parent = parent info._proxy = self._proxy elif isinstance(info, FGCPResponse): # CHECKME: add caller to the FGCP Respone info._caller = parent for subelem in root: key = self.clean_tag(subelem.tag) if isinstance(info, list): # CHECKME: use grand-parent for the child now ! info.append(self.xmlelement_to_object(subelem, parent)) elif hasattr(info, key) and key == 'status': # special case to avoid overlap with status() method setattr(info, '_status', self.xmlelement_to_object(subelem, info)) elif hasattr(info, key) and getattr(info, key) is not None: #print "OOPS ! " + key + " child is already in " + repr(info) # convert to list !? child = getattr(info, key) # CHECKME: re-parent the child if child is not None and isinstance(child, FGCPResource): child._parent = parent info = [child] # CHECKME: use grand-parent for the child now ! info.append(self.xmlelement_to_object(subelem, parent)) elif isinstance(info, FGCPResponse): # CHECKME: use caller as parent here setattr(info, key, self.xmlelement_to_object(subelem, parent)) else: # CHECKME: use current info as parent for now setattr(info, key, self.xmlelement_to_object(subelem, info)) return info
Python
#!/usr/bin/python # # Copyright (C) 2011 Michel Dalle # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ Fujitsu Global Cloud Platform (FGCP) API Server(s) Example: [see tests/test_*.py for more examples] # Connect without client certificate to region 'test' from fgcp.resource import FGCPVDataCenter vdc = FGCPVDataCenter('client.pem', 'test') # Do typical resource actions - updates are not supported here vsystem = vdc.get_vsystem('Demo System') vsystem.show_status() for vserver in vsystem.vservers: #result = vserver.backup(wait=True) ... Note: you need to unzip the file 'fixtures.zip' in tests/fixtures first """ import httplib import time import os.path import re from fgcp import FGCPError FGCP_REGIONS = { 'au': 'api.globalcloud.fujitsu.com.au', # for Australia and New Zealand 'de': 'api.globalcloud.de.fujitsu.com', # for Central Europe, Middle East, Eastern Europe, Africa & India (CEMEA&I) 'jp': 'api.oviss.jp.fujitsu.com', # for Japan 'sg': 'api.globalcloud.sg.fujitsu.com', # for Singapore, Malaysia, Indonesia, Thailand and Vietnam 'uk': 'api.globalcloud.uk.fujitsu.com', # for the UK and Ireland (UK&I) 'us': 'api.globalcloud.us.fujitsu.com', # for the Americas 'test': 'test', # for local client tests with test fixtures #'fake': 'fake', # for local client tests with fake updates etc. ? 'relay': 'relay', # for remote connection via relay API server } class FGCPServerError(FGCPError): pass def FGCPGetServerConnection(key_file='client.pem', region='de'): if region == 'test': # connect to test API server for local testing # format: region = 'test' return FGCPTestServerWithFixtures() elif region.startswith('relay='): # connect to relay API server for remote connection # format: region = 'relay=http://127.0.0.1:8000/cgi-bin/fgcp_relay.py' relay = region.split('=').pop() from urlparse import urlparse url = urlparse(relay) # TODO: secure access to relay server in some other way, e.g. Basic Auth, OAuth, ... if url.scheme == 'https': return FGCPRelayServer(url.hostname, port=url.port, path=url.path) else: return FGCPUnsecureRelayServer(url.hostname, port=url.port, path=url.path) elif region in FGCP_REGIONS: # connect to real API server # format: region = 'uk' host = FGCP_REGIONS[region] # use the same PEM file for cert and key return FGCPRealServer(host, key_file=key_file, cert_file=key_file) else: raise FGCPServerError('INVALID_REGION', 'Region %s does not exist' % region) class FGCPRealServer(httplib.HTTPSConnection): """ Connect to the real API server for the Fujitsu Global Cloud Platform in this region """ pass class FGCPRelayServer(httplib.HTTPSConnection): """ Connect via some relay API server for remote connections, e.g. for Google App Engine """ _relay_host = None _relay_port = None _relay_path = None def __init__(self, host, port=None, path=None, strict=None): # TODO: we do not support key_file and cert_file here, so we connect via a relay server self._relay_host = host self._relay_port = port self._relay_path = path httplib.HTTPSConnection.__init__(self, host, port=port, strict=strict) def connect(self): return httplib.HTTPSConnection.connect(self) def request(self, method, url, body=None, headers={}): # TODO: fix request return httplib.HTTPSConnection.request(self, method, self._relay_path, body, headers) def getresponse(self): # TODO: fix response # TODO: fix response.read() return httplib.HTTPSConnection.getresponse(self) class FGCPUnsecureRelayServer(httplib.HTTPConnection): """ Connect via some relay API server for remote connections, e.g. for localhost """ _relay_host = None _relay_port = None _relay_path = None def __init__(self, host, port=None, path=None, strict=None): # TODO: we do not support key_file and cert_file here, so we connect via a relay server self._relay_host = host self._relay_port = port self._relay_path = path httplib.HTTPConnection.__init__(self, host, port=port) def connect(self): return httplib.HTTPConnection.connect(self) def request(self, method, url, body=None, headers={}): # TODO: fix request return httplib.HTTPConnection.request(self, method, self._relay_path, body, headers) def getresponse(self): # TODO: fix response # TODO: fix response.read() return httplib.HTTPConnection.getresponse(self) class FGCPTestServer: status = 200 reason = 'OK' _testid = None def __init__(self, *args, **kwargs): pass def request(self, method, uri, body, headers): pass def getresponse(self): return self def read(self): return """<?xml version="1.0" encoding="UTF-8"?> <Response xmlns="http://apioviss.jp.fujitsu.com"> <responseMessage>Processing was completed.</responseMessage> <responseStatus>SUCCESS</responseStatus> </Response> """ def close(self): pass def set_testid(self, testid): self._testid = testid class FGCPTestServerWithFixtures(FGCPTestServer): """ Connect to this test API server for local tests - updates are not supported >>> from fgcp.resource import FGCPVDataCenter >>> vdc = FGCPVDataCenter('client.pem', 'test') >>> vsystem = vdc.get_vsystem('Demo System') >>> vsystem.show_status() #doctest: +NORMALIZE_WHITESPACE Status Overview for VSystem Demo System VSystem Demo System NORMAL PublicIP 80.70.163.172 ATTACHED Firewall Firewall RUNNING LoadBalancer SLB1 192.168.0.211 RUNNING VServer WebApp1 192.168.0.13 RUNNING VServer DB1 192.168.1.12 RUNNING VDisk DISK1 NORMAL VServer WebApp2 192.168.0.15 RUNNING . """ _path = 'tests/fixtures' _file = None def __init__(self, *args, **kwargs): self._path = os.path.join('tests', 'fixtures') if not os.path.isdir(self._path): raise FGCPServerError('INVALID_PATH', 'Path %s does not exist' % self._path) def request(self, method, uri, body, headers): if self._testid is None: raise FGCPServerError('INVALID_PATH', 'Invalid test identifier') # check if we have a request file self._file = os.path.join(self._path, '%s.request.xml' % self._testid) if not os.path.isfile(self._file): print body raise FGCPServerError('INVALID_PATH', 'File %s does not exist' % self._file) # compare body with request file f = open(self._file, 'rb') data = f.read() f.close() if data != body: raise FGCPServerError('INVALID_REQUEST', 'Request for test %s does not match test fixture:\n\ Current body:\n\ ====\n\ %s\n\ ====\n\ Test fixture:\n\ ====\n\ %s\n\ ====\n' % (self._testid, body, data)) return def getresponse(self): # add some delay to make it more realistic time.sleep(0.3) # check if we have a response file self._file = os.path.join(self._path, '%s.response.xml' % self._testid) if os.path.exists(self._file): self.status = 200 self.reason = 'OK' else: self.status = 404 self.reason = 'File %s does not exist' % self._file return self def read(self): # send back the response file f = open(self._file) data = f.read() f.close() # TODO: transform status if necessary ? return data def close(self): self._file = None return #========================================================================= def save_request(self, testid, body): # sanitize accesskeyid and signature for test fixtures p = re.compile('<AccessKeyId>[^<]+</AccessKeyId>') body = p.sub('<AccessKeyId>...</AccessKeyId>', body) p = re.compile('<Signature>[^<]+</Signature>') body = p.sub('<Signature>...</Signature>', body) # save request in tests/fixtures f = open(os.path.join('tests', 'fixtures', '%s.request.xml' % testid), 'wb') f.write(body) f.close() def save_response(self, testid, data): # sanitize initialPassword for test fixtures :-) if testid.startswith('GetVServerInitialPassword'): p = re.compile('<initialPassword>[^<]+</initialPassword>') data = p.sub('<initialPassword>...</initialPassword>', data) # save response in tests/fixtures f = open(os.path.join('tests', 'fixtures', '%s.response.xml' % testid), 'wb') f.write(data) f.close() class FGCPTestServerWithRegistry(FGCPTestServer): _vdc = None def __init__(self, filePath='fgcp_demo_system.txt'): if not os.path.isfile(filePath): raise FGCPServerError('INVALID_PATH', 'File %s does not exist' % filePath) # create registry with dummy VDataCenter from fgcp.resource import FGCPVDataCenter self._vdc = FGCPVDataCenter() self._vdc.vsystems = [] # load demo vsystem from file design = self._vdc.get_vsystem_design() design.load_file(filePath) # save demo vsystem in registry self._vdc.vsystems.append(design.vsystem) if __name__ == "__main__": import doctest doctest.testmod()
Python
#!/usr/bin/python # # Copyright (C) 2011 Michel Dalle # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ Client Methods for the Fujitsu Global Cloud Platform (FGCP) Example: [see tests/test_client.py for more examples] # Connect with your client certificate to region 'uk' from fgcp.client import FGCPClient client = FGCPClient('client.pem', 'uk') # Call custom client methods client.ShowSystemStatus() The client methods below are organized by client role, i.e. Monitor, Operator, Designer and Client. Note: with version 1.0.x and later of the library, most of these client methods can now directly be replaced by corresponding resource actions. """ import time from fgcp.command import FGCPCommand from fgcp import FGCPError class FGCPClientError(FGCPError): pass class FGCPMonitor(FGCPCommand): """ FGCP Monitoring Methods """ _vdc = None def getvdc(self): if self._vdc is None: # get a new VDataCenter object from fgcp.resource import FGCPVDataCenter self._vdc = FGCPVDataCenter() # link it to the current client self._vdc._proxy = self # cosmetic for repr(vdc) self._vdc.config = '%s:%s' % (self.region, self.key_file) return self._vdc def FindSystemByName(self, vsysName): """ Find VSystem by vsysName vsystem = vdc.get_vsystem(vsysName) """ vdc = self.getvdc() return vdc.get_vsystem(vsysName) def GetSystemInventory(self, vsysName=None): """ Get VSystem inventory (by vsysName) vsystems = vdc.list_vsystems() inventory = vsystem.get_inventory() """ vdc = self.getvdc() if vsysName is None: inventory = {} inventory['vsys'] = {} vsystems = vdc.list_vsystems() if len(vsystems) < 1: self.show_output('No VSystems are defined') return for vsystem in vsystems: inventory['vsys'][vsystem.vsysName] = vsystem.get_inventory() return inventory else: vsystem = vdc.get_vsystem(vsysName) return vsystem.get_inventory() def GetSystemStatus(self, vsysName=None, verbose=None): """ Get the overall system status (for a particular VSystem) status = vsystem.get_status() """ vdc = self.getvdc() # set output old_verbose = self.set_verbose(verbose) if vsysName is None: self.show_output('Show System Status for all VSystems') inventory = {} inventory['vsys'] = {} vsystems = vdc.list_vsystems() if len(vsystems) < 1: self.show_output('No VSystems are defined') return for vsystem in vsystems: inventory['vsys'][vsystem.vsysName] = vsystem.get_status() else: vsystem = vdc.get_vsystem(vsysName) inventory = vsystem.get_status() # reset output self.set_verbose(old_verbose) # return inventory with status return inventory def ShowSystemStatus(self, vsysName=None, sep='\t'): """ Show the overall system status (for a particular VSystem) vdc.show_vsystem_status() vsystem.show_status() """ vdc = self.getvdc() if vsysName is None: vdc.show_vsystem_status(sep) else: vsystem = vdc.get_vsystem(vsysName) vsystem.show_status(sep) class FGCPOperator(FGCPMonitor): """ FGCP Operator Methods """ def check_status(self, done_status, pass_status, status_method, *args): """ Call status_method(*args) to see if we get done_status, or something other than pass_status Obsolete - included in resource actions """ if not hasattr(self, status_method): raise FGCPClientError('ILLEGAL_METHOD', 'Invalid method %s for checking status' % status_method) check_status = getattr(self, status_method, None) if not callable(check_status): raise FGCPClientError('ILLEGAL_METHOD', 'Invalid method %s for checking status' % status_method) if isinstance(done_status, str): done_list = [done_status] else: done_list = done_status if isinstance(pass_status, str): pass_list = [pass_status] else: pass_list = pass_status status = check_status(*args) if status in done_list: # we're already done so return the status return status elif status in pass_list: # we can continue with whatever needs doing return else: raise FGCPClientError('ILLEGAL_STATE', 'Invalid status %s for %s' % (status, status_method)) def wait_for_status(self, done_status, wait_status, status_method, *args): """ Call status_method(*args) repeatedly until we get done_status (or something else than wait_status) Obsolete - included in resource actions """ if not hasattr(self, status_method): raise FGCPClientError('ILLEGAL_METHOD', 'Invalid method %s for checking status' % status_method) check_status = getattr(self, status_method, None) if not callable(check_status): raise FGCPClientError('ILLEGAL_METHOD', 'Invalid method %s for checking status' % status_method) if isinstance(done_status, str): done_list = [done_status] else: done_list = done_status if isinstance(wait_status, str): wait_list = [wait_status] else: wait_list = wait_status # wait until we get the done_status - TODO: add some timeout while True: time.sleep(10) status = check_status(*args) if status in done_list: return status elif status in wait_list: pass else: raise FGCPClientError('ILLEGAL_STATE', '%s returned unexpected status %s while %s' % (status_method, status, wait_status)) return status def StartVServerAndWait(self, vsysId, vserverId): """ Start VServer and wait until it's running result = vserver.start(wait=True) """ vdc = self.getvdc() vsystem = vdc.get_vsystem(vsysId) vserver = vsystem.get_vserver(vserverId) # start vserver status = vserver.start(wait=True) return status def StopVServerAndWait(self, vsysId, vserverId, force=None): """ Stop VServer and wait until it's stopped result = vserver.stop(wait=True, force=None) """ vdc = self.getvdc() vsystem = vdc.get_vsystem(vsysId) vserver = vsystem.get_vserver(vserverId) # stop vserver status = vserver.stop(wait=True, force=force) return status def StartEFMAndWait(self, vsysId, efmId): """ Start EFM and wait until it's running result = loadbalancer.start(wait=True) """ vdc = self.getvdc() vsystem = vdc.get_vsystem(vsysId) try: efm = vsystem.get_loadbalancer(efmId) except: efm = vsystem.get_firewall(efmId) # start efm status = efm.start(wait=True) return status def StopEFMAndWait(self, vsysId, efmId): """ Stop EFM and wait until it's stopped result = loadbalancer.stop(wait=True) """ vdc = self.getvdc() vsystem = vdc.get_vsystem(vsysId) try: efm = vsystem.get_loadbalancer(efmId) except: efm = vsystem.get_firewall(efmId) # stop efm status = efm.stop(wait=True) return status def AttachPublicIPAndWait(self, vsysId, publicIp): """ Attach PublicIP and wait until it's attached result = publicip.attach(wait=True) """ vdc = self.getvdc() vsystem = vdc.get_vsystem(vsysId) ip = vsystem.get_publicip(publicIp) # attach publicip status = ip.attach(wait=True) return status def DetachPublicIPAndWait(self, vsysId, publicIp): """ Detach PublicIP and wait until it's detached result = publicip.detach(wait=True) """ vdc = self.getvdc() vsystem = vdc.get_vsystem(vsysId) ip = vsystem.get_publicip(publicIp) # detach publicip status = ip.detach(wait=True) return status def BackupVDiskAndWait(self, vsysId, vdiskId): """ Take Backup of VDisk and wait until it's finished (this might take a while) result = vdisk.backup(wait=True) """ vdc = self.getvdc() vsystem = vdc.get_vsystem(vsysId) vdisk = vsystem.get_vdisk(vdiskId) # backup vdisk status = vdisk.backup(wait=True) return status def BackupVServerAndRestart(self, vsysId, vserverId): """ Backup all VDisks of a VServer and restart the VServer (this might take a while) result = vserver.backup(wait=True) for vdisk in vserver.list_vdisks(): result = vdisk.backup(wait=True) result = vserver.start(wait=True) """ vdc = self.getvdc() vsystem = vdc.get_vsystem(vsysId) vserver = vsystem.get_vserver(vserverId) # stop server and backup system disk status = vserver.backup(wait=True) # backup other vdisks for vdisk in vserver.list_vdisks(): status = vdisk.backup(wait=True) # start server status = vserver.start(wait=True) return status # TODO: set expiration date + max. number def CleanupBackups(self, vsysId, vdiskId=None): """ Clean up old VDisk backups e.g. to minimize disk space result = vdisk.cleanup_backups(max_num=100, max_age=None) """ vdc = self.getvdc() vsystem = vdc.get_vsystem(vsysId) if vdiskId is None: vdisks = vsystem.list_vdisks() for vdisk in vdisks: vdisk.cleanup_backups() else: vdisk = vsystem.get_vdisk(vdiskId) vdisk.cleanup_backups() def StartSystem(self, vsysName, verbose=None): """ Start VSystem and wait until all VServers and EFMs are started (TODO: define start sequence for vservers) vsystem.boot(wait=True) vsystem.start(wait=True) """ vdc = self.getvdc() vsystem = vdc.get_vsystem(vsysName) # Set output old_verbose = self.set_verbose(verbose) vsystem.boot(wait=True) vsystem.start(wait=True) # Reset output self.set_verbose(old_verbose) def StopSystem(self, vsysName, verbose=None): """ Stop VSystem and wait until all VServers and EFMs are stopped (TODO: define stop sequence for vservers) vsystem.stop(wait=True) vsystem.shutdown(wait=True) """ vdc = self.getvdc() vsystem = vdc.get_vsystem(vsysName) # Set output old_verbose = self.set_verbose(verbose) vsystem.stop(wait=True) vsystem.shutdown(wait=True) # Reset output self.set_verbose(old_verbose) class FGCPDesigner(FGCPOperator): """ FGCP Designer Methods """ def FindDiskImageByName(self, diskimageName): """ Find DiskImage by diskimageName diskimage = vdc.get_diskimage(diskimageName) """ vdc = self.getvdc() diskimage = vdc.get_diskimage(diskimageName) return diskimage def FindVSYSDescriptorByName(self, vsysdescriptorName): """ Find VSYSDescriptor by vsysdescriptorName vsysdescriptor = vdc.get_vsysdescriptor(vsysdescriptorName) """ vdc = self.getvdc() vsysdescriptor = vdc.get_vsysdescriptor(vsysdescriptorName) return vsysdescriptor def FindServerTypeByName(self, name): """ Find ServerType by name servertype = vdc.get_servertype(name) """ #vdc = self.getvdc() #servertype = vdc.get_servertype(name) return name def CreateSystem(self, vsysName, vsysdescriptorName, verbose=None): """ Create VSystem based on descriptor and wait until it's deployed vsysId = vdc.create_vsystem(vsysName, vsysdescriptorName, wait=True) """ vdc = self.getvdc() # Set output old_verbose = self.set_verbose(verbose) # Create VSystem vsysId = vdc.create_vsystem(vsysName, vsysdescriptorName, wait=True) # Reset output self.set_verbose(old_verbose) return vsysId def DestroySystem(self, vsysName, verbose=None): """ Destroy VSystem after stopping all VServers and EFMs vdc.destroy_vsystem(vsysName, wait=True) """ vdc = self.getvdc() # Set output old_verbose = self.set_verbose(verbose) # Destroy VSystem vdc.destroy_vsystem(vsysName, wait=True) # Reset output self.set_verbose(old_verbose) def LoadSystemDesign(self, filePath, verbose=None): """ Load VSystem design from file, for use e.g. in ConfigureSystem() design = vdc.get_vsystem_design() design.load_file(filePath) #design.build_vsystem(vsysName) """ vdc = self.getvdc() # Set output old_verbose = self.set_verbose(verbose) # Load system design from file design = vdc.get_vsystem_design() design.load_file(filePath) # Reset output self.set_verbose(old_verbose) # Return system design return design def ConfigureSystem(self, vsysName, systemDesign, verbose=None): """ Configure VSystem based on some systemDesign - see LoadSystemDesign() #design = vdc.get_vsystem_design() #design.load_file(filePath) design.build_vsystem(vsysName) """ # Set output old_verbose = self.set_verbose(verbose) # Build VSystem systemDesign.build_vsystem(vsysName) # Reset output self.set_verbose(old_verbose) def SaveSystemDesign(self, vsysName, filePath, verbose=None): """ Save (fixed parts of) VSystem design to file design = vdc.get_vsystem_design() design.load_vsystem(vsysName) design.save_file(filePath) """ vdc = self.getvdc() # Set output old_verbose = self.set_verbose(verbose) # Save system design to file design = vdc.get_vsystem_design() design.load_vsystem(vsysName) design.save_file(filePath) # Reset output self.set_verbose(old_verbose) class FGCPClient(FGCPDesigner): """ FGCP Client Methods Example: # Connect with your client certificate in region 'uk' from fgcp.client import FGCPClient client = FGCPClient('client.pem', 'uk') # Backup all VServers in some VSystem vsys = client.GetSystemInventory('Python API Demo System') for vserver in vsys.vservers: client.BackupVServerAndRestart(vsys.vsysId, vserver.vserverId) client.CleanupBackups(vsys.vsysId) # Note: you can also use all API commands from FGCPCommand() vsystems = client.ListVSYS() for vsys in vsystems: vsysconfig = client.GetVSYSConfiguration(vsys.vsysId) ... """ pass
Python
#!/usr/bin/python # # Copyright (C) 2012 Michel Dalle # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ Client API library for the Fujitsu Global Cloud Platform (FGCP) using XML-RPC API Version 2012-02-18 Requirements: this module uses gdata.tlslite.utils to create the key signature, see http://code.google.com/p/gdata-python-client/ for download and installation Caution: this is a development work in progress - please do not use for productive systems without adequate testing... """ __version__ = '1.3.2' class FGCPError(Exception): """ Exception class for FGCP Errors """ def __init__(self, status, message): self.status = status self.message = message def __str__(self): return '\nStatus: %s\nMessage: %s' % (self.status, self.message)
Python
#!/usr/bin/python # # Copyright (C) 2011 Michel Dalle # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ VSystem Design for the Fujitsu Global Cloud Platform (FGCP) Example: [see tests/test_resource.py for more examples] # Connect with your client certificate to region 'uk' from fgcp.resource import FGCPVDataCenter vdc = FGCPVDataCenter('client.pem', 'uk') # Get VSystem Design from an existing vsystem or file, and build a new vsystem with it (TODO) design = vdc.get_vsystem_design('Demo System') #design.load_file('fgcp_demo_system.txt') #design.build_vsystem('My New Demo System') #design.load_vsystem('Demo System') design.save_file('new_demo_system.txt') """ import time from fgcp import FGCPError from fgcp.resource import FGCPElement, FGCPResource, FGCPResourceError class FGCPDesignError(FGCPError): """ Exception class for FGCP Design Errors """ def __init__(self, status, message, resource=None): self.status = status self.message = message self.resource = resource def __str__(self): return '\nStatus: %s\nMessage: %s\nResource: %s' % (self.status, self.message, repr(self.resource)) class FGCPDesign(FGCPResource): """ FGCP VSystem Design """ _idname = 'vsysName' filePath = None vsysName = None vsystem = None def from_code(self, lines): # CHECKME: add line continuations before exec() !? try: # Note: FGCPElement().pformat() writes objects initialized with the right values exec 'from fgcp.resource import *\nvsystem = ' + lines.replace("\r\n", "\\\r\n") except: #raise FGCPDesignError('INVALID_FORMAT', 'File %s seems to have some syntax errors' % self.filePath) raise return vsystem def to_code(self, what): # FGCPElement().pformat() writes objects initialized with the right values return self.pformat(what) def from_yaml(self, lines): # TODO: import from yaml :-) from fgcp.resource import FGCPVSystem return FGCPVSystem(vsysName='TODO: import from yaml', description='This library does not support importing from yaml files yet') def to_yaml(self, what, depth=0, suffix=''): if isinstance(what, FGCPResource): # convert to dict recursively first what = self.to_var(what) L = [] prefix = ' ' * depth # See http://yaml.org/spec/1.1/ # Mapping of ... if isinstance(what, dict): keylist = what.keys() keylist.sort() for key in keylist: if key == '_class': L.append('%s# %s%s' % (prefix, what[key], suffix)) # ... mappings elif isinstance(what[key], dict): L.append('%s%s: {' % (prefix, key)) # CHECKME: add , after each entry ! L.append(self.to_yaml(what[key], depth + 1, ',')) L.append('%s}%s' % (prefix, suffix)) # ... sequences elif isinstance(what[key], list): L.append('%s%s:' % (prefix, key)) L.append(self.to_yaml(what[key], depth + 1)) # CHECKME: no suffix here ??? # ... scalars else: L.append('%s%s: %s%s' % (prefix, key, what[key], suffix)) # Sequence of ... elif isinstance(what, list): if len(what) == 0: return # ... mappings elif isinstance(what[0], dict): for item in what: if '_class' in item: L.append('%s- # %s' % (prefix, item['_class'])) del item['_class'] else: L.append('%s-' % prefix) L.append(self.to_yaml(item, depth + 1)) # ... sequences elif isinstance(what[0], list): for item in what: L.append('%s- [' % prefix) # CHECKME: add , after each entry for entry in item: L.append(self.to_yaml(entry, depth + 1) + ',') L.append('%s]' % prefix) # ... scalars else: for item in what: L.append('%s- %s' % (prefix, item)) # Scalar else: L.append('%s%s' % (prefix, what)) return '\r\n'.join(L) def from_var(self, what, parent=None): if isinstance(what, dict): # convert to class based on _class if '_class' not in what: raise FGCPDesignError('INVALID_FORMAT', 'The dictionary does not contain a _class key:\n%s' % repr(what), self) new_what = what['_class']() # CHECKME: add parent and proxy to the FGCP Resource new_what.setparent(parent) keylist = what.keys() for key in keylist: if key == '_class': continue setattr(new_what, key, self.from_var(what[key], new_what)) return new_what elif isinstance(what, list): new_what = [] for item in what: new_what.append(self.from_var(item, parent)) return new_what else: # str, int, float etc. are returned as is return what def to_var(self, what): if isinstance(what, FGCPElement): # convert to dict and add _class new_what = {'_class': type(what).__name__} keylist = what.__dict__.keys() for key in keylist: # skip internal attributes if key.startswith('_') and key != '_status': continue new_what[key] = self.to_var(what.__dict__[key]) return new_what elif isinstance(what, dict): new_what = {} keylist = what.keys() for key in keylist: # skip internal keys #if key.startswith('_'): # continue new_what[key] = self.to_var(what[key]) return new_what elif isinstance(what, list): new_what = [] for item in what: new_what.append(self.to_var(item)) return new_what else: # str, int, float etc. are returned as is return what def load_file(self, filePath): """ Load VSystem Design from file """ self.filePath = filePath self.show_output('Loading VSystem Design from file %s' % self.filePath) import os.path if self.filePath is None or not os.path.exists(self.filePath): raise FGCPDesignError('INVALID_PATH', 'File %s does not seem to exist' % self.filePath) f = open(self.filePath, 'r') lines = f.read() f.close() # check if we have something we need, i.e. a FGCPSys() instance or # FGCPVSystem comment line if lines.startswith('FGCPVSystem('): format = 'txt' vsystem = self.from_code(lines) elif lines.startswith('#'): format = 'yaml' # TODO :-) vsystem = self.from_yaml(lines) else: raise FGCPDesignError('INVALID_FORMAT', 'File %s does not seem to start with FGCPSystem(' % self.filePath) self.show_output('Loaded VSystem Design for %s from file %s' % (vsystem.vsysName, self.filePath)) try: # check if VDataCenter already has a vsystem with the same name found = self._parent.get_vsystem(vsystem.vsysName) self.show_output('CAUTION: you already have a VSystem called %s' % vsystem.vsysName) except FGCPResourceError: pass # set the vsystem parent to the vdatacenter vsystem.setparent(self._parent) # return vsystem self.vsystem = vsystem self.vsysName = self.vsystem.vsysName return self.vsystem def load_vsystem(self, vsystem): """ Load VSystem Design from vsystem """ # let VDataCenter find the right vsystem self.vsystem = self._parent.get_vsystem(vsystem) self.show_output('Loading VSystem Design from vsystem %s' % self.vsystem.vsysName) # update vsystem inventory if necessary self.vsystem.get_inventory() self.vsysName = self.vsystem.vsysName return self.vsystem def build_vsystem(self, vsysName=None, filePath=None): """ Build new VSystem based on loaded VSystem Design """ if filePath is not None: self.load_file(filePath) # check that we have a vsystem design in memory if self.vsystem is None: raise FGCPDesignError('INVALID_VSYSTEM', 'No VSystem Design has been loaded') if vsysName is None: self.vsysName = 'New %s' % self.vsystem.vsysName else: self.vsysName = vsysName self.show_output('Building VSystem %s based on %s' % (self.vsysName, self.vsystem.vsysName)) # 1. check that the base descriptor exists vsysdescriptor = self._parent.get_vsysdescriptor(self.vsystem.baseDescriptor) # 2. check if the new vsystem already exists try: new_vsystem = self._parent.get_vsystem(self.vsysName) except FGCPResourceError: # 3. create it if necessary vsysId = vsysdescriptor.create_vsystem(self.vsysName, wait=True) # retrieve the newly created vsystem new_vsystem = self._parent.get_vsystem(self.vsysName) # 4. boot vsystem if necessary new_vsystem.boot(wait=True) # 5. allocate more publicips as needed self.show_output('Checking PublicIPs') new_ips = len(new_vsystem.publicips) orig_ips = len(self.vsystem.publicips) if new_ips < orig_ips: while new_ips < orig_ips: new_vsystem.allocate_publicip(wait=True) new_ips = len(new_vsystem.publicips) # 6. attach publicips if necessary for publicip in new_vsystem.publicips: publicip.attach(wait=True) # 7. find missing vservers based on vserverName self.show_output('Checking VServers') new_vservers = {} for vserver in new_vsystem.vservers: new_vservers[vserver.vserverName] = vserver orig_vservers = {} for vserver in self.vsystem.vservers: orig_vservers[vserver.vserverName] = vserver for vserverName in orig_vservers: if vserverName in new_vservers: continue self.show_output('Creating VServer %s: %s' % (vserverName, orig_vservers[vserverName])) servertype = orig_vservers[vserverName].vserverType # note: use the diskimage name here, rather than the diskimage id diskimage = orig_vservers[vserverName].diskimageName # get the last part of the newtworkId as vnet (= DMZ, SECURE1, SECURE2 etc.) vnet = orig_vservers[vserverName].vnics[0].getid().split('-').pop() self.show_output('with parameters: %s, %s, %s, %s' % (vserverName, servertype, diskimage, vnet)) # 8. let the new vsystem create the vserver - it will convert the parameters correctly new_vsystem.create_vserver(vserverName, servertype, diskimage, vnet, wait=True) # 9. find missing vdisks based on vdiskName self.show_output('Checking VDisks') new_vdisks = {} for vdisk in new_vsystem.vdisks: new_vdisks[vdisk.vdiskName] = vdisk orig_vdisks = {} for vdisk in self.vsystem.vdisks: orig_vdisks[vdisk.vdiskName] = vdisk for vdiskName in orig_vdisks: if vdiskName in new_vdisks: continue self.show_output('Creating VDisk %s: %s' % (vdiskName, orig_vdisks[vdiskName])) size = orig_vdisks[vdiskName].size self.show_output('with parameters: %s, %s' % (vdiskName, size)) # 10. let the new vsystem create the vdisk - it will convert the parameters correctly new_vsystem.create_vdisk(vdiskName, size, wait=True) # 11. find missing loadbalancers based on efmName self.show_output('Checking LoadBalancers') new_loadbalancers = {} for loadbalancer in new_vsystem.loadbalancers: new_loadbalancers[loadbalancer.efmName] = loadbalancer orig_loadbalancers = {} for loadbalancer in self.vsystem.loadbalancers: orig_loadbalancers[loadbalancer.efmName] = loadbalancer for efmName in orig_loadbalancers: if efmName in new_loadbalancers: continue self.show_output('Creating LoadBalancer %s: %s' % (efmName, orig_loadbalancers[efmName])) orig_loadbalancers[efmName].pprint() slbVip = orig_loadbalancers[efmName].slbVip self.show_output('with parameters: %s, %s' % (efmName, slbVip)) # 12. let the new vsystem create the loadbalancer - it will convert the parameters correctly # CHECKME: the only way to know in which vnet this SLB is located, is via the slbVip (which is translated to the efmName in design files) ??? # FIXME; assume they're all in the DMZ at the moment !? new_vsystem.create_loadbalancer(efmName, 'DMZ', wait=True) # 13. refresh vserver and vdisk list new_vsystem.get_inventory(refresh=True) # TODO: attach the new vdisk to the right vserver !? # TODO: remap FW and SLB rules and update them !? self.show_output('Configured VSystem %s' % self.vsysName) def save_file(self, filePath, format='txt'): """ Save VSystem Design to file """ self.filePath = filePath import os.path if self.filePath is None or os.path.isdir(self.filePath): raise FGCPDesignError('INVALID_PATH', 'File %s is invalid for output' % self.filePath) # check that we have a vsystem design in memory if self.vsystem is None: raise FGCPDesignError('INVALID_VSYSTEM', 'No VSystem Design has been loaded') # update vsystem inventory if necessary self.vsystem.get_inventory() self.show_output('Saving VSystem Design for %s to file %s' % (self.vsystem.vsysName, self.filePath)) # CHECKME: is description always the name correspoding to baseDescriptor ? seenip = {} # replace addresses and other variable information idx = 1 #new_publicips = [] for publicip in self.vsystem.publicips: seenip[publicip.address] = 'publicip.%s' % idx idx += 1 #publicip.address = 'xxx.xxx.xxx.xxx' #new_publicips.append(publicip) #self.vsystem.publicips = new_publicips from fgcp.resource import FGCPFirewall new_firewalls = [] for firewall in self.vsystem.firewalls: # in case we didn't load this from file if getattr(firewall, 'nat', None) is None: firewall.get_nat_rules() if getattr(firewall, 'dns', None) is None: firewall.get_dns() if getattr(firewall, 'directions', None) is None: firewall.get_policies(from_zone=None, to_zone=None) new_firewalls.append(firewall) self.vsystem.firewalls = new_firewalls #from fgcp.resource import FGCPLoadBalancer new_loadbalancers = [] for loadbalancer in self.vsystem.loadbalancers: seenip[loadbalancer.slbVip] = loadbalancer.efmName #loadbalancer.slbVip = 'xxx.xxx.xxx.xxx' # in case we didn't load this from file if getattr(loadbalancer, 'groups', None) is None: loadbalancer.get_rules() new_loadbalancers.append(loadbalancer) self.vsystem.loadbalancers = new_loadbalancers # get mapping of diskimage id to name diskimages = self._parent.list_diskimages() imageid2name = {} for diskimage in diskimages: imageid2name[diskimage.diskimageId] = diskimage.diskimageName new_vservers = [] for vserver in self.vsystem.vservers: # CHECKME: use diskimage name as reference across regions !? setattr(vserver, 'diskimageName', imageid2name[vserver.diskimageId]) #new_vnics = [] for vnic in vserver.vnics: seenip[vnic.privateIp] = vserver.vserverName #vnic.privateIp = 'xxx.xxx.xxx.xxx' #new_vnics.append(vnic) #vserver.vnics = new_vnics #new_vdisks = [] #for vdisk in vserver.vdisks: # new_vdisks.append(vdisk) #vserver.vdisks = new_vdisks new_vservers.append(vserver) self.vsystem.vservers = new_vservers #new_vdisks = [] #for vdisk in self.vsystem.vdisks: # new_vdisks.append(vdisk) #self.vsystem.vdisks = new_vdisks # Prepare for output - FGCPElement().pformat() writes objects initialized with the right values if format == 'txt': lines = self.to_code(self.vsystem) else: lines = self.to_yaml(self.vsystem) # Replace vsysId and creator everywhere (including Id's) lines = lines.replace(self.vsystem.vsysId, 'DEMO-VSYSTEM') lines = lines.replace(self.vsystem.creator, 'DEMO') # CHECKME: replace ip addresses with names everywhere, including firewall policies and loadbalancer rules for ip in seenip.keys(): lines = lines.replace(ip, seenip[ip]) # CHECKME: fix from=... issue for firewall policies if format == 'txt': lines = lines.replace('from=', 'from_zone=') lines = lines.replace('to=', 'to_zone=') # Write configuration to file f = open(self.filePath, 'wb') f.write(lines) f.close() self.show_output('Saved VSystem Design for %s to file %s' % (self.vsystem.vsysName, self.filePath))
Python
#!/usr/bin/python # # Copyright (C) 2012 Michel Dalle # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ API Commands to the Fujitsu Global Cloud Platform (FGCP) Example: [see tests/test_api.py for more examples] # Connect with your client certificate to region 'uk' from fgcp.command import FGCPCommand api_proxy = FGCPCommand('client.pem', 'uk') # Call standard API commands with identifiers vsystems = api_proxy.ListVSYS() for vsys in vsystems: status = api_proxy.GetVSYSStatus(vsys.vsysId) vsysconfig = api_proxy.GetVSYSConfiguration(vsys.vsysId) for vserver in vsysconfig.vservers: status = api_proxy.GetVServerStatus(vsys.vsysId, vserver.vserverId) ... """ from fgcp import FGCPError from fgcp.connection import FGCPProxyServer, FGCPResponseError class FGCPCommandError(FGCPError): pass class FGCPCommand(FGCPProxyServer): """ Proxy for FGCP API Commands """ def set_verbose(self, verbose=None): """ Show output (1), status checks (2) or nothing (0) """ old_verbose = self.verbose if verbose is None: # don't change current setting pass elif verbose > 1: # start showing output + status self.verbose = 2 elif verbose == 1: # start showing output self.verbose = 1 else: # stop showing output self.verbose = 0 return old_verbose def show_output(self, text=''): if self.verbose > 0: print text def show_status(self, text=''): if self.verbose > 1: print text def ListVSYSDescriptor(self): """ Usage: vsysdescriptors = proxy.ListVSYSDescriptor() """ result = self.do_action('ListVSYSDescriptor') return result.vsysdescriptors def GetVSYSDescriptorConfiguration(self, vsysDescriptorId): """ Usage: vsysdescriptorconfig = proxy.GetVSYSDescriptorConfiguration(vsysdescriptor.vsysdescriptorId) """ result = self.do_action('GetVSYSDescriptorConfiguration', {'vsysDescriptorId': vsysDescriptorId}) return result.vsysdescriptor def GetVSYSDescriptorAttributes(self, vsysDescriptorId): """ Usage: vsysdescriptorattr = proxy.GetVSYSDescriptorAttributes(vsysdescriptor.vsysdescriptorId) """ result = self.do_action('GetVSYSDescriptorAttributes', {'vsysDescriptorId': vsysDescriptorId}) return result.vsysdescriptor def UpdateVSYSDescriptorAttribute(self, vsysDescriptorId, updateLcId, attributeName, attributeValue): result = self.do_action('UpdateVSYSDescriptorAttribute', {'vsysDescriptorId': vsysDescriptorId, 'updateLcId': updateLcId, 'attributeName': attributeName, 'attributeValue': attributeValue}) return result.responseStatus def UnregisterVSYSDescriptor(self, vsysDescriptorId): result = self.do_action('UnregisterVSYSDescriptor', {'vsysDescriptorId': vsysDescriptorId}) return result.responseStatus def RegisterPrivateVSYSDescriptor(self, vsysId, name, description, keyword, vservers): """Usage: vsys = proxy.GetSystemInventory('My Existing VSYS') proxy.RegisterPrivateVSYSDescriptor(vsys.vsysId, 'My New Template', 'This is a new template based on my existing VSYS', 'some key words', vsys.vservers) """ filename = 'dummy.xml' vsysDescriptorXML = self._get_vsysDescriptorXML(vsysId, name, description, keyword, vservers) result = self.do_action('RegisterPrivateVSYSDescriptor', {'vsysDescriptorXMLFilePath': filename}, {'name': 'vsysDescriptorXMLFilePath', 'filename': filename, 'body': vsysDescriptorXML}) return result.responseStatus def _get_vsysDescriptorXML(self, vsysId, name, description, keyword, vservers): CRLF = '\r\n' L = [] L.append('<?xml version="1.0" encoding="UTF-8"?>') L.append('<Request>') L.append(' <vsysId>%s</vsysId>' % vsysId) L.append(' <locales>') L.append(' <locale>') L.append(' <lcid>en</lcid>') L.append(' <name>%s</name>' % name) L.append(' <description>%s</description>' % description) L.append(' </locale>') L.append(' </locales>') L.append(' <keyword>%s</keyword>' % keyword) L.append(' <servers>') if vservers is not None and len(vservers) > 0: # CHECKME: do we need to add name & description for loadbalancers too ? for vserver in vservers: L.append(' <server>') # CHECKME: and what should we use for the id here - is it mandatory ? L.append(' <id>%s</id>' % vserver.vserverId) L.append(' <locales>') L.append(' <locale>') L.append(' <lcid>en</lcid>') L.append(' <name>%s</name>' % vserver.vserverName) # CHECKME: what should we use for description ? descr = vserver.vserverName + ' on ' + vserver.vserverType + ' server type' L.append(' <description>%s</description>' % descr) L.append(' </locale>') L.append(' </locales>') L.append(' </server>') L.append(' </servers>') L.append('</Request>') return CRLF.join(L) def UnregisterPrivateVSYSDescriptor(self, vsysDescriptorId): result = self.do_action('UnregisterPrivateVSYSDescriptor', {'vsysDescriptorId': vsysDescriptorId}) return result.responseStatus def ListPublicIP(self, vsysId=None): """ Usage: publicips = proxy.ListPublicIP() """ result = self.do_action('ListPublicIP', {'vsysId': vsysId}) return result.publicips def GetPublicIPAttributes(self, publicIp): """ Usage: publicipattr = proxy.GetPublicIPAttributes(publicip.address) """ result = self.do_action('GetPublicIPAttributes', {'publicIp': publicIp}) return result.publicips def GetPublicIPStatus(self, publicIp): """ Usage: status = proxy.GetPublicIPStatus(publicip.address) """ result = self.do_action('GetPublicIPStatus', {'publicIp': publicIp}) # show status if requested, e.g. for wait operations self.show_status(result.publicipStatus) return result.publicipStatus def AllocatePublicIP(self, vsysId): result = self.do_action('AllocatePublicIP', {'vsysId': vsysId}) return result.responseStatus def AttachPublicIP(self, vsysId, publicIp): result = self.do_action('AttachPublicIP', {'vsysId': vsysId, 'publicIp': publicIp}) return result.responseStatus def DetachPublicIP(self, vsysId, publicIp): result = self.do_action('DetachPublicIP', {'vsysId': vsysId, 'publicIp': publicIp}) return result.responseStatus def FreePublicIP(self, vsysId, publicIp): result = self.do_action('FreePublicIP', {'vsysId': vsysId, 'publicIp': publicIp}) return result.responseStatus def GetAddressRange(self): """ Usage: addressranges = proxy.GetAddressRange() """ result = self.do_action('GetAddressRange') if hasattr(result, 'addressranges'): return result.addressranges def CreateAddressPool(self, pipFrom=None, pipTo=None): result = self.do_action('CreateAddressPool', {'pipFrom': pipFrom, 'pipTo': pipTo}) return result def AddAddressRange(self, pipFrom, pipTo): result = self.do_action('AddAddressRange', {'pipFrom': pipFrom, 'pipTo': pipTo}) return result.responseStatus def DeleteAddressRange(self, pipFrom, pipTo): result = self.do_action('DeleteAddressRange', {'pipFrom': pipFrom, 'pipTo': pipTo}) return result.responseStatus def ListDiskImage(self, serverCategory=None, vsysDescriptorId=None): """ Usage: diskimages = proxy.ListDiskImage() """ result = self.do_action('ListDiskImage', {'serverCategory': serverCategory, 'vsysDescriptorId': vsysDescriptorId}) return result.diskimages def GetDiskImageAttributes(self, diskImageId): """ Usage: diskimage = proxy.GetDiskImageAttributes(diskimage.diskimageId) """ result = self.do_action('GetDiskImageAttributes', {'diskImageId': diskImageId}) return result.diskimage def UpdateDiskImageAttribute(self, diskImageId, updateLcId, attributeName, attributeValue): result = self.do_action('UpdateDiskImageAttribute', {'diskImageId': diskImageId, 'updateLcId': updateLcId, 'attributeName': attributeName, 'attributeValue': attributeValue}) return result.responseStatus def RegisterPrivateDiskImage(self, vserverId, name, description): filename = 'dummy.xml' diskImageXML = self._get_diskImageXML(vserverId, name, description) result = self.do_action('RegisterPrivateDiskImage', {'diskImageXMLFilePath': filename}, {'name': 'diskImageXMLFilePath', 'filename': filename, 'body': diskImageXML}) return result.responseStatus def _get_diskImageXML(self, vserverId, name, description): CRLF = '\r\n' L = [] L.append('<?xml version="1.0" encoding="UTF-8"?>') L.append('<Request>') L.append(' <vserverId>%s</vserverId>' % vserverId) L.append(' <locales>') L.append(' <locale>') L.append(' <lcid>en</lcid>') L.append(' <name>%s</name>' % name) L.append(' <description>%s</description>' % description) L.append(' </locale>') L.append(' </locales>') L.append('</Request>') return CRLF.join(L) def UnregisterDiskImage(self, diskImageId): result = self.do_action('UnregisterDiskImage', {'diskImageId': diskImageId}) return result.responseStatus def ListServerType(self, diskImageId): """ Usage: servertypes = proxy.ListServerType(diskimage.diskimageId) """ result = self.do_action('ListServerType', {'diskImageId': diskImageId}) return result.servertypes def ListVSYS(self): """ Usage: vsystems = proxy.ListVSYS() """ result = self.do_action('ListVSYS') # CHECKME: initialize empty list if necessary if not hasattr(result, 'vsyss'): setattr(result, 'vsyss', []) return result.vsyss def GetVSYSConfiguration(self, vsysId): """ Usage: vsysconfig = proxy.GetVSYSConfiguration(vsys.vsysId) """ result = self.do_action('GetVSYSConfiguration', {'vsysId': vsysId}) # FIXME: we seem to have ghosts in VSYSConfiguration.publicips compared to the overall ListPublicIP(vsys.vsysId) ! setattr(result.vsys, 'publicips', self.ListPublicIP(vsysId)) return result.vsys def UpdateVSYSConfiguration(self, vsysId, configurationName, configurationValue): result = self.do_action('UpdateVSYSConfiguration', {'vsysId': vsysId, 'configurationName': configurationName, 'configurationValue': configurationValue}) return result.responseStatus def GetVSYSAttributes(self, vsysId): """ Usage: vsysattr = proxy.GetVSYSAttributes(vsys.vsysId) """ result = self.do_action('GetVSYSAttributes', {'vsysId': vsysId}) return result.vsys def UpdateVSYSAttribute(self, vsysId, attributeName, attributeValue): result = self.do_action('UpdateVSYSAttribute', {'vsysId': vsysId, 'attributeName': attributeName, 'attributeValue': attributeValue}) return result.responseStatus def GetVSYSStatus(self, vsysId): """ Usage: status = proxy.GetVSYSStatus(vsys.vsysId) """ result = self.do_action('GetVSYSStatus', {'vsysId': vsysId}) # show status if requested, e.g. for wait operations self.show_status(result.vsysStatus) return result.vsysStatus def CreateVSYS(self, vsysDescriptorId, vsysName): """ Usage: vsysId = proxy.CreateVSYS(vsysdescriptor.vsysdescriptorId, 'My New System') """ result = self.do_action('CreateVSYS', {'vsysDescriptorId': vsysDescriptorId, 'vsysName': vsysName}) return result.vsysId def DestroyVSYS(self, vsysId): result = self.do_action('DestroyVSYS', {'vsysId': vsysId}) return result.responseStatus def ListVServer(self, vsysId): """ Usage: vservers = proxy.ListVServer(vsys.vsysId) """ result = self.do_action('ListVServer', {'vsysId': vsysId}) return result.vservers def GetVServerConfiguration(self, vsysId, vserverId): """ Usage: vserverconfig = proxy.GetVServerConfiguration(vsys.vsysId, vserver.vserverId) """ result = self.do_action('GetVServerConfiguration', {'vsysId': vsysId, 'vserverId': vserverId}) return result.vserver def GetVServerAttributes(self, vsysId, vserverId): """ Usage: vserverattr = proxy.GetVServerAttributes(vsys.vsysId, vserver.vserverId) """ result = self.do_action('GetVServerAttributes', {'vsysId': vsysId, 'vserverId': vserverId}) return result.vserver def UpdateVServerAttribute(self, vsysId, vserverId, attributeName, attributeValue): result = self.do_action('UpdateVServerAttribute', {'vsysId': vsysId, 'vserverId': vserverId, 'attributeName': attributeName, 'attributeValue': attributeValue}) return result.responseStatus def GetVServerInitialPassword(self, vsysId, vserverId): """ Usage: initialpwd = proxy.GetVServerInitialPassword(vsys.vsysId, vserver.vserverId) """ result = self.do_action('GetVServerInitialPassword', {'vsysId': vsysId, 'vserverId': vserverId}) return result.initialPassword def GetVServerStatus(self, vsysId, vserverId): """ Usage: status = proxy.GetVServerStatus(vsys.vsysId, vserver.vserverId) """ result = self.do_action('GetVServerStatus', {'vsysId': vsysId, 'vserverId': vserverId}) # show status if requested, e.g. for wait operations self.show_status(result.vserverStatus) return result.vserverStatus def GetPerformanceInformation(self, vsysId, vserverId, interval='10minute', dataType=None): """ Usage: perfinfos = proxy.GetPerformanceInformation(vsys.vsysId, vserver.vserverId, interval='hour') """ # CHECKME: serverId instead of vserverId ? result = self.do_action('GetPerformanceInformation', {'vsysId': vsysId, 'serverId': vserverId, 'interval': interval, 'dataType': dataType}) return result.performanceinfos def CreateVServer(self, vsysId, vserverName, vserverType, diskImageId, networkId): """ Usage: vserverId = proxy.CreateVServer(self, vsys.vsysId, 'My New Server', servertype.name, diskimage.diskimageId, vsys.vnets[0]) """ result = self.do_action('CreateVServer', {'vsysId': vsysId, 'vserverName': vserverName, 'vserverType': vserverType, 'diskImageId': diskImageId, 'networkId': networkId}) return result.vserverId def StartVServer(self, vsysId, vserverId): result = self.do_action('StartVServer', {'vsysId': vsysId, 'vserverId': vserverId}) return result.responseStatus def StopVServer(self, vsysId, vserverId, force=None): result = self.do_action('StopVServer', {'vsysId': vsysId, 'vserverId': vserverId, 'force': force}) return result.responseStatus def DestroyVServer(self, vsysId, vserverId): result = self.do_action('DestroyVServer', {'vsysId': vsysId, 'vserverId': vserverId}) return result.responseStatus def ListVDisk(self, vsysId): """ Usage: vdisks = proxy.ListVDisk(vsys.vsysId) """ result = self.do_action('ListVDisk', {'vsysId': vsysId}) return result.vdisks def GetVDiskAttributes(self, vsysId, vdiskId): """ Usage: vdiskattr = proxy.GetVDiskAttributes(vsys.vsysId, vdisk.vdiskId) """ result = self.do_action('GetVDiskAttributes', {'vsysId': vsysId, 'vdiskId': vdiskId}) return result.vdisk def UpdateVDiskAttribute(self, vsysId, vdiskId, attributeName, attributeValue): result = self.do_action('UpdateVDiskAttribute', {'vsysId': vsysId, 'vdiskId': vdiskId, 'attributeName': attributeName, 'attributeValue': attributeValue}) return result.responseStatus def GetVDiskStatus(self, vsysId, vdiskId): """ Usage: status = proxy.GetVDiskStatus(vsys.vsysId, vdisk.vdiskId) """ result = self.do_action('GetVDiskStatus', {'vsysId': vsysId, 'vdiskId': vdiskId}) # show status if requested, e.g. for wait operations self.show_status(result.vdiskStatus) return result.vdiskStatus def CreateVDisk(self, vsysId, vdiskName, size): """ Usage: vdiskId = proxy.CreateVDisk(self, vsys.vsysId, vdiskName, size) """ result = self.do_action('CreateVDisk', {'vsysId': vsysId, 'vdiskName': vdiskName, 'size': size}) return result.vdiskId def AttachVDisk(self, vsysId, vserverId, vdiskId): result = self.do_action('AttachVDisk', {'vsysId': vsysId, 'vserverId': vserverId, 'vdiskId': vdiskId}) return result.responseStatus def DetachVDisk(self, vsysId, vserverId, vdiskId): result = self.do_action('DetachVDisk', {'vsysId': vsysId, 'vserverId': vserverId, 'vdiskId': vdiskId}) return result.responseStatus def DestroyVDisk(self, vsysId, vdiskId): result = self.do_action('DestroyVDisk', {'vsysId': vsysId, 'vdiskId': vdiskId}) return result.responseStatus def ListVDiskBackup(self, vsysId, vdiskId, timeZone=None, countryCode=None): """ Usage: backups = proxy.ListVDiskBackup(vsys.vsysId, vdisk.vdiskId) """ result = self.do_action('ListVDiskBackup', {'vsysId': vsysId, 'vdiskId': vdiskId, 'timeZone': timeZone, 'countryCode': countryCode}) # convert weird time format to time value for backup in result.backups: backup.get_timeval() return result.backups def BackupVDisk(self, vsysId, vdiskId): result = self.do_action('BackupVDisk', {'vsysId': vsysId, 'vdiskId': vdiskId}) return result.responseStatus def RestoreVDisk(self, vsysId, backupId): result = self.do_action('RestoreVDisk', {'vsysId': vsysId, 'backupId': backupId}) return result.responseStatus def DestroyVDiskBackup(self, vsysId, backupId): result = self.do_action('DestroyVDiskBackup', {'vsysId': vsysId, 'backupId': backupId}) return result.responseStatus def ListEFM(self, vsysId, efmType): """Usage: firewalls = proxy.ListEFM(vsys.vsysId, "FW") loadbalancers = proxy.ListEFM(vsys.vsysId, "SLB") """ result = self.do_action('ListEFM', {'vsysId': vsysId, 'efmType': efmType}) # CHECKME: return child firewall or loadbalancer objects child_efms = [] for efm in result.efms: child_efms.append(efm.get_child_object()) return child_efms def GetEFMConfiguration(self, vsysId, efmId, configurationName, configurationXML=None): """Generic method for all GetEFMConfiguration methods""" if configurationXML is None: result = self.do_action('GetEFMConfiguration', {'vsysId': vsysId, 'efmId': efmId, 'configurationName': configurationName}) else: result = self.do_action('GetEFMConfiguration', {'vsysId': vsysId, 'efmId': efmId, 'configurationName': configurationName}, {'name': 'configurationXMLFilePath', 'body': configurationXML}) # CHECKME: return child firewall or loadbalancer object return result.efm.get_child_object() def GetEFMConfigHandler(self, vsysId, efmId): """Handler for specific GetEFMConfiguration methods, see FGCPGetEFMConfigHandler for details Usage: fw_policies = proxy.GetEFMConfigHandler(vsys.vsysId, firewall.efmId).fw_policy(from_zone, to_zone) """ return FGCPGetEFMConfigHandler(self, vsysId, efmId) def UpdateEFMConfiguration(self, vsysId, efmId, configurationName, configurationXML=None, filePath=None): """Generic method for all UpdateEFMConfiguration methods""" if configurationXML is None: result = self.do_action('UpdateEFMConfiguration', {'vsysId': vsysId, 'efmId': efmId, 'configurationName': configurationName}) elif filePath is None: result = self.do_action('UpdateEFMConfiguration', {'vsysId': vsysId, 'efmId': efmId, 'configurationName': configurationName}, {'name': 'configurationXMLFilePath', 'body': configurationXML}) else: # when adding SLB server/cca certificates, configurationXML contains the filePath for the actual certificate to be uploaded result = self.do_action('UpdateEFMConfiguration', {'vsysId': vsysId, 'efmId': efmId, 'configurationName': configurationName}, [{'name': 'configurationXMLFilePath', 'body': configurationXML}, {'name': 'filePath', 'filename': filePath}]) return result.responseStatus def UpdateEFMConfigHandler(self, vsysId, efmId): """Handler for specific UpdateEFMConfiguration methods, see FGCPUpdateEFMConfigHandler for details Usage: proxy.UpdateEFMConfigHandler(vsys.vsysId, firewall.efmId).fw_dns('AUTO') """ return FGCPUpdateEFMConfigHandler(self, vsysId, efmId) def _get_configurationXML(self, configName, params=None): CRLF = '\r\n' L = [] L.append('<?xml version="1.0" encoding="UTF-8"?>') L.append('<Request>') L.append(' <configuration>') L.append(self.add_param(configName, params, 2)) L.append(' </configuration>') L.append('</Request>') return CRLF.join(L) def GetEFMAttributes(self, vsysId, efmId): """ Usage: efmattr = proxy.GetEFMAttributes(vsys.vsysId, loadbalancer.efmId) """ result = self.do_action('GetEFMAttributes', {'vsysId': vsysId, 'efmId': efmId}) # CHECKME: return child firewall or loadbalancer object return result.efm.get_child_object() def UpdateEFMAttribute(self, vsysId, efmId, attributeName, attributeValue): result = self.do_action('UpdateEFMAttribute', {'vsysId': vsysId, 'efmId': efmId, 'attributeName': attributeName, 'attributeValue': attributeValue}) return result.responseStatus def GetEFMStatus(self, vsysId, efmId): """ Usage: status = proxy.GetEFMStatus(vsys.vsysId, loadbalancer.efmId) """ result = self.do_action('GetEFMStatus', {'vsysId': vsysId, 'efmId': efmId}) # show status if requested, e.g. for wait operations self.show_status(result.efmStatus) return result.efmStatus def CreateEFM(self, vsysId, efmType, efmName, networkId): """ Usage: efmId = proxy.CreateEFM(self, vsys.vsysId, 'SLB', 'My LoadBalancer', vsys.vnets[0]) """ result = self.do_action('CreateEFM', {'vsysId': vsysId, 'efmType': efmType, 'efmName': efmName, 'networkId': networkId}) return result.efmId def StartEFM(self, vsysId, efmId): result = self.do_action('StartEFM', {'vsysId': vsysId, 'efmId': efmId}) return result.responseStatus def StopEFM(self, vsysId, efmId): result = self.do_action('StopEFM', {'vsysId': vsysId, 'efmId': efmId}) return result.responseStatus def DestroyEFM(self, vsysId, efmId): result = self.do_action('DestroyEFM', {'vsysId': vsysId, 'efmId': efmId}) return result.responseStatus def ListEFMBackup(self, vsysId, efmId, timeZone=None, countryCode=None): """ Usage: backups = proxy.ListEFMBackup(vsys.vsysId, firewall.efmId) """ result = self.do_action('ListEFMBackup', {'vsysId': vsysId, 'efmId': efmId, 'timeZone': timeZone, 'countryCode': countryCode}) return result.backups def BackupEFM(self, vsysId, efmId): result = self.do_action('BackupEFM', {'vsysId': vsysId, 'efmId': efmId}) return result.responseStatus def RestoreEFM(self, vsysId, efmId, backupId): result = self.do_action('RestoreEFM', {'vsysId': vsysId, 'efmId': efmId, 'backupId': backupId}) return result.responseStatus def DestroyEFMBackup(self, vsysId, efmId, backupId): result = self.do_action('DestroyEFMBackup', {'vsysId': vsysId, 'efmId': efmId, 'backupId': backupId}) return result.responseStatus def StandByConsole(self, vsysId, networkId): """ Usage: url = proxy.StandByConsole(vsys.vsysId, vsys.vnets[0]) """ result = self.do_action('StandByConsole', {'vsysId': vsysId, 'networkId': networkId}) return result.url def GetInformation(self, all=None, timeZone=None, countryCode=None): """ Usage: infos = proxy.GetInformation() """ result = self.do_action('GetInformation', {'all': all, 'timeZone': timeZone, 'countryCode': countryCode}) return result.informations def GetEventLog(self, all=None, timeZone=None, countryCode=None): """ Usage: logs = proxy.GetEventLog() """ result = self.do_action('GetEventLog', {'all': all, 'timeZone': timeZone, 'countryCode': countryCode}) return result.eventlogs def GetSystemUsage(self, vsysIds=None): """NOTE: extra 'date' element on top-level compared to other API calls ! Usage: date, usage = proxy.GetSystemUsage() """ if isinstance(vsysIds, list): vsysIds = ' '.join(vsysIds) result = self.do_action('GetSystemUsage', {'vsysIds': vsysIds}) return result.date, result.usageinfos class FGCPGenericEFMHandler: """ Generic Handler for FGCP Get/Update EFM Configuration methods """ _proxy = None vsysId = None efmId = None def __init__(self, proxy, vsysId=None, efmId=None): # initialize proxy self._proxy = proxy self.vsysId = vsysId self.efmId = efmId class FGCPGetEFMConfigHandler(FGCPGenericEFMHandler): """ Handler for FGCP GetEFMConfiguration methods Example: fw_nat_rules = proxy.GetEFMConfigHandler(vsys.vsysId, firewall.efmId).fw_nat_rule() """ # CHECKME: pass back the complete firewall or loadbalancer response instead of filtering it out here ? def fw_nat_rule(self): """ Usage: fw_nat_rules = proxy.GetEFMConfigHandler(vsys.vsysId, firewall.efmId).fw_nat_rule() """ firewall = self._proxy.GetEFMConfiguration(self.vsysId, self.efmId, 'FW_NAT_RULE') if hasattr(firewall, 'nat'): # CHECKME: remove <rules> part first if isinstance(firewall.nat, list) and len(firewall.nat) == 1: return firewall.nat[0] def fw_dns(self): """ Usage: fw_dns = proxy.GetEFMConfigHandler(vsys.vsysId, firewall.efmId).fw_dns() """ firewall = self._proxy.GetEFMConfiguration(self.vsysId, self.efmId, 'FW_DNS') if hasattr(firewall, 'dns'): return firewall.dns def fw_policy(self, from_zone=None, to_zone=None): """CHECKME: for network identifiers besides INTERNET and INTRANET, see GetVSYSConfiguration() Usage: fw_policies = proxy.GetEFMConfigHandler(vsys.vsysId, firewall.efmId).fw_policy(from_zone, to_zone) """ configurationXML = self._proxy._get_configurationXML('firewall_policy', {'from': from_zone, 'to': to_zone}) firewall = self._proxy.GetEFMConfiguration(self.vsysId, self.efmId, 'FW_POLICY', configurationXML) if hasattr(firewall, 'directions') and isinstance(firewall.directions, list): #return firewall.directions # CHECKME: filter out all general rules with id='50000' ? return self._filter_fw_policies(firewall.directions) def _filter_fw_policies(self, directions=[]): new_directions = [] for direction in directions: if getattr(direction, 'policies', None) is None: continue new_policies = [] for policy in direction.policies: # CHECKME: filter out all general rules with id='50000' ? if getattr(policy, 'id', None) == '50000': continue new_policies.append(policy) if len(new_policies) > 0: direction.policies = new_policies new_directions.append(direction) return new_directions def fw_log(self, num=100, orders=None): """CHECKME: for network identifiers besides INTERNET and INTRANET, see GetVSYSConfiguration() Usage: ipaddress = vsys.publicips[0].address orders = [FGCPFWLogOrder(prefix='dst', value=ipaddress, from_zone=None, to_zone=None)] fw_log = proxy.GetEFMConfigHandler(vsys.vsysId, firewall.efmId).fw_log(100, orders) """ orders = self._convert_fw_log_orders(orders) configurationXML = self._proxy._get_configurationXML('firewall_log', {'num': num, 'orders': orders}) return self._proxy.GetEFMConfiguration(self.vsysId, self.efmId, 'FW_LOG', configurationXML) def _convert_fw_log_orders(self, orders=None): if orders is None or len(orders) < 1: return None new_orders = [] for order in orders: new_orders.append({'order': order.__dict__}) return new_orders def fw_limit_policy(self, from_zone=None, to_zone=None): """CHECKME: for network identifiers besides INTERNET and INTRANET, see GetVSYSConfiguration() Usage: fw_limit_policy = proxy.GetEFMConfigHandler(vsys.vsysId, firewall.efmId).fw_limit_policy(from_zone, to_zone) """ configurationXML = self._proxy._get_configurationXML('firewall_limit_policy', {'from': from_zone, 'to': to_zone}) result = self._proxy.GetEFMConfiguration(self.vsysId, self.efmId, 'FW_LIMIT_POLICY', configurationXML) # CHECKME: remove <directions> part first if isinstance(result, list) and len(result) == 1: return result[0] def slb_rule(self): """ Usage: slb_rule = proxy.GetEFMConfigHandler(vsys.vsysId, loadbalancer.efmId).slb_rule() """ return self._proxy.GetEFMConfiguration(self.vsysId, self.efmId, 'SLB_RULE') def slb_try_getaction(self, action): try: return self._proxy.GetEFMConfiguration(self.vsysId, self.efmId, action) except FGCPResponseError: import sys e = sys.exc_info()[1] if e.status == 'NONE_LB_RULE': return raise def slb_load(self): """ Usage: slb_load_stats = proxy.GetEFMConfigHandler(vsys.vsysId, loadbalancer.efmId).slb_load() """ # CHECKME: this generates an exception with status NONE_LB_RULE if no SLB rules are defined #stats = self._proxy.GetEFMConfiguration(self.vsysId, self.efmId, 'SLB_LOAD_STATISTICS').loadStatistics result = self.slb_try_getaction('SLB_LOAD_STATISTICS') if result is not None and hasattr(result, 'loadStatistics') and len(result.loadStatistics) == 1: # CHECKME: remove <groups> part first return result.loadStatistics[0] def slb_error(self): """ Usage: slb_error_stats = proxy.GetEFMConfigHandler(vsys.vsysId, loadbalancer.efmId).slb_error() """ # CHECKME: this generates an exception with status NONE_LB_RULE if no SLB rules are defined #return self._proxy.GetEFMConfiguration(self.vsysId, self.efmId, 'SLB_ERROR_STATISTICS').errorStatistics result = self.slb_try_getaction('SLB_ERROR_STATISTICS') if result is not None and hasattr(result, 'errorStatistics'): return result.errorStatistics def slb_cert_list(self, certCategory=None, detail=None): """ Usage: slb_cert_list = proxy.GetEFMConfigHandler(vsys.vsysId, loadbalancer.efmId).slb_cert_list() """ configurationXML = self._proxy._get_configurationXML('loadbalancer_certificate_list', {'certCategory': certCategory, 'detail': detail}) return self._proxy.GetEFMConfiguration(self.vsysId, self.efmId, 'SLB_CERTIFICATE_LIST', configurationXML) def efm_update(self): """ Common method for FW and SLB EFM_UPDATE returns firewall or loadbalancer """ return self._proxy.GetEFMConfiguration(self.vsysId, self.efmId, 'EFM_UPDATE') def fw_update(self): """ Usage: fw_update = proxy.GetEFMConfigHandler(vsys.vsysId, firewall.efmId).fw_update() """ return self.efm_update() def slb_update(self): """ Usage: slb_update = proxy.GetEFMConfigHandler(vsys.vsysId, loadbalancer.efmId).slb_update() """ return self.efm_update() class FGCPUpdateEFMConfigHandler(FGCPGenericEFMHandler): """ Handler for FGCP UpdateEFMConfiguration methods Example: proxy.UpdateEFMConfigHandler(vsys.vsysId, firewall.efmId).fw_dns('AUTO') """ def fw_nat_rule(self, rules=None): """Usage: fw_nat_rules = proxy.GetEFMConfigHandler(vsys.vsysId, firewall.efmId).fw_nat_rule() proxy.UpdateEFMConfigHandler(vsys.vsysId, firewall.efmId).fw_nat_rule(fw_nat_rules) """ # TODO: add firewall nat rule builder ? # round-trip support rules = self._convert_fw_nat_rules(rules) configurationXML = self._proxy._get_configurationXML('firewall_nat', rules) return self._proxy.UpdateEFMConfiguration(self.vsysId, self.efmId, 'FW_NAT_RULE', configurationXML) def _convert_fw_nat_rules(self, rules=None): # CHECKME: for round-trip support, we need to: clean_rule = ['_proxy', '_parent'] if rules is None or len(rules) < 1: # this resets the NAT and SNAPT rules return '' elif len(rules) == 1: # single rule: use {'rule': {'publicIp': '80.70.163.172', 'snapt': 'true', 'privateIp': '192.168.0.211'}} rule = rules[0] for key in clean_rule: if hasattr(rule, key): delattr(rule, key) return {'rule': rule.__dict__} else: # multiple rules: use [{'rule': {...}}, {'rule': {...}}, ...] new_rules = [] for rule in rules: for key in clean_rule: if hasattr(rule, key): delattr(rule, key) new_rules.append({'rule': rule.__dict__}) return new_rules def fw_dns(self, dnstype='AUTO', primary=None, secondary=None): """ Usage: proxy.UpdateEFMConfigHandler(vsys.vsysId, firewall.efmId).fw_dns('AUTO') """ configurationXML = self._proxy._get_configurationXML('firewall_dns', {'type': dnstype, 'primary': primary, 'secondary': secondary}) return self._proxy.UpdateEFMConfiguration(self.vsysId, self.efmId, 'FW_DNS', configurationXML) def fw_policy(self, log='On', directions=None): """Usage: policies = proxy.GetEFMConfigHandler(vsys.vsysId, firewall.efmId).fw_policy() proxy.UpdateEFMConfigHandler(vsys.vsysId, firewall.efmId).fw_policy('On', policies) Warning: this overrides the complete firewall configuration, so you need to specify all the policies at once ! """ # TODO: add firewall policy builder # round-trip support directions = self._convert_fw_directions(log, directions) configurationXML = self._proxy._get_configurationXML('firewall_policy', {'directions': directions}) return self._proxy.UpdateEFMConfiguration(self.vsysId, self.efmId, 'FW_POLICY', configurationXML) def _convert_fw_directions(self, log, directions=None): # CHECKME: for round-trip support, we need to: clean_policy = ['_proxy', '_parent'] new_directions = [] # add default log policy to directions new_directions.append({'direction': {'policies': {'policy': {'log': log}}}}) if directions is None: return new_directions # CHECKME: for round-trip support, we need to: for direction in directions: # a. add {'direction': {...}} for each {from, to, policies} new_direction = {'direction': {}} # b. replace 'UU62ICIP-AQYOXXRXS-N-INTERNET' by 'INTERNET' in each from and to # CHECKME: direction.from is restricted, so we use getattr() here instead !? if not hasattr(direction, 'from') or getattr(direction, 'from') is None: pass elif getattr(direction, 'from').endswith('-INTERNET'): new_direction['direction']['from'] = 'INTERNET' elif getattr(direction, 'from').endswith('-INTRANET'): new_direction['direction']['from'] = 'INTRANET' else: new_direction['direction']['from'] = getattr(direction, 'from') if not hasattr(direction, 'to') or getattr(direction, 'to') is None: pass elif direction.to.endswith('-INTERNET'): new_direction['direction']['to'] = 'INTERNET' elif direction.to.endswith('-INTRANET'): new_direction['direction']['to'] = 'INTRANET' else: new_direction['direction']['to'] = direction.to # c. add {'policy': {...}} for each policy new_policies = [] for policy in direction.policies: # d. remove all policies with id 50000 = default rule if policy.id == '50000': continue # e. replace each policy id 46999 by id 999 elif len(policy.id) > 3: policy.id = policy.id[2:] # CHECKME: dump the whole dictionary here ? for key in clean_policy: if hasattr(policy, key): delattr(policy, key) new_policies.append({'policy': policy.__dict__}) # if we have anything left, add it to the new directions if len(new_policies) > 0: new_direction['direction']['policies'] = new_policies new_directions.append(new_direction) return new_directions def slb_rule(self, groups=None, force=None, webAccelerator=None): """Usage: slb_rule = proxy.GetEFMConfigHandler(vsys.vsysId, loadbalancer.efmId).slb_rule() proxy.UpdateEFMConfigHandler(vsys.vsysId, loadbalancer.efmId).slb_rule(slb_rule.groups) Warning: this overrides the complete loadbalancer configuration, so you need to specify all the groups at once ! """ # TODO: add loadbalancer group builder # round-trip support groups = self._convert_slb_groups(groups) configurationXML = self._proxy._get_configurationXML('loadbalancer_rule', {'groups': groups, 'force': force, 'webAccelerator': webAccelerator}) return self._proxy.UpdateEFMConfiguration(self.vsysId, self.efmId, 'SLB_RULE', configurationXML) def _convert_slb_groups(self, groups=None): new_groups = [] if groups is None: return new_groups # CHECKME: for round-trip support, we need to: clean_group = ['causes', '_proxy', '_parent', 'targets'] clean_target = ['ipAddress', 'serverName', '_proxy', '_parent'] for group in groups: # a. add {'group': {...}} for each {id, protocol, ..., targets} new_group = {'group': {}} # b. CHECKME: remove causes ? for key in group.__dict__: if key not in clean_group: new_group['group'][key] = group.__dict__[key] new_targets = [] # c. add {'target': {...}} for each target for target in group.targets: new_target = {'target': {}} # d. remove ipAddress and serverName from each target for key in target.__dict__: if key not in clean_target: new_target['target'][key] = target.__dict__[key] new_targets.append(new_target) # ... # if we have anything left, add it to the new groups #if len(new_targets) > 0: new_group['group']['targets'] = new_targets new_groups.append(new_group) return new_groups def slb_try_updateaction(self, action): try: return self._proxy.UpdateEFMConfiguration(self.vsysId, self.efmId, action) except FGCPResponseError: import sys e = sys.exc_info()[1] if e.status == 'NONE_LB_RULE': return raise def slb_load_clear(self): # CHECKME: this generates an exception with status NONE_LB_RULE if no SLB rules are defined #return self._proxy.UpdateEFMConfiguration(self.vsysId, self.efmId, 'SLB_LOAD_STATISTICS_CLEAR') return self.slb_try_updateaction('SLB_LOAD_STATISTICS_CLEAR') def slb_error_clear(self): # CHECKME: this generates an exception with status NONE_LB_RULE if no SLB rules are defined #return self._proxy.UpdateEFMConfiguration(self.vsysId, self.efmId, 'SLB_ERROR_STATISTICS_CLEAR') return self.slb_try_updateaction('SLB_ERROR_STATISTICS_CLEAR') def slb_start_maint(self, id, ipAddress, time=None, unit=None): configurationXML = self._proxy._get_configurationXML('loadbalancer_start_maintenance', {'id': id, 'ipAddress': ipAddress, 'time': time, 'unit': unit}) return self._proxy.UpdateEFMConfiguration(self.vsysId, self.efmId, 'SLB_START_MAINTENANCE', configurationXML) def slb_stop_maint(self, id, ipAddress): configurationXML = self._proxy._get_configurationXML('loadbalancer_stop_maintenance', {'id': id, 'ipAddress': ipAddress}) return self._proxy.UpdateEFMConfiguration(self.vsysId, self.efmId, 'SLB_STOP_MAINTENANCE', configurationXML) def slb_cert_add(self, certNum, filePath, passphrase): """ Note: server certificates in unencrypted PEM format are NOT supported here, use PKCS12 format (and others ?) """ # when adding SLB server/cca certificates, configurationXML contains the filePath for the actual certificate to be uploaded configurationXML = self._proxy._get_configurationXML('loadbalancer_certificate', {'certNum': certNum, 'filePath': filePath, 'passphrase': passphrase}) return self._proxy.UpdateEFMConfiguration(self.vsysId, self.efmId, 'SLB_CERTIFICATE_ADD', configurationXML, filePath) def slb_cert_set(self, certNum, id): configurationXML = self._proxy._get_configurationXML('loadbalancer_certificate', {'certNum': certNum, 'id': id}) return self._proxy.UpdateEFMConfiguration(self.vsysId, self.efmId, 'SLB_CERTIFICATE_SET', configurationXML) def slb_cert_release(self, certNum): configurationXML = self._proxy._get_configurationXML('loadbalancer_certificate', {'certNum': certNum}) return self._proxy.UpdateEFMConfiguration(self.vsysId, self.efmId, 'SLB_CERTIFICATE_RELEASE', configurationXML) def slb_cert_delete(self, certNum, force=None): configurationXML = self._proxy._get_configurationXML('loadbalancer_certificate', {'certNum': certNum, 'force': force}) return self._proxy.UpdateEFMConfiguration(self.vsysId, self.efmId, 'SLB_CERTIFICATE_DELETE', configurationXML) def slb_cca_add(self, ccacertNum, filePath): """ Note: cca certificates in .crt or .pem format ARE supported here (and others ?) """ # when adding SLB server/cca certificates, configurationXML contains the filePath for the actual certificate to be uploaded configurationXML = self._proxy._get_configurationXML('loadbalancer_cca_certificate', {'ccacertNum': ccacertNum, 'filePath': filePath}) return self._proxy.UpdateEFMConfiguration(self.vsysId, self.efmId, 'SLB_CCA_CERTIFICATE_ADD', configurationXML, filePath) def slb_cca_delete(self, ccacertNum): configurationXML = self._proxy._get_configurationXML('loadbalancer_cca_certificate', {'ccacertNum': ccacertNum}) return self._proxy.UpdateEFMConfiguration(self.vsysId, self.efmId, 'SLB_CCA_CERTIFICATE_DELETE', configurationXML) def efm_update(self): return self._proxy.UpdateEFMConfiguration(self.vsysId, self.efmId, 'EFM_UPDATE') def efm_backout(self): return self._proxy.UpdateEFMConfiguration(self.vsysId, self.efmId, 'EFM_BACKOUT') """ FGCP API Commands that are not supported in the current API version class FGCPCommandNotSupported(FGCPCommand): def GetVSYSDescriptor(self): raise FGCPCommandError('UNSUPPORT_ERROR', 'Unable to use the specified API') def CreateVSYSDescriptor(self): raise FGCPCommandError('UNSUPPORT_ERROR', 'Unable to use the specified API') def RegisterVSYSDescriptor(self): raise FGCPCommandError('UNSUPPORT_ERROR', 'Unable to use the specified API') def ListVNet(self): raise FGCPCommandError('UNSUPPORT_ERROR', 'Unable to use the specified API') def CreateVNet(self): raise FGCPCommandError('UNSUPPORT_ERROR', 'Unable to use the specified API') def GetINet(self): raise FGCPCommandError('UNSUPPORT_ERROR', 'Unable to use the specified API') def ListProductID(self): raise FGCPCommandError('UNSUPPORT_ERROR', 'Unable to use the specified API') def RegisterProductID(self): raise FGCPCommandError('UNSUPPORT_ERROR', 'Unable to use the specified API') def CreateDiskImage(self): raise FGCPCommandError('UNSUPPORT_ERROR', 'Unable to use the specified API') def RegisterDiskImage(self): raise FGCPCommandError('UNSUPPORT_ERROR', 'Unable to use the specified API') def ListVNIC(self): raise FGCPCommandError('UNSUPPORT_ERROR', 'Unable to use the specified API') def CreateVNIC(self): raise FGCPCommandError('UNSUPPORT_ERROR', 'Unable to use the specified API') """
Python
#!/usr/bin/python # # Copyright (C) 2011 Michel Dalle # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ Client API library for the Fujitsu Global Cloud Platform (FGCP) using XML-RPC API Version 2012-02-18 Requirements: this module uses gdata.tlslite.utils to create the key signature, see http://code.google.com/p/gdata-python-client/ for download and installation """ def fgcp_run_sample(pem_file, region, private_key=None): # Connect with your client certificate to this region from fgcp.resource import FGCPVDataCenter vdc = FGCPVDataCenter(pem_file, region) # Set your private key for signatures if you use the relay server if region.startswith('relay') and private_key: vdc.getproxy().set_key(private_key) # Do typical actions on resources vsystem = vdc.get_vsystem('Demo System') vsystem.show_status() #for vserver in vsystem.vservers: # result = vserver.backup(wait=True) #... # See tests/test_resource.py for more examples def fgcp_show_usage(name='fgcp_demo.py'): print """Client API library for the Fujitsu Global Cloud Platform (FGCP) Usage: %s [pem_file] [region] # Connect with your client certificate to region 'uk' from fgcp.resource import FGCPVDataCenter # Do typical actions on resources vdc = FGCPVDataCenter('client.pem', 'uk') vsystem = vdc.get_vsystem('Demo System') vsystem.show_status() #for vserver in vsystem.vservers: # result = vserver.backup(wait=True) #... # See tests/test_resource.py for more examples Requirements: this module uses gdata.tlslite.utils to create the key signature, see http://code.google.com/p/gdata-python-client/ for download and installation Note: to convert your .p12 or .pfx file to unencrypted PEM format, you can use the following 'openssl' command: openssl pkcs12 -in UserCert.p12 -out client.pem -nodes """ % name if __name__ == "__main__": """ Check if we have an existing 'client.pem' file or command line argument specifying the PEM file, or get your private key from some configuration if you use the relay server """ import os.path import sys pem_file = 'client.pem' #region = 'de' region = 'test' #region = 'relay=http://localhost:8000/cgi-bin/fgcp_relay.py' # Get your private key from somewhere if you use the relay server private_key = """ -----BEGIN RSA PRIVATE KEY----- ... -----END RSA PRIVATE KEY----- """ if len(sys.argv) > 1: pem_file = sys.argv[1] if len(sys.argv) > 2: region = sys.argv[2] if region.startswith('relay') and private_key: fgcp_run_sample(pem_file, region, private_key) elif os.path.exists(pem_file): fgcp_run_sample(pem_file, region) else: fgcp_show_usage(os.path.basename(sys.argv[0]))
Python
__author__ = 'guotie' from flask import Flask app = Flask(__name__) @app.route('/') def hello_world(): return 'Hello World!' if __name__ == '__main__': #app.debug = True app.run()
Python
#!/usr/bin/python # # Copyright (C) 2012 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. __author__ = 'afshar@google.com (Ali Afshar)' import os import httplib2 import sessions from google.appengine.ext import db from google.appengine.ext.webapp import template from apiclient.discovery import build_from_document from apiclient.http import MediaUpload from oauth2client import client from oauth2client.appengine import CredentialsProperty from oauth2client.appengine import StorageByKeyName from oauth2client.appengine import simplejson as json APIS_BASE = 'https://www.googleapis.com' ALL_SCOPES = ('https://www.googleapis.com/auth/drive.file ' 'https://www.googleapis.com/auth/userinfo.email ' 'https://www.googleapis.com/auth/userinfo.profile') CODE_PARAMETER = 'code' STATE_PARAMETER = 'state' SESSION_SECRET = open('session.secret').read() DRIVE_DISCOVERY_DOC = open('drive.json').read() USERS_DISCOVERY_DOC = open('users.json').read() class Credentials(db.Model): """Datastore entity for storing OAuth2.0 credentials.""" credentials = CredentialsProperty() def CreateOAuthFlow(request): """Create OAuth2.0 flow controller Args: request: HTTP request to create OAuth2.0 flow for Returns: OAuth2.0 Flow instance suitable for performing OAuth2.0. """ flow = client.flow_from_clientsecrets('client-debug.json', scope='') flow.redirect_uri = request.url.split('?', 1)[0].rstrip('/') return flow def GetCodeCredentials(request): """Create OAuth2.0 credentials by extracting a code and performing OAuth2.0. Args: request: HTTP request used for extracting an authorization code. Returns: OAuth2.0 credentials suitable for authorizing clients. """ code = request.get(CODE_PARAMETER) if code: oauth_flow = CreateOAuthFlow(request) creds = oauth_flow.step2_exchange(code) users_service = CreateService(USERS_DISCOVERY_DOC, creds) userid = users_service.userinfo().get().execute().get('id') request.session.set_secure_cookie(name='userid', value=userid) StorageByKeyName(Credentials, userid, 'credentials').put(creds) return creds def GetSessionCredentials(request): """Get OAuth2.0 credentials for an HTTP session. Args: request: HTTP request to use session from. Returns: OAuth2.0 credentials suitable for authorizing clients. """ userid = request.session.get_secure_cookie(name='userid') if userid: creds = StorageByKeyName(Credentials, userid, 'credentials').get() if creds and not creds.invalid: return creds def CreateService(discovery_doc, creds): """Create a Google API service. Args: discovery_doc: Discovery doc used to configure service. creds: Credentials used to authorize service. Returns: Authorized Google API service. """ http = httplib2.Http() creds.authorize(http) return build_from_document(discovery_doc, APIS_BASE, http=http) def RedirectAuth(handler): """Redirect a handler to an authorization page. Args: handler: webapp.RequestHandler to redirect. """ flow = CreateOAuthFlow(handler.request) flow.scope = ALL_SCOPES uri = flow.step1_get_authorize_url(flow.redirect_uri) handler.redirect(uri) def CreateDrive(handler): """Create a fully authorized drive service for this handler. Args: handler: RequestHandler from which drive service is generated. Returns: Authorized drive service, generated from the handler request. """ request = handler.request request.session = sessions.LilCookies(handler, SESSION_SECRET) creds = GetCodeCredentials(request) or GetSessionCredentials(request) if creds: return CreateService(DRIVE_DISCOVERY_DOC, creds) else: RedirectAuth(handler) def ServiceEnabled(view): """Decorator to inject an authorized service into an HTTP handler. Args: view: HTTP request handler method. Returns: Decorated handler which accepts the service as a parameter. """ def ServiceDecoratedView(handler, view=view): service = CreateDrive(handler) response_data = view(handler, service) handler.response.headers['Content-Type'] = 'text/html' handler.response.out.write(response_data) return ServiceDecoratedView def ServiceEnabledJson(view): """Decorator to inject an authorized service into a JSON HTTP handler. Args: view: HTTP request handler method. Returns: Decorated handler which accepts the service as a parameter. """ def ServiceDecoratedView(handler, view=view): service = CreateDrive(handler) if handler.request.body: data = json.loads(handler.request.body) else: data = None response_data = json.dumps(view(handler, service, data)) handler.response.headers['Content-Type'] = 'application/json' handler.response.out.write(response_data) return ServiceDecoratedView class DriveState(object): """Store state provided by Drive.""" def __init__(self, state): self.ParseState(state) @classmethod def FromRequest(cls, request): """Create a Drive State instance from an HTTP request. Args: cls: Type this class method is called against. request: HTTP request. """ return DriveState(request.get(STATE_PARAMETER)) def ParseState(self, state): """Parse a state parameter and set internal values. Args: state: State parameter to parse. """ if state.startswith('{'): self.ParseJsonState(state) else: self.ParsePlainState(state) def ParseJsonState(self, state): """Parse a state parameter that is JSON. Args: state: State parameter to parse """ state_data = json.loads(state) self.action = state_data['action'] self.ids = map(str, state_data.get('ids', [])) def ParsePlainState(self, state): """Parse a state parameter that is a plain resource id or missing. Args: state: State parameter to parse """ if state: self.action = 'open' self.ids = [state] else: self.action = 'create' self.ids = [] class MediaInMemoryUpload(MediaUpload): """MediaUpload for a chunk of bytes. Construct a MediaFileUpload and pass as the media_body parameter of the method. For example, if we had a service that allowed plain text: """ def __init__(self, body, mimetype='application/octet-stream', chunksize=256*1024, resumable=False): """Create a new MediaBytesUpload. Args: body: string, Bytes of body content. mimetype: string, Mime-type of the file or default of 'application/octet-stream'. chunksize: int, File will be uploaded in chunks of this many bytes. Only used if resumable=True. resumable: bool, True if this is a resumable upload. False means upload in a single request. """ self._body = body self._mimetype = mimetype self._resumable = resumable self._chunksize = chunksize def chunksize(self): """Chunk size for resumable uploads. Returns: Chunk size in bytes. """ return self._chunksize def mimetype(self): """Mime type of the body. Returns: Mime type. """ return self._mimetype def size(self): """Size of upload. Returns: Size of the body. """ return len(self._body) def resumable(self): """Whether this upload is resumable. Returns: True if resumable upload or False. """ return self._resumable def getbytes(self, begin, length): """Get bytes from the media. Args: begin: int, offset from beginning of file. length: int, number of bytes to read, starting at begin. Returns: A string of bytes read. May be shorter than length if EOF was reached first. """ return self._body[begin:begin + length] def RenderTemplate(name, **context): """Render a named template in a context. Args: name: Template name. context: Keyword arguments to render as template variables. """ return template.render(name, context)
Python
#!/usr/bin/python # # Copyright (C) 2012 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. __author__ = 'afshar@google.com (Ali Afshar)' # Add the library location to the path import sys sys.path.insert(0, 'lib') import os import httplib2 import sessions from google.appengine.ext import webapp from google.appengine.ext.webapp.util import run_wsgi_app from google.appengine.ext import db from google.appengine.ext.webapp import template from apiclient.discovery import build from apiclient.http import MediaUpload from oauth2client.client import flow_from_clientsecrets from oauth2client.client import FlowExchangeError from oauth2client.client import AccessTokenRefreshError from oauth2client.appengine import CredentialsProperty from oauth2client.appengine import StorageByKeyName from oauth2client.appengine import simplejson as json ALL_SCOPES = ('https://www.googleapis.com/auth/drive.file ' 'https://www.googleapis.com/auth/userinfo.email ' 'https://www.googleapis.com/auth/userinfo.profile') def SibPath(name): """Generate a path that is a sibling of this file. Args: name: Name of sibling file. Returns: Path to sibling file. """ return os.path.join(os.path.dirname(__file__), name) # Load the secret that is used for client side sessions # Create one of these for yourself with, for example: # python -c "import os; print os.urandom(64)" > session-secret SESSION_SECRET = open(SibPath('session.secret')).read() INDEX_HTML = open(SibPath('index.html')).read() class Credentials(db.Model): """Datastore entity for storing OAuth2.0 credentials. The CredentialsProperty is provided by the Google API Python Client, and is used by the Storage classes to store OAuth 2.0 credentials in the data store.""" credentials = CredentialsProperty() def CreateService(service, version, creds): """Create a Google API service. Load an API service from a discovery document and authorize it with the provided credentials. Args: service: Service name (e.g 'drive', 'oauth2'). version: Service version (e.g 'v1'). creds: Credentials used to authorize service. Returns: Authorized Google API service. """ # Instantiate an Http instance http = httplib2.Http() # Authorize the Http instance with the passed credentials creds.authorize(http) # Build a service from the passed discovery document path return build(service, version, http=http) class DriveState(object): """Store state provided by Drive.""" def __init__(self, state): """Create a new instance of drive state. Parse and load the JSON state parameter. Args: state: State query parameter as a string. """ if state: state_data = json.loads(state) self.action = state_data['action'] self.ids = map(str, state_data.get('ids', [])) else: self.action = 'create' self.ids = [] @classmethod def FromRequest(cls, request): """Create a Drive State instance from an HTTP request. Args: cls: Type this class method is called against. request: HTTP request. """ return DriveState(request.get('state')) class BaseDriveHandler(webapp.RequestHandler): """Base request handler for drive applications. Adds Authorization support for Drive. """ def CreateOAuthFlow(self): """Create OAuth2.0 flow controller This controller can be used to perform all parts of the OAuth 2.0 dance including exchanging an Authorization code. Args: request: HTTP request to create OAuth2.0 flow for Returns: OAuth2.0 Flow instance suitable for performing OAuth2.0. """ flow = flow_from_clientsecrets('client_secrets.json', scope='') # Dynamically set the redirect_uri based on the request URL. This is extremely # convenient for debugging to an alternative host without manually setting the # redirect URI. flow.redirect_uri = self.request.url.split('?', 1)[0].rsplit('/', 1)[0] return flow def GetCodeCredentials(self): """Create OAuth 2.0 credentials by extracting a code and performing OAuth2.0. The authorization code is extracted form the URI parameters. If it is absent, None is returned immediately. Otherwise, if it is present, it is used to perform step 2 of the OAuth 2.0 web server flow. Once a token is received, the user information is fetched from the userinfo service and stored in the session. The token is saved in the datastore against the user ID received from the userinfo service. Args: request: HTTP request used for extracting an authorization code and the session information. Returns: OAuth2.0 credentials suitable for authorizing clients or None if Authorization could not take place. """ # Other frameworks use different API to get a query parameter. code = self.request.get('code') if not code: # returns None to indicate that no code was passed from Google Drive. return None # Auth flow is a controller that is loaded with the client information, # including client_id, client_secret, redirect_uri etc oauth_flow = self.CreateOAuthFlow() # Perform the exchange of the code. If there is a failure with exchanging # the code, return None. try: creds = oauth_flow.step2_exchange(code) except FlowExchangeError: return None # Create an API service that can use the userinfo API. Authorize it with our # credentials that we gained from the code exchange. users_service = CreateService('oauth2', 'v2', creds) # Make a call against the userinfo service to retrieve the user's information. # In this case we are interested in the user's "id" field. userid = users_service.userinfo().get().execute().get('id') # Store the user id in the user's cookie-based session. session = sessions.LilCookies(self, SESSION_SECRET) session.set_secure_cookie(name='userid', value=userid) # Store the credentials in the data store using the userid as the key. StorageByKeyName(Credentials, userid, 'credentials').put(creds) return creds def GetSessionCredentials(self): """Get OAuth 2.0 credentials for an HTTP session. If the user has a user id stored in their cookie session, extract that value and use it to load that user's credentials from the data store. Args: request: HTTP request to use session from. Returns: OAuth2.0 credentials suitable for authorizing clients. """ # Try to load the user id from the session session = sessions.LilCookies(self, SESSION_SECRET) userid = session.get_secure_cookie(name='userid') if not userid: # return None to indicate that no credentials could be loaded from the # session. return None # Load the credentials from the data store, using the userid as a key. creds = StorageByKeyName(Credentials, userid, 'credentials').get() # if the credentials are invalid, return None to indicate that the credentials # cannot be used. if creds and creds.invalid: return None return creds def RedirectAuth(self): """Redirect a handler to an authorization page. Used when a handler fails to fetch credentials suitable for making Drive API requests. The request is redirected to an OAuth 2.0 authorization approval page and on approval, are returned to application. Args: handler: webapp.RequestHandler to redirect. """ flow = self.CreateOAuthFlow() # Manually add the required scopes. Since this redirect does not originate # from the Google Drive UI, which authomatically sets the scopes that are # listed in the API Console. flow.scope = ALL_SCOPES # Create the redirect URI by performing step 1 of the OAuth 2.0 web server # flow. uri = flow.step1_get_authorize_url(flow.redirect_uri) # Perform the redirect. self.redirect(uri) def RespondJSON(self, data): """Generate a JSON response and return it to the client. Args: data: The data that will be converted to JSON to return. """ self.response.headers['Content-Type'] = 'application/json' self.response.out.write(json.dumps(data)) def CreateAuthorizedService(self, service, version): """Create an authorize service instance. The service can only ever retrieve the credentials from the session. Args: service: Service name (e.g 'drive', 'oauth2'). version: Service version (e.g 'v1'). Returns: Authorized service or redirect to authorization flow if no credentials. """ # For the service, the session holds the credentials creds = self.GetSessionCredentials() if creds: # If the session contains credentials, use them to create a Drive service # instance. return CreateService(service, version, creds) else: # If no credentials could be loaded from the session, redirect the user to # the authorization page. self.RedirectAuth() def CreateDrive(self): """Create a drive client instance.""" return self.CreateAuthorizedService('drive', 'v2') def CreateUserInfo(self): """Create a user info client instance.""" return self.CreateAuthorizedService('oauth2', 'v2') class MainPage(BaseDriveHandler): """Web handler for the main page. Handles requests and returns the user interface for Open With and Create cases. Responsible for parsing the state provided from the Drive UI and acting appropriately. """ def get(self): """Handle GET for Create New and Open With. This creates an authorized client, and checks whether a resource id has been passed or not. If a resource ID has been passed, this is the Open With use-case, otherwise it is the Create New use-case. """ # Generate a state instance for the request, this includes the action, and # the file id(s) that have been sent from the Drive user interface. drive_state = DriveState.FromRequest(self.request) if drive_state.action == 'open' and len(drive_state.ids) > 0: code = self.request.get('code') if code: code = '?code=%s' % code self.redirect('/#edit/%s%s' % (drive_state.ids[0], code)) return # Fetch the credentials by extracting an OAuth 2.0 authorization code from # the request URL. If the code is not present, redirect to the OAuth 2.0 # authorization URL. creds = self.GetCodeCredentials() if not creds: return self.RedirectAuth() # Extract the numerical portion of the client_id from the stored value in # the OAuth flow. You could also store this value as a separate variable # somewhere. client_id = self.CreateOAuthFlow().client_id.split('.')[0].split('-')[0] self.RenderTemplate() def RenderTemplate(self): """Render a named template in a context.""" self.response.headers['Content-Type'] = 'text/html' self.response.out.write(INDEX_HTML) class ServiceHandler(BaseDriveHandler): """Web handler for the service to read and write to Drive.""" def post(self): """Called when HTTP POST requests are received by the web application. The POST body is JSON which is deserialized and used as values to create a new file in Drive. The authorization access token for this action is retreived from the data store. """ # Create a Drive service service = self.CreateDrive() if service is None: return # Load the data that has been posted as JSON data = self.RequestJSON() # Create a new file data structure. resource = { 'title': data['title'], 'description': data['description'], 'mimeType': data['mimeType'], } try: # Make an insert request to create a new file. A MediaInMemoryUpload # instance is used to upload the file body. resource = service.files().insert( body=resource, media_body=MediaInMemoryUpload( data.get('content', ''), data['mimeType'], resumable=True) ).execute() # Respond with the new file id as JSON. self.RespondJSON(resource['id']) except AccessTokenRefreshError: # In cases where the access token has expired and cannot be refreshed # (e.g. manual token revoking) redirect the user to the authorization page # to authorize. self.RedirectAuth() def get(self): """Called when HTTP GET requests are received by the web application. Use the query parameter file_id to fetch the required file's metadata then content and return it as a JSON object. Since DrEdit deals with text files, it is safe to dump the content directly into JSON, but this is not the case with binary files, where something like Base64 encoding is more appropriate. """ # Create a Drive service service = self.CreateDrive() if service is None: return try: # Requests are expected to pass the file_id query parameter. file_id = self.request.get('file_id') if file_id: # Fetch the file metadata by making the service.files().get method of # the Drive API. f = service.files().get(fileId=file_id).execute() downloadUrl = f.get('downloadUrl') # If a download URL is provided in the file metadata, use it to make an # authorized request to fetch the file ontent. Set this content in the # data to return as the 'content' field. If there is no downloadUrl, # just set empty content. if downloadUrl: resp, f['content'] = service._http.request(downloadUrl) else: f['content'] = '' else: f = None # Generate a JSON response with the file data and return to the client. self.RespondJSON(f) except AccessTokenRefreshError: # Catch AccessTokenRefreshError which occurs when the API client library # fails to refresh a token. This occurs, for example, when a refresh token # is revoked. When this happens the user is redirected to the # Authorization URL. self.RedirectAuth() def put(self): """Called when HTTP PUT requests are received by the web application. The PUT body is JSON which is deserialized and used as values to update a file in Drive. The authorization access token for this action is retreived from the data store. """ # Create a Drive service service = self.CreateDrive() if service is None: return # Load the data that has been posted as JSON data = self.RequestJSON() try: # Create a new file data structure. content = data.get('content') if 'content' in data: data.pop('content') if content is not None: # Make an update request to update the file. A MediaInMemoryUpload # instance is used to upload the file body. Because of a limitation, this # request must be made in two parts, the first to update the metadata, and # the second to update the body. resource = service.files().update( fileId=data['resource_id'], newRevision=self.request.get('newRevision', False), body=data, media_body=MediaInMemoryUpload( content, data['mimeType'], resumable=True) ).execute() else: # Only update the metadata, a patch request is prefered but not yet # supported on Google App Engine; see # http://code.google.com/p/googleappengine/issues/detail?id=6316. resource = service.files().update( fileId=data['resource_id'], newRevision=self.request.get('newRevision', False), body=data).execute() # Respond with the new file id as JSON. self.RespondJSON(resource['id']) except AccessTokenRefreshError: # In cases where the access token has expired and cannot be refreshed # (e.g. manual token revoking) redirect the user to the authorization page # to authorize. self.RedirectAuth() def RequestJSON(self): """Load the request body as JSON. Returns: Request body loaded as JSON or None if there is no request body. """ if self.request.body: return json.loads(self.request.body) class UserHandler(BaseDriveHandler): """Web handler for the service to read user information.""" def get(self): """Called when HTTP GET requests are received by the web application.""" # Create a Drive service service = self.CreateUserInfo() if service is None: return try: result = service.userinfo().get().execute() # Generate a JSON response with the file data and return to the client. self.RespondJSON(result) except AccessTokenRefreshError: # Catch AccessTokenRefreshError which occurs when the API client library # fails to refresh a token. This occurs, for example, when a refresh token # is revoked. When this happens the user is redirected to the # Authorization URL. self.RedirectAuth() class AboutHandler(BaseDriveHandler): """Web handler for the service to read user information.""" def get(self): """Called when HTTP GET requests are received by the web application.""" # Create a Drive service service = self.CreateDrive() if service is None: return try: result = service.about().get().execute() # Generate a JSON response with the file data and return to the client. self.RespondJSON(result) except AccessTokenRefreshError: # Catch AccessTokenRefreshError which occurs when the API client library # fails to refresh a token. This occurs, for example, when a refresh token # is revoked. When this happens the user is redirected to the # Authorization URL. self.RedirectAuth() class MediaInMemoryUpload(MediaUpload): """MediaUpload for a chunk of bytes. Construct a MediaFileUpload and pass as the media_body parameter of the method. For example, if we had a service that allowed plain text: """ def __init__(self, body, mimetype='application/octet-stream', chunksize=256*1024, resumable=False): """Create a new MediaBytesUpload. Args: body: string, Bytes of body content. mimetype: string, Mime-type of the file or default of 'application/octet-stream'. chunksize: int, File will be uploaded in chunks of this many bytes. Only used if resumable=True. resumable: bool, True if this is a resumable upload. False means upload in a single request. """ self._body = body self._mimetype = mimetype self._resumable = resumable self._chunksize = chunksize def chunksize(self): """Chunk size for resumable uploads. Returns: Chunk size in bytes. """ return self._chunksize def mimetype(self): """Mime type of the body. Returns: Mime type. """ return self._mimetype def size(self): """Size of upload. Returns: Size of the body. """ return len(self._body) def resumable(self): """Whether this upload is resumable. Returns: True if resumable upload or False. """ return self._resumable def getbytes(self, begin, length): """Get bytes from the media. Args: begin: int, offset from beginning of file. length: int, number of bytes to read, starting at begin. Returns: A string of bytes read. May be shorter than length if EOF was reached first. """ return self._body[begin:begin + length] # Create an WSGI application suitable for running on App Engine application = webapp.WSGIApplication( [('/', MainPage), ('/svc', ServiceHandler), ('/about', AboutHandler), ('/user', UserHandler)], # XXX Set to False in production. debug=True ) def main(): """Main entry point for executing a request with this handler.""" run_wsgi_app(application) if __name__ == "__main__": main()
Python
#!/usr/bin/env python # # Copyright (c) 2002, Google Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following disclaimer # in the documentation and/or other materials provided with the # distribution. # * Neither the name of Google Inc. nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # # --- # Author: Chad Lester # Design and style contributions by: # Amit Patel, Bogdan Cocosel, Daniel Dulitz, Eric Tiedemann, # Eric Veach, Laurence Gonsalves, Matthew Springer # Code reorganized a bit by Craig Silverstein """This module is used to define and parse command line flags. This module defines a *distributed* flag-definition policy: rather than an application having to define all flags in or near main(), each python module defines flags that are useful to it. When one python module imports another, it gains access to the other's flags. (This is implemented by having all modules share a common, global registry object containing all the flag information.) Flags are defined through the use of one of the DEFINE_xxx functions. The specific function used determines how the flag is parsed, checked, and optionally type-converted, when it's seen on the command line. IMPLEMENTATION: DEFINE_* creates a 'Flag' object and registers it with a 'FlagValues' object (typically the global FlagValues FLAGS, defined here). The 'FlagValues' object can scan the command line arguments and pass flag arguments to the corresponding 'Flag' objects for value-checking and type conversion. The converted flag values are available as attributes of the 'FlagValues' object. Code can access the flag through a FlagValues object, for instance gflags.FLAGS.myflag. Typically, the __main__ module passes the command line arguments to gflags.FLAGS for parsing. At bottom, this module calls getopt(), so getopt functionality is supported, including short- and long-style flags, and the use of -- to terminate flags. Methods defined by the flag module will throw 'FlagsError' exceptions. The exception argument will be a human-readable string. FLAG TYPES: This is a list of the DEFINE_*'s that you can do. All flags take a name, default value, help-string, and optional 'short' name (one-letter name). Some flags have other arguments, which are described with the flag. DEFINE_string: takes any input, and interprets it as a string. DEFINE_bool or DEFINE_boolean: typically does not take an argument: say --myflag to set FLAGS.myflag to true, or --nomyflag to set FLAGS.myflag to false. Alternately, you can say --myflag=true or --myflag=t or --myflag=1 or --myflag=false or --myflag=f or --myflag=0 DEFINE_float: takes an input and interprets it as a floating point number. Takes optional args lower_bound and upper_bound; if the number specified on the command line is out of range, it will raise a FlagError. DEFINE_integer: takes an input and interprets it as an integer. Takes optional args lower_bound and upper_bound as for floats. DEFINE_enum: takes a list of strings which represents legal values. If the command-line value is not in this list, raise a flag error. Otherwise, assign to FLAGS.flag as a string. DEFINE_list: Takes a comma-separated list of strings on the commandline. Stores them in a python list object. DEFINE_spaceseplist: Takes a space-separated list of strings on the commandline. Stores them in a python list object. Example: --myspacesepflag "foo bar baz" DEFINE_multistring: The same as DEFINE_string, except the flag can be specified more than once on the commandline. The result is a python list object (list of strings), even if the flag is only on the command line once. DEFINE_multi_int: The same as DEFINE_integer, except the flag can be specified more than once on the commandline. The result is a python list object (list of ints), even if the flag is only on the command line once. SPECIAL FLAGS: There are a few flags that have special meaning: --help prints a list of all the flags in a human-readable fashion --helpshort prints a list of all key flags (see below). --helpxml prints a list of all flags, in XML format. DO NOT parse the output of --help and --helpshort. Instead, parse the output of --helpxml. For more info, see "OUTPUT FOR --helpxml" below. --flagfile=foo read flags from file foo. --undefok=f1,f2 ignore unrecognized option errors for f1,f2. For boolean flags, you should use --undefok=boolflag, and --boolflag and --noboolflag will be accepted. Do not use --undefok=noboolflag. -- as in getopt(), terminates flag-processing FLAGS VALIDATORS: If your program: - requires flag X to be specified - needs flag Y to match a regular expression - or requires any more general constraint to be satisfied then validators are for you! Each validator represents a constraint over one flag, which is enforced starting from the initial parsing of the flags and until the program terminates. Also, lower_bound and upper_bound for numerical flags are enforced using flag validators. Howto: If you want to enforce a constraint over one flag, use gflags.RegisterValidator(flag_name, checker, message='Flag validation failed', flag_values=FLAGS) After flag values are initially parsed, and after any change to the specified flag, method checker(flag_value) will be executed. If constraint is not satisfied, an IllegalFlagValue exception will be raised. See RegisterValidator's docstring for a detailed explanation on how to construct your own checker. EXAMPLE USAGE: FLAGS = gflags.FLAGS gflags.DEFINE_integer('my_version', 0, 'Version number.') gflags.DEFINE_string('filename', None, 'Input file name', short_name='f') gflags.RegisterValidator('my_version', lambda value: value % 2 == 0, message='--my_version must be divisible by 2') gflags.MarkFlagAsRequired('filename') NOTE ON --flagfile: Flags may be loaded from text files in addition to being specified on the commandline. Any flags you don't feel like typing, throw them in a file, one flag per line, for instance: --myflag=myvalue --nomyboolean_flag You then specify your file with the special flag '--flagfile=somefile'. You CAN recursively nest flagfile= tokens OR use multiple files on the command line. Lines beginning with a single hash '#' or a double slash '//' are comments in your flagfile. Any flagfile=<file> will be interpreted as having a relative path from the current working directory rather than from the place the file was included from: myPythonScript.py --flagfile=config/somefile.cfg If somefile.cfg includes further --flagfile= directives, these will be referenced relative to the original CWD, not from the directory the including flagfile was found in! The caveat applies to people who are including a series of nested files in a different dir than they are executing out of. Relative path names are always from CWD, not from the directory of the parent include flagfile. We do now support '~' expanded directory names. Absolute path names ALWAYS work! EXAMPLE USAGE: FLAGS = gflags.FLAGS # Flag names are globally defined! So in general, we need to be # careful to pick names that are unlikely to be used by other libraries. # If there is a conflict, we'll get an error at import time. gflags.DEFINE_string('name', 'Mr. President', 'your name') gflags.DEFINE_integer('age', None, 'your age in years', lower_bound=0) gflags.DEFINE_boolean('debug', False, 'produces debugging output') gflags.DEFINE_enum('gender', 'male', ['male', 'female'], 'your gender') def main(argv): try: argv = FLAGS(argv) # parse flags except gflags.FlagsError, e: print '%s\\nUsage: %s ARGS\\n%s' % (e, sys.argv[0], FLAGS) sys.exit(1) if FLAGS.debug: print 'non-flag arguments:', argv print 'Happy Birthday', FLAGS.name if FLAGS.age is not None: print 'You are a %d year old %s' % (FLAGS.age, FLAGS.gender) if __name__ == '__main__': main(sys.argv) KEY FLAGS: As we already explained, each module gains access to all flags defined by all the other modules it transitively imports. In the case of non-trivial scripts, this means a lot of flags ... For documentation purposes, it is good to identify the flags that are key (i.e., really important) to a module. Clearly, the concept of "key flag" is a subjective one. When trying to determine whether a flag is key to a module or not, assume that you are trying to explain your module to a potential user: which flags would you really like to mention first? We'll describe shortly how to declare which flags are key to a module. For the moment, assume we know the set of key flags for each module. Then, if you use the app.py module, you can use the --helpshort flag to print only the help for the flags that are key to the main module, in a human-readable format. NOTE: If you need to parse the flag help, do NOT use the output of --help / --helpshort. That output is meant for human consumption, and may be changed in the future. Instead, use --helpxml; flags that are key for the main module are marked there with a <key>yes</key> element. The set of key flags for a module M is composed of: 1. Flags defined by module M by calling a DEFINE_* function. 2. Flags that module M explictly declares as key by using the function DECLARE_key_flag(<flag_name>) 3. Key flags of other modules that M specifies by using the function ADOPT_module_key_flags(<other_module>) This is a "bulk" declaration of key flags: each flag that is key for <other_module> becomes key for the current module too. Notice that if you do not use the functions described at points 2 and 3 above, then --helpshort prints information only about the flags defined by the main module of our script. In many cases, this behavior is good enough. But if you move part of the main module code (together with the related flags) into a different module, then it is nice to use DECLARE_key_flag / ADOPT_module_key_flags and make sure --helpshort lists all relevant flags (otherwise, your code refactoring may confuse your users). Note: each of DECLARE_key_flag / ADOPT_module_key_flags has its own pluses and minuses: DECLARE_key_flag is more targeted and may lead a more focused --helpshort documentation. ADOPT_module_key_flags is good for cases when an entire module is considered key to the current script. Also, it does not require updates to client scripts when a new flag is added to the module. EXAMPLE USAGE 2 (WITH KEY FLAGS): Consider an application that contains the following three files (two auxiliary modules and a main module) File libfoo.py: import gflags gflags.DEFINE_integer('num_replicas', 3, 'Number of replicas to start') gflags.DEFINE_boolean('rpc2', True, 'Turn on the usage of RPC2.') ... some code ... File libbar.py: import gflags gflags.DEFINE_string('bar_gfs_path', '/gfs/path', 'Path to the GFS files for libbar.') gflags.DEFINE_string('email_for_bar_errors', 'bar-team@google.com', 'Email address for bug reports about module libbar.') gflags.DEFINE_boolean('bar_risky_hack', False, 'Turn on an experimental and buggy optimization.') ... some code ... File myscript.py: import gflags import libfoo import libbar gflags.DEFINE_integer('num_iterations', 0, 'Number of iterations.') # Declare that all flags that are key for libfoo are # key for this module too. gflags.ADOPT_module_key_flags(libfoo) # Declare that the flag --bar_gfs_path (defined in libbar) is key # for this module. gflags.DECLARE_key_flag('bar_gfs_path') ... some code ... When myscript is invoked with the flag --helpshort, the resulted help message lists information about all the key flags for myscript: --num_iterations, --num_replicas, --rpc2, and --bar_gfs_path. Of course, myscript uses all the flags declared by it (in this case, just --num_replicas) or by any of the modules it transitively imports (e.g., the modules libfoo, libbar). E.g., it can access the value of FLAGS.bar_risky_hack, even if --bar_risky_hack is not declared as a key flag for myscript. OUTPUT FOR --helpxml: The --helpxml flag generates output with the following structure: <?xml version="1.0"?> <AllFlags> <program>PROGRAM_BASENAME</program> <usage>MAIN_MODULE_DOCSTRING</usage> (<flag> [<key>yes</key>] <file>DECLARING_MODULE</file> <name>FLAG_NAME</name> <meaning>FLAG_HELP_MESSAGE</meaning> <default>DEFAULT_FLAG_VALUE</default> <current>CURRENT_FLAG_VALUE</current> <type>FLAG_TYPE</type> [OPTIONAL_ELEMENTS] </flag>)* </AllFlags> Notes: 1. The output is intentionally similar to the output generated by the C++ command-line flag library. The few differences are due to the Python flags that do not have a C++ equivalent (at least not yet), e.g., DEFINE_list. 2. New XML elements may be added in the future. 3. DEFAULT_FLAG_VALUE is in serialized form, i.e., the string you can pass for this flag on the command-line. E.g., for a flag defined using DEFINE_list, this field may be foo,bar, not ['foo', 'bar']. 4. CURRENT_FLAG_VALUE is produced using str(). This means that the string 'false' will be represented in the same way as the boolean False. Using repr() would have removed this ambiguity and simplified parsing, but would have broken the compatibility with the C++ command-line flags. 5. OPTIONAL_ELEMENTS describe elements relevant for certain kinds of flags: lower_bound, upper_bound (for flags that specify bounds), enum_value (for enum flags), list_separator (for flags that consist of a list of values, separated by a special token). 6. We do not provide any example here: please use --helpxml instead. This module requires at least python 2.2.1 to run. """ import cgi import getopt import os import re import string import struct import sys # pylint: disable-msg=C6204 try: import fcntl except ImportError: fcntl = None try: # Importing termios will fail on non-unix platforms. import termios except ImportError: termios = None import gflags_validators # pylint: enable-msg=C6204 # Are we running under pychecker? _RUNNING_PYCHECKER = 'pychecker.python' in sys.modules def _GetCallingModuleObjectAndName(): """Returns the module that's calling into this module. We generally use this function to get the name of the module calling a DEFINE_foo... function. """ # Walk down the stack to find the first globals dict that's not ours. for depth in range(1, sys.getrecursionlimit()): if not sys._getframe(depth).f_globals is globals(): globals_for_frame = sys._getframe(depth).f_globals module, module_name = _GetModuleObjectAndName(globals_for_frame) if module_name is not None: return module, module_name raise AssertionError("No module was found") def _GetCallingModule(): """Returns the name of the module that's calling into this module.""" return _GetCallingModuleObjectAndName()[1] def _GetThisModuleObjectAndName(): """Returns: (module object, module name) for this module.""" return _GetModuleObjectAndName(globals()) # module exceptions: class FlagsError(Exception): """The base class for all flags errors.""" pass class DuplicateFlag(FlagsError): """Raised if there is a flag naming conflict.""" pass class CantOpenFlagFileError(FlagsError): """Raised if flagfile fails to open: doesn't exist, wrong permissions, etc.""" pass class DuplicateFlagCannotPropagateNoneToSwig(DuplicateFlag): """Special case of DuplicateFlag -- SWIG flag value can't be set to None. This can be raised when a duplicate flag is created. Even if allow_override is True, we still abort if the new value is None, because it's currently impossible to pass None default value back to SWIG. See FlagValues.SetDefault for details. """ pass class DuplicateFlagError(DuplicateFlag): """A DuplicateFlag whose message cites the conflicting definitions. A DuplicateFlagError conveys more information than a DuplicateFlag, namely the modules where the conflicting definitions occur. This class was created to avoid breaking external modules which depend on the existing DuplicateFlags interface. """ def __init__(self, flagname, flag_values, other_flag_values=None): """Create a DuplicateFlagError. Args: flagname: Name of the flag being redefined. flag_values: FlagValues object containing the first definition of flagname. other_flag_values: If this argument is not None, it should be the FlagValues object where the second definition of flagname occurs. If it is None, we assume that we're being called when attempting to create the flag a second time, and we use the module calling this one as the source of the second definition. """ self.flagname = flagname first_module = flag_values.FindModuleDefiningFlag( flagname, default='<unknown>') if other_flag_values is None: second_module = _GetCallingModule() else: second_module = other_flag_values.FindModuleDefiningFlag( flagname, default='<unknown>') msg = "The flag '%s' is defined twice. First from %s, Second from %s" % ( self.flagname, first_module, second_module) DuplicateFlag.__init__(self, msg) class IllegalFlagValue(FlagsError): """The flag command line argument is illegal.""" pass class UnrecognizedFlag(FlagsError): """Raised if a flag is unrecognized.""" pass # An UnrecognizedFlagError conveys more information than an UnrecognizedFlag. # Since there are external modules that create DuplicateFlags, the interface to # DuplicateFlag shouldn't change. The flagvalue will be assigned the full value # of the flag and its argument, if any, allowing handling of unrecognized flags # in an exception handler. # If flagvalue is the empty string, then this exception is an due to a # reference to a flag that was not already defined. class UnrecognizedFlagError(UnrecognizedFlag): def __init__(self, flagname, flagvalue=''): self.flagname = flagname self.flagvalue = flagvalue UnrecognizedFlag.__init__( self, "Unknown command line flag '%s'" % flagname) # Global variable used by expvar _exported_flags = {} _help_width = 80 # width of help output def GetHelpWidth(): """Returns: an integer, the width of help lines that is used in TextWrap.""" if (not sys.stdout.isatty()) or (termios is None) or (fcntl is None): return _help_width try: data = fcntl.ioctl(sys.stdout, termios.TIOCGWINSZ, '1234') columns = struct.unpack('hh', data)[1] # Emacs mode returns 0. # Here we assume that any value below 40 is unreasonable if columns >= 40: return columns # Returning an int as default is fine, int(int) just return the int. return int(os.getenv('COLUMNS', _help_width)) except (TypeError, IOError, struct.error): return _help_width def CutCommonSpacePrefix(text): """Removes a common space prefix from the lines of a multiline text. If the first line does not start with a space, it is left as it is and only in the remaining lines a common space prefix is being searched for. That means the first line will stay untouched. This is especially useful to turn doc strings into help texts. This is because some people prefer to have the doc comment start already after the apostrophe and then align the following lines while others have the apostrophes on a separate line. The function also drops trailing empty lines and ignores empty lines following the initial content line while calculating the initial common whitespace. Args: text: text to work on Returns: the resulting text """ text_lines = text.splitlines() # Drop trailing empty lines while text_lines and not text_lines[-1]: text_lines = text_lines[:-1] if text_lines: # We got some content, is the first line starting with a space? if text_lines[0] and text_lines[0][0].isspace(): text_first_line = [] else: text_first_line = [text_lines.pop(0)] # Calculate length of common leading whitespace (only over content lines) common_prefix = os.path.commonprefix([line for line in text_lines if line]) space_prefix_len = len(common_prefix) - len(common_prefix.lstrip()) # If we have a common space prefix, drop it from all lines if space_prefix_len: for index in xrange(len(text_lines)): if text_lines[index]: text_lines[index] = text_lines[index][space_prefix_len:] return '\n'.join(text_first_line + text_lines) return '' def TextWrap(text, length=None, indent='', firstline_indent=None, tabs=' '): """Wraps a given text to a maximum line length and returns it. We turn lines that only contain whitespace into empty lines. We keep new lines and tabs (e.g., we do not treat tabs as spaces). Args: text: text to wrap length: maximum length of a line, includes indentation if this is None then use GetHelpWidth() indent: indent for all but first line firstline_indent: indent for first line; if None, fall back to indent tabs: replacement for tabs Returns: wrapped text Raises: FlagsError: if indent not shorter than length FlagsError: if firstline_indent not shorter than length """ # Get defaults where callee used None if length is None: length = GetHelpWidth() if indent is None: indent = '' if len(indent) >= length: raise FlagsError('Indent must be shorter than length') # In line we will be holding the current line which is to be started # with indent (or firstline_indent if available) and then appended # with words. if firstline_indent is None: firstline_indent = '' line = indent else: line = firstline_indent if len(firstline_indent) >= length: raise FlagsError('First line indent must be shorter than length') # If the callee does not care about tabs we simply convert them to # spaces If callee wanted tabs to be single space then we do that # already here. if not tabs or tabs == ' ': text = text.replace('\t', ' ') else: tabs_are_whitespace = not tabs.strip() line_regex = re.compile('([ ]*)(\t*)([^ \t]+)', re.MULTILINE) # Split the text into lines and the lines with the regex above. The # resulting lines are collected in result[]. For each split we get the # spaces, the tabs and the next non white space (e.g. next word). result = [] for text_line in text.splitlines(): # Store result length so we can find out whether processing the next # line gave any new content old_result_len = len(result) # Process next line with line_regex. For optimization we do an rstrip(). # - process tabs (changes either line or word, see below) # - process word (first try to squeeze on line, then wrap or force wrap) # Spaces found on the line are ignored, they get added while wrapping as # needed. for spaces, current_tabs, word in line_regex.findall(text_line.rstrip()): # If tabs weren't converted to spaces, handle them now if current_tabs: # If the last thing we added was a space anyway then drop # it. But let's not get rid of the indentation. if (((result and line != indent) or (not result and line != firstline_indent)) and line[-1] == ' '): line = line[:-1] # Add the tabs, if that means adding whitespace, just add it at # the line, the rstrip() code while shorten the line down if # necessary if tabs_are_whitespace: line += tabs * len(current_tabs) else: # if not all tab replacement is whitespace we prepend it to the word word = tabs * len(current_tabs) + word # Handle the case where word cannot be squeezed onto current last line if len(line) + len(word) > length and len(indent) + len(word) <= length: result.append(line.rstrip()) line = indent + word word = '' # No space left on line or can we append a space? if len(line) + 1 >= length: result.append(line.rstrip()) line = indent else: line += ' ' # Add word and shorten it up to allowed line length. Restart next # line with indent and repeat, or add a space if we're done (word # finished) This deals with words that cannot fit on one line # (e.g. indent + word longer than allowed line length). while len(line) + len(word) >= length: line += word result.append(line[:length]) word = line[length:] line = indent # Default case, simply append the word and a space if word: line += word + ' ' # End of input line. If we have content we finish the line. If the # current line is just the indent but we had content in during this # original line then we need to add an empty line. if (result and line != indent) or (not result and line != firstline_indent): result.append(line.rstrip()) elif len(result) == old_result_len: result.append('') line = indent return '\n'.join(result) def DocToHelp(doc): """Takes a __doc__ string and reformats it as help.""" # Get rid of starting and ending white space. Using lstrip() or even # strip() could drop more than maximum of first line and right space # of last line. doc = doc.strip() # Get rid of all empty lines whitespace_only_line = re.compile('^[ \t]+$', re.M) doc = whitespace_only_line.sub('', doc) # Cut out common space at line beginnings doc = CutCommonSpacePrefix(doc) # Just like this module's comment, comments tend to be aligned somehow. # In other words they all start with the same amount of white space # 1) keep double new lines # 2) keep ws after new lines if not empty line # 3) all other new lines shall be changed to a space # Solution: Match new lines between non white space and replace with space. doc = re.sub('(?<=\S)\n(?=\S)', ' ', doc, re.M) return doc def _GetModuleObjectAndName(globals_dict): """Returns the module that defines a global environment, and its name. Args: globals_dict: A dictionary that should correspond to an environment providing the values of the globals. Returns: A pair consisting of (1) module object and (2) module name (a string). Returns (None, None) if the module could not be identified. """ # The use of .items() (instead of .iteritems()) is NOT a mistake: if # a parallel thread imports a module while we iterate over # .iteritems() (not nice, but possible), we get a RuntimeError ... # Hence, we use the slightly slower but safer .items(). for name, module in sys.modules.items(): if getattr(module, '__dict__', None) is globals_dict: if name == '__main__': # Pick a more informative name for the main module. name = sys.argv[0] return (module, name) return (None, None) def _GetMainModule(): """Returns: string, name of the module from which execution started.""" # First, try to use the same logic used by _GetCallingModuleObjectAndName(), # i.e., call _GetModuleObjectAndName(). For that we first need to # find the dictionary that the main module uses to store the # globals. # # That's (normally) the same dictionary object that the deepest # (oldest) stack frame is using for globals. deepest_frame = sys._getframe(0) while deepest_frame.f_back is not None: deepest_frame = deepest_frame.f_back globals_for_main_module = deepest_frame.f_globals main_module_name = _GetModuleObjectAndName(globals_for_main_module)[1] # The above strategy fails in some cases (e.g., tools that compute # code coverage by redefining, among other things, the main module). # If so, just use sys.argv[0]. We can probably always do this, but # it's safest to try to use the same logic as _GetCallingModuleObjectAndName() if main_module_name is None: main_module_name = sys.argv[0] return main_module_name class FlagValues: """Registry of 'Flag' objects. A 'FlagValues' can then scan command line arguments, passing flag arguments through to the 'Flag' objects that it owns. It also provides easy access to the flag values. Typically only one 'FlagValues' object is needed by an application: gflags.FLAGS This class is heavily overloaded: 'Flag' objects are registered via __setitem__: FLAGS['longname'] = x # register a new flag The .value attribute of the registered 'Flag' objects can be accessed as attributes of this 'FlagValues' object, through __getattr__. Both the long and short name of the original 'Flag' objects can be used to access its value: FLAGS.longname # parsed flag value FLAGS.x # parsed flag value (short name) Command line arguments are scanned and passed to the registered 'Flag' objects through the __call__ method. Unparsed arguments, including argv[0] (e.g. the program name) are returned. argv = FLAGS(sys.argv) # scan command line arguments The original registered Flag objects can be retrieved through the use of the dictionary-like operator, __getitem__: x = FLAGS['longname'] # access the registered Flag object The str() operator of a 'FlagValues' object provides help for all of the registered 'Flag' objects. """ def __init__(self): # Since everything in this class is so heavily overloaded, the only # way of defining and using fields is to access __dict__ directly. # Dictionary: flag name (string) -> Flag object. self.__dict__['__flags'] = {} # Dictionary: module name (string) -> list of Flag objects that are defined # by that module. self.__dict__['__flags_by_module'] = {} # Dictionary: module id (int) -> list of Flag objects that are defined by # that module. self.__dict__['__flags_by_module_id'] = {} # Dictionary: module name (string) -> list of Flag objects that are # key for that module. self.__dict__['__key_flags_by_module'] = {} # Set if we should use new style gnu_getopt rather than getopt when parsing # the args. Only possible with Python 2.3+ self.UseGnuGetOpt(False) def UseGnuGetOpt(self, use_gnu_getopt=True): """Use GNU-style scanning. Allows mixing of flag and non-flag arguments. See http://docs.python.org/library/getopt.html#getopt.gnu_getopt Args: use_gnu_getopt: wether or not to use GNU style scanning. """ self.__dict__['__use_gnu_getopt'] = use_gnu_getopt def IsGnuGetOpt(self): return self.__dict__['__use_gnu_getopt'] def FlagDict(self): return self.__dict__['__flags'] def FlagsByModuleDict(self): """Returns the dictionary of module_name -> list of defined flags. Returns: A dictionary. Its keys are module names (strings). Its values are lists of Flag objects. """ return self.__dict__['__flags_by_module'] def FlagsByModuleIdDict(self): """Returns the dictionary of module_id -> list of defined flags. Returns: A dictionary. Its keys are module IDs (ints). Its values are lists of Flag objects. """ return self.__dict__['__flags_by_module_id'] def KeyFlagsByModuleDict(self): """Returns the dictionary of module_name -> list of key flags. Returns: A dictionary. Its keys are module names (strings). Its values are lists of Flag objects. """ return self.__dict__['__key_flags_by_module'] def _RegisterFlagByModule(self, module_name, flag): """Records the module that defines a specific flag. We keep track of which flag is defined by which module so that we can later sort the flags by module. Args: module_name: A string, the name of a Python module. flag: A Flag object, a flag that is key to the module. """ flags_by_module = self.FlagsByModuleDict() flags_by_module.setdefault(module_name, []).append(flag) def _RegisterFlagByModuleId(self, module_id, flag): """Records the module that defines a specific flag. Args: module_id: An int, the ID of the Python module. flag: A Flag object, a flag that is key to the module. """ flags_by_module_id = self.FlagsByModuleIdDict() flags_by_module_id.setdefault(module_id, []).append(flag) def _RegisterKeyFlagForModule(self, module_name, flag): """Specifies that a flag is a key flag for a module. Args: module_name: A string, the name of a Python module. flag: A Flag object, a flag that is key to the module. """ key_flags_by_module = self.KeyFlagsByModuleDict() # The list of key flags for the module named module_name. key_flags = key_flags_by_module.setdefault(module_name, []) # Add flag, but avoid duplicates. if flag not in key_flags: key_flags.append(flag) def _GetFlagsDefinedByModule(self, module): """Returns the list of flags defined by a module. Args: module: A module object or a module name (a string). Returns: A new list of Flag objects. Caller may update this list as he wishes: none of those changes will affect the internals of this FlagValue object. """ if not isinstance(module, str): module = module.__name__ return list(self.FlagsByModuleDict().get(module, [])) def _GetKeyFlagsForModule(self, module): """Returns the list of key flags for a module. Args: module: A module object or a module name (a string) Returns: A new list of Flag objects. Caller may update this list as he wishes: none of those changes will affect the internals of this FlagValue object. """ if not isinstance(module, str): module = module.__name__ # Any flag is a key flag for the module that defined it. NOTE: # key_flags is a fresh list: we can update it without affecting the # internals of this FlagValues object. key_flags = self._GetFlagsDefinedByModule(module) # Take into account flags explicitly declared as key for a module. for flag in self.KeyFlagsByModuleDict().get(module, []): if flag not in key_flags: key_flags.append(flag) return key_flags def FindModuleDefiningFlag(self, flagname, default=None): """Return the name of the module defining this flag, or default. Args: flagname: Name of the flag to lookup. default: Value to return if flagname is not defined. Defaults to None. Returns: The name of the module which registered the flag with this name. If no such module exists (i.e. no flag with this name exists), we return default. """ for module, flags in self.FlagsByModuleDict().iteritems(): for flag in flags: if flag.name == flagname or flag.short_name == flagname: return module return default def FindModuleIdDefiningFlag(self, flagname, default=None): """Return the ID of the module defining this flag, or default. Args: flagname: Name of the flag to lookup. default: Value to return if flagname is not defined. Defaults to None. Returns: The ID of the module which registered the flag with this name. If no such module exists (i.e. no flag with this name exists), we return default. """ for module_id, flags in self.FlagsByModuleIdDict().iteritems(): for flag in flags: if flag.name == flagname or flag.short_name == flagname: return module_id return default def AppendFlagValues(self, flag_values): """Appends flags registered in another FlagValues instance. Args: flag_values: registry to copy from """ for flag_name, flag in flag_values.FlagDict().iteritems(): # Each flags with shortname appears here twice (once under its # normal name, and again with its short name). To prevent # problems (DuplicateFlagError) with double flag registration, we # perform a check to make sure that the entry we're looking at is # for its normal name. if flag_name == flag.name: try: self[flag_name] = flag except DuplicateFlagError: raise DuplicateFlagError(flag_name, self, other_flag_values=flag_values) def RemoveFlagValues(self, flag_values): """Remove flags that were previously appended from another FlagValues. Args: flag_values: registry containing flags to remove. """ for flag_name in flag_values.FlagDict(): self.__delattr__(flag_name) def __setitem__(self, name, flag): """Registers a new flag variable.""" fl = self.FlagDict() if not isinstance(flag, Flag): raise IllegalFlagValue(flag) if not isinstance(name, type("")): raise FlagsError("Flag name must be a string") if len(name) == 0: raise FlagsError("Flag name cannot be empty") # If running under pychecker, duplicate keys are likely to be # defined. Disable check for duplicate keys when pycheck'ing. if (name in fl and not flag.allow_override and not fl[name].allow_override and not _RUNNING_PYCHECKER): module, module_name = _GetCallingModuleObjectAndName() if (self.FindModuleDefiningFlag(name) == module_name and id(module) != self.FindModuleIdDefiningFlag(name)): # If the flag has already been defined by a module with the same name, # but a different ID, we can stop here because it indicates that the # module is simply being imported a subsequent time. return raise DuplicateFlagError(name, self) short_name = flag.short_name if short_name is not None: if (short_name in fl and not flag.allow_override and not fl[short_name].allow_override and not _RUNNING_PYCHECKER): raise DuplicateFlagError(short_name, self) fl[short_name] = flag fl[name] = flag global _exported_flags _exported_flags[name] = flag def __getitem__(self, name): """Retrieves the Flag object for the flag --name.""" return self.FlagDict()[name] def __getattr__(self, name): """Retrieves the 'value' attribute of the flag --name.""" fl = self.FlagDict() if name not in fl: raise AttributeError(name) return fl[name].value def __setattr__(self, name, value): """Sets the 'value' attribute of the flag --name.""" fl = self.FlagDict() fl[name].value = value self._AssertValidators(fl[name].validators) return value def _AssertAllValidators(self): all_validators = set() for flag in self.FlagDict().itervalues(): for validator in flag.validators: all_validators.add(validator) self._AssertValidators(all_validators) def _AssertValidators(self, validators): """Assert if all validators in the list are satisfied. Asserts validators in the order they were created. Args: validators: Iterable(gflags_validators.Validator), validators to be verified Raises: AttributeError: if validators work with a non-existing flag. IllegalFlagValue: if validation fails for at least one validator """ for validator in sorted( validators, key=lambda validator: validator.insertion_index): try: validator.Verify(self) except gflags_validators.Error, e: message = validator.PrintFlagsWithValues(self) raise IllegalFlagValue('%s: %s' % (message, str(e))) def _FlagIsRegistered(self, flag_obj): """Checks whether a Flag object is registered under some name. Note: this is non trivial: in addition to its normal name, a flag may have a short name too. In self.FlagDict(), both the normal and the short name are mapped to the same flag object. E.g., calling only "del FLAGS.short_name" is not unregistering the corresponding Flag object (it is still registered under the longer name). Args: flag_obj: A Flag object. Returns: A boolean: True iff flag_obj is registered under some name. """ flag_dict = self.FlagDict() # Check whether flag_obj is registered under its long name. name = flag_obj.name if flag_dict.get(name, None) == flag_obj: return True # Check whether flag_obj is registered under its short name. short_name = flag_obj.short_name if (short_name is not None and flag_dict.get(short_name, None) == flag_obj): return True # The flag cannot be registered under any other name, so we do not # need to do a full search through the values of self.FlagDict(). return False def __delattr__(self, flag_name): """Deletes a previously-defined flag from a flag object. This method makes sure we can delete a flag by using del flag_values_object.<flag_name> E.g., gflags.DEFINE_integer('foo', 1, 'Integer flag.') del gflags.FLAGS.foo Args: flag_name: A string, the name of the flag to be deleted. Raises: AttributeError: When there is no registered flag named flag_name. """ fl = self.FlagDict() if flag_name not in fl: raise AttributeError(flag_name) flag_obj = fl[flag_name] del fl[flag_name] if not self._FlagIsRegistered(flag_obj): # If the Flag object indicated by flag_name is no longer # registered (please see the docstring of _FlagIsRegistered), then # we delete the occurrences of the flag object in all our internal # dictionaries. self.__RemoveFlagFromDictByModule(self.FlagsByModuleDict(), flag_obj) self.__RemoveFlagFromDictByModule(self.FlagsByModuleIdDict(), flag_obj) self.__RemoveFlagFromDictByModule(self.KeyFlagsByModuleDict(), flag_obj) def __RemoveFlagFromDictByModule(self, flags_by_module_dict, flag_obj): """Removes a flag object from a module -> list of flags dictionary. Args: flags_by_module_dict: A dictionary that maps module names to lists of flags. flag_obj: A flag object. """ for unused_module, flags_in_module in flags_by_module_dict.iteritems(): # while (as opposed to if) takes care of multiple occurrences of a # flag in the list for the same module. while flag_obj in flags_in_module: flags_in_module.remove(flag_obj) def SetDefault(self, name, value): """Changes the default value of the named flag object.""" fl = self.FlagDict() if name not in fl: raise AttributeError(name) fl[name].SetDefault(value) self._AssertValidators(fl[name].validators) def __contains__(self, name): """Returns True if name is a value (flag) in the dict.""" return name in self.FlagDict() has_key = __contains__ # a synonym for __contains__() def __iter__(self): return iter(self.FlagDict()) def __call__(self, argv): """Parses flags from argv; stores parsed flags into this FlagValues object. All unparsed arguments are returned. Flags are parsed using the GNU Program Argument Syntax Conventions, using getopt: http://www.gnu.org/software/libc/manual/html_mono/libc.html#Getopt Args: argv: argument list. Can be of any type that may be converted to a list. Returns: The list of arguments not parsed as options, including argv[0] Raises: FlagsError: on any parsing error """ # Support any sequence type that can be converted to a list argv = list(argv) shortopts = "" longopts = [] fl = self.FlagDict() # This pre parses the argv list for --flagfile=<> options. argv = argv[:1] + self.ReadFlagsFromFiles(argv[1:], force_gnu=False) # Correct the argv to support the google style of passing boolean # parameters. Boolean parameters may be passed by using --mybool, # --nomybool, --mybool=(true|false|1|0). getopt does not support # having options that may or may not have a parameter. We replace # instances of the short form --mybool and --nomybool with their # full forms: --mybool=(true|false). original_argv = list(argv) # list() makes a copy shortest_matches = None for name, flag in fl.items(): if not flag.boolean: continue if shortest_matches is None: # Determine the smallest allowable prefix for all flag names shortest_matches = self.ShortestUniquePrefixes(fl) no_name = 'no' + name prefix = shortest_matches[name] no_prefix = shortest_matches[no_name] # Replace all occurrences of this boolean with extended forms for arg_idx in range(1, len(argv)): arg = argv[arg_idx] if arg.find('=') >= 0: continue if arg.startswith('--'+prefix) and ('--'+name).startswith(arg): argv[arg_idx] = ('--%s=true' % name) elif arg.startswith('--'+no_prefix) and ('--'+no_name).startswith(arg): argv[arg_idx] = ('--%s=false' % name) # Loop over all of the flags, building up the lists of short options # and long options that will be passed to getopt. Short options are # specified as a string of letters, each letter followed by a colon # if it takes an argument. Long options are stored in an array of # strings. Each string ends with an '=' if it takes an argument. for name, flag in fl.items(): longopts.append(name + "=") if len(name) == 1: # one-letter option: allow short flag type also shortopts += name if not flag.boolean: shortopts += ":" longopts.append('undefok=') undefok_flags = [] # In case --undefok is specified, loop to pick up unrecognized # options one by one. unrecognized_opts = [] args = argv[1:] while True: try: if self.__dict__['__use_gnu_getopt']: optlist, unparsed_args = getopt.gnu_getopt(args, shortopts, longopts) else: optlist, unparsed_args = getopt.getopt(args, shortopts, longopts) break except getopt.GetoptError, e: if not e.opt or e.opt in fl: # Not an unrecognized option, re-raise the exception as a FlagsError raise FlagsError(e) # Remove offender from args and try again for arg_index in range(len(args)): if ((args[arg_index] == '--' + e.opt) or (args[arg_index] == '-' + e.opt) or (args[arg_index].startswith('--' + e.opt + '='))): unrecognized_opts.append((e.opt, args[arg_index])) args = args[0:arg_index] + args[arg_index+1:] break else: # We should have found the option, so we don't expect to get # here. We could assert, but raising the original exception # might work better. raise FlagsError(e) for name, arg in optlist: if name == '--undefok': flag_names = arg.split(',') undefok_flags.extend(flag_names) # For boolean flags, if --undefok=boolflag is specified, then we should # also accept --noboolflag, in addition to --boolflag. # Since we don't know the type of the undefok'd flag, this will affect # non-boolean flags as well. # NOTE: You shouldn't use --undefok=noboolflag, because then we will # accept --nonoboolflag here. We are choosing not to do the conversion # from noboolflag -> boolflag because of the ambiguity that flag names # can start with 'no'. undefok_flags.extend('no' + name for name in flag_names) continue if name.startswith('--'): # long option name = name[2:] short_option = 0 else: # short option name = name[1:] short_option = 1 if name in fl: flag = fl[name] if flag.boolean and short_option: arg = 1 flag.Parse(arg) # If there were unrecognized options, raise an exception unless # the options were named via --undefok. for opt, value in unrecognized_opts: if opt not in undefok_flags: raise UnrecognizedFlagError(opt, value) if unparsed_args: if self.__dict__['__use_gnu_getopt']: # if using gnu_getopt just return the program name + remainder of argv. ret_val = argv[:1] + unparsed_args else: # unparsed_args becomes the first non-flag detected by getopt to # the end of argv. Because argv may have been modified above, # return original_argv for this region. ret_val = argv[:1] + original_argv[-len(unparsed_args):] else: ret_val = argv[:1] self._AssertAllValidators() return ret_val def Reset(self): """Resets the values to the point before FLAGS(argv) was called.""" for f in self.FlagDict().values(): f.Unparse() def RegisteredFlags(self): """Returns: a list of the names and short names of all registered flags.""" return list(self.FlagDict()) def FlagValuesDict(self): """Returns: a dictionary that maps flag names to flag values.""" flag_values = {} for flag_name in self.RegisteredFlags(): flag = self.FlagDict()[flag_name] flag_values[flag_name] = flag.value return flag_values def __str__(self): """Generates a help string for all known flags.""" return self.GetHelp() def GetHelp(self, prefix=''): """Generates a help string for all known flags.""" helplist = [] flags_by_module = self.FlagsByModuleDict() if flags_by_module: modules = sorted(flags_by_module) # Print the help for the main module first, if possible. main_module = _GetMainModule() if main_module in modules: modules.remove(main_module) modules = [main_module] + modules for module in modules: self.__RenderOurModuleFlags(module, helplist) self.__RenderModuleFlags('gflags', _SPECIAL_FLAGS.FlagDict().values(), helplist) else: # Just print one long list of flags. self.__RenderFlagList( self.FlagDict().values() + _SPECIAL_FLAGS.FlagDict().values(), helplist, prefix) return '\n'.join(helplist) def __RenderModuleFlags(self, module, flags, output_lines, prefix=""): """Generates a help string for a given module.""" if not isinstance(module, str): module = module.__name__ output_lines.append('\n%s%s:' % (prefix, module)) self.__RenderFlagList(flags, output_lines, prefix + " ") def __RenderOurModuleFlags(self, module, output_lines, prefix=""): """Generates a help string for a given module.""" flags = self._GetFlagsDefinedByModule(module) if flags: self.__RenderModuleFlags(module, flags, output_lines, prefix) def __RenderOurModuleKeyFlags(self, module, output_lines, prefix=""): """Generates a help string for the key flags of a given module. Args: module: A module object or a module name (a string). output_lines: A list of strings. The generated help message lines will be appended to this list. prefix: A string that is prepended to each generated help line. """ key_flags = self._GetKeyFlagsForModule(module) if key_flags: self.__RenderModuleFlags(module, key_flags, output_lines, prefix) def ModuleHelp(self, module): """Describe the key flags of a module. Args: module: A module object or a module name (a string). Returns: string describing the key flags of a module. """ helplist = [] self.__RenderOurModuleKeyFlags(module, helplist) return '\n'.join(helplist) def MainModuleHelp(self): """Describe the key flags of the main module. Returns: string describing the key flags of a module. """ return self.ModuleHelp(_GetMainModule()) def __RenderFlagList(self, flaglist, output_lines, prefix=" "): fl = self.FlagDict() special_fl = _SPECIAL_FLAGS.FlagDict() flaglist = [(flag.name, flag) for flag in flaglist] flaglist.sort() flagset = {} for (name, flag) in flaglist: # It's possible this flag got deleted or overridden since being # registered in the per-module flaglist. Check now against the # canonical source of current flag information, the FlagDict. if fl.get(name, None) != flag and special_fl.get(name, None) != flag: # a different flag is using this name now continue # only print help once if flag in flagset: continue flagset[flag] = 1 flaghelp = "" if flag.short_name: flaghelp += "-%s," % flag.short_name if flag.boolean: flaghelp += "--[no]%s" % flag.name + ":" else: flaghelp += "--%s" % flag.name + ":" flaghelp += " " if flag.help: flaghelp += flag.help flaghelp = TextWrap(flaghelp, indent=prefix+" ", firstline_indent=prefix) if flag.default_as_str: flaghelp += "\n" flaghelp += TextWrap("(default: %s)" % flag.default_as_str, indent=prefix+" ") if flag.parser.syntactic_help: flaghelp += "\n" flaghelp += TextWrap("(%s)" % flag.parser.syntactic_help, indent=prefix+" ") output_lines.append(flaghelp) def get(self, name, default): """Returns the value of a flag (if not None) or a default value. Args: name: A string, the name of a flag. default: Default value to use if the flag value is None. """ value = self.__getattr__(name) if value is not None: # Can't do if not value, b/c value might be '0' or "" return value else: return default def ShortestUniquePrefixes(self, fl): """Returns: dictionary; maps flag names to their shortest unique prefix.""" # Sort the list of flag names sorted_flags = [] for name, flag in fl.items(): sorted_flags.append(name) if flag.boolean: sorted_flags.append('no%s' % name) sorted_flags.sort() # For each name in the sorted list, determine the shortest unique # prefix by comparing itself to the next name and to the previous # name (the latter check uses cached info from the previous loop). shortest_matches = {} prev_idx = 0 for flag_idx in range(len(sorted_flags)): curr = sorted_flags[flag_idx] if flag_idx == (len(sorted_flags) - 1): next = None else: next = sorted_flags[flag_idx+1] next_len = len(next) for curr_idx in range(len(curr)): if (next is None or curr_idx >= next_len or curr[curr_idx] != next[curr_idx]): # curr longer than next or no more chars in common shortest_matches[curr] = curr[:max(prev_idx, curr_idx) + 1] prev_idx = curr_idx break else: # curr shorter than (or equal to) next shortest_matches[curr] = curr prev_idx = curr_idx + 1 # next will need at least one more char return shortest_matches def __IsFlagFileDirective(self, flag_string): """Checks whether flag_string contain a --flagfile=<foo> directive.""" if isinstance(flag_string, type("")): if flag_string.startswith('--flagfile='): return 1 elif flag_string == '--flagfile': return 1 elif flag_string.startswith('-flagfile='): return 1 elif flag_string == '-flagfile': return 1 else: return 0 return 0 def ExtractFilename(self, flagfile_str): """Returns filename from a flagfile_str of form -[-]flagfile=filename. The cases of --flagfile foo and -flagfile foo shouldn't be hitting this function, as they are dealt with in the level above this function. """ if flagfile_str.startswith('--flagfile='): return os.path.expanduser((flagfile_str[(len('--flagfile=')):]).strip()) elif flagfile_str.startswith('-flagfile='): return os.path.expanduser((flagfile_str[(len('-flagfile=')):]).strip()) else: raise FlagsError('Hit illegal --flagfile type: %s' % flagfile_str) def __GetFlagFileLines(self, filename, parsed_file_list): """Returns the useful (!=comments, etc) lines from a file with flags. Args: filename: A string, the name of the flag file. parsed_file_list: A list of the names of the files we have already read. MUTATED BY THIS FUNCTION. Returns: List of strings. See the note below. NOTE(springer): This function checks for a nested --flagfile=<foo> tag and handles the lower file recursively. It returns a list of all the lines that _could_ contain command flags. This is EVERYTHING except whitespace lines and comments (lines starting with '#' or '//'). """ line_list = [] # All line from flagfile. flag_line_list = [] # Subset of lines w/o comments, blanks, flagfile= tags. try: file_obj = open(filename, 'r') except IOError, e_msg: raise CantOpenFlagFileError('ERROR:: Unable to open flagfile: %s' % e_msg) line_list = file_obj.readlines() file_obj.close() parsed_file_list.append(filename) # This is where we check each line in the file we just read. for line in line_list: if line.isspace(): pass # Checks for comment (a line that starts with '#'). elif line.startswith('#') or line.startswith('//'): pass # Checks for a nested "--flagfile=<bar>" flag in the current file. # If we find one, recursively parse down into that file. elif self.__IsFlagFileDirective(line): sub_filename = self.ExtractFilename(line) # We do a little safety check for reparsing a file we've already done. if not sub_filename in parsed_file_list: included_flags = self.__GetFlagFileLines(sub_filename, parsed_file_list) flag_line_list.extend(included_flags) else: # Case of hitting a circularly included file. sys.stderr.write('Warning: Hit circular flagfile dependency: %s\n' % (sub_filename,)) else: # Any line that's not a comment or a nested flagfile should get # copied into 2nd position. This leaves earlier arguments # further back in the list, thus giving them higher priority. flag_line_list.append(line.strip()) return flag_line_list def ReadFlagsFromFiles(self, argv, force_gnu=True): """Processes command line args, but also allow args to be read from file. Args: argv: A list of strings, usually sys.argv[1:], which may contain one or more flagfile directives of the form --flagfile="./filename". Note that the name of the program (sys.argv[0]) should be omitted. force_gnu: If False, --flagfile parsing obeys normal flag semantics. If True, --flagfile parsing instead follows gnu_getopt semantics. *** WARNING *** force_gnu=False may become the future default! Returns: A new list which has the original list combined with what we read from any flagfile(s). References: Global gflags.FLAG class instance. This function should be called before the normal FLAGS(argv) call. This function scans the input list for a flag that looks like: --flagfile=<somefile>. Then it opens <somefile>, reads all valid key and value pairs and inserts them into the input list between the first item of the list and any subsequent items in the list. Note that your application's flags are still defined the usual way using gflags DEFINE_flag() type functions. Notes (assuming we're getting a commandline of some sort as our input): --> Flags from the command line argv _should_ always take precedence! --> A further "--flagfile=<otherfile.cfg>" CAN be nested in a flagfile. It will be processed after the parent flag file is done. --> For duplicate flags, first one we hit should "win". --> In a flagfile, a line beginning with # or // is a comment. --> Entirely blank lines _should_ be ignored. """ parsed_file_list = [] rest_of_args = argv new_argv = [] while rest_of_args: current_arg = rest_of_args[0] rest_of_args = rest_of_args[1:] if self.__IsFlagFileDirective(current_arg): # This handles the case of -(-)flagfile foo. In this case the # next arg really is part of this one. if current_arg == '--flagfile' or current_arg == '-flagfile': if not rest_of_args: raise IllegalFlagValue('--flagfile with no argument') flag_filename = os.path.expanduser(rest_of_args[0]) rest_of_args = rest_of_args[1:] else: # This handles the case of (-)-flagfile=foo. flag_filename = self.ExtractFilename(current_arg) new_argv.extend( self.__GetFlagFileLines(flag_filename, parsed_file_list)) else: new_argv.append(current_arg) # Stop parsing after '--', like getopt and gnu_getopt. if current_arg == '--': break # Stop parsing after a non-flag, like getopt. if not current_arg.startswith('-'): if not force_gnu and not self.__dict__['__use_gnu_getopt']: break if rest_of_args: new_argv.extend(rest_of_args) return new_argv def FlagsIntoString(self): """Returns a string with the flags assignments from this FlagValues object. This function ignores flags whose value is None. Each flag assignment is separated by a newline. NOTE: MUST mirror the behavior of the C++ CommandlineFlagsIntoString from http://code.google.com/p/google-gflags """ s = '' for flag in self.FlagDict().values(): if flag.value is not None: s += flag.Serialize() + '\n' return s def AppendFlagsIntoFile(self, filename): """Appends all flags assignments from this FlagInfo object to a file. Output will be in the format of a flagfile. NOTE: MUST mirror the behavior of the C++ AppendFlagsIntoFile from http://code.google.com/p/google-gflags """ out_file = open(filename, 'a') out_file.write(self.FlagsIntoString()) out_file.close() def WriteHelpInXMLFormat(self, outfile=None): """Outputs flag documentation in XML format. NOTE: We use element names that are consistent with those used by the C++ command-line flag library, from http://code.google.com/p/google-gflags We also use a few new elements (e.g., <key>), but we do not interfere / overlap with existing XML elements used by the C++ library. Please maintain this consistency. Args: outfile: File object we write to. Default None means sys.stdout. """ outfile = outfile or sys.stdout outfile.write('<?xml version=\"1.0\"?>\n') outfile.write('<AllFlags>\n') indent = ' ' _WriteSimpleXMLElement(outfile, 'program', os.path.basename(sys.argv[0]), indent) usage_doc = sys.modules['__main__'].__doc__ if not usage_doc: usage_doc = '\nUSAGE: %s [flags]\n' % sys.argv[0] else: usage_doc = usage_doc.replace('%s', sys.argv[0]) _WriteSimpleXMLElement(outfile, 'usage', usage_doc, indent) # Get list of key flags for the main module. key_flags = self._GetKeyFlagsForModule(_GetMainModule()) # Sort flags by declaring module name and next by flag name. flags_by_module = self.FlagsByModuleDict() all_module_names = list(flags_by_module.keys()) all_module_names.sort() for module_name in all_module_names: flag_list = [(f.name, f) for f in flags_by_module[module_name]] flag_list.sort() for unused_flag_name, flag in flag_list: is_key = flag in key_flags flag.WriteInfoInXMLFormat(outfile, module_name, is_key=is_key, indent=indent) outfile.write('</AllFlags>\n') outfile.flush() def AddValidator(self, validator): """Register new flags validator to be checked. Args: validator: gflags_validators.Validator Raises: AttributeError: if validators work with a non-existing flag. """ for flag_name in validator.GetFlagsNames(): flag = self.FlagDict()[flag_name] flag.validators.append(validator) # end of FlagValues definition # The global FlagValues instance FLAGS = FlagValues() def _StrOrUnicode(value): """Converts value to a python string or, if necessary, unicode-string.""" try: return str(value) except UnicodeEncodeError: return unicode(value) def _MakeXMLSafe(s): """Escapes <, >, and & from s, and removes XML 1.0-illegal chars.""" s = cgi.escape(s) # Escape <, >, and & # Remove characters that cannot appear in an XML 1.0 document # (http://www.w3.org/TR/REC-xml/#charsets). # # NOTE: if there are problems with current solution, one may move to # XML 1.1, which allows such chars, if they're entity-escaped (&#xHH;). s = re.sub(r'[\x00-\x08\x0b\x0c\x0e-\x1f]', '', s) # Convert non-ascii characters to entities. Note: requires python >=2.3 s = s.encode('ascii', 'xmlcharrefreplace') # u'\xce\x88' -> 'u&#904;' return s def _WriteSimpleXMLElement(outfile, name, value, indent): """Writes a simple XML element. Args: outfile: File object we write the XML element to. name: A string, the name of XML element. value: A Python object, whose string representation will be used as the value of the XML element. indent: A string, prepended to each line of generated output. """ value_str = _StrOrUnicode(value) if isinstance(value, bool): # Display boolean values as the C++ flag library does: no caps. value_str = value_str.lower() safe_value_str = _MakeXMLSafe(value_str) outfile.write('%s<%s>%s</%s>\n' % (indent, name, safe_value_str, name)) class Flag: """Information about a command-line flag. 'Flag' objects define the following fields: .name - the name for this flag .default - the default value for this flag .default_as_str - default value as repr'd string, e.g., "'true'" (or None) .value - the most recent parsed value of this flag; set by Parse() .help - a help string or None if no help is available .short_name - the single letter alias for this flag (or None) .boolean - if 'true', this flag does not accept arguments .present - true if this flag was parsed from command line flags. .parser - an ArgumentParser object .serializer - an ArgumentSerializer object .allow_override - the flag may be redefined without raising an error The only public method of a 'Flag' object is Parse(), but it is typically only called by a 'FlagValues' object. The Parse() method is a thin wrapper around the 'ArgumentParser' Parse() method. The parsed value is saved in .value, and the .present attribute is updated. If this flag was already present, a FlagsError is raised. Parse() is also called during __init__ to parse the default value and initialize the .value attribute. This enables other python modules to safely use flags even if the __main__ module neglects to parse the command line arguments. The .present attribute is cleared after __init__ parsing. If the default value is set to None, then the __init__ parsing step is skipped and the .value attribute is initialized to None. Note: The default value is also presented to the user in the help string, so it is important that it be a legal value for this flag. """ def __init__(self, parser, serializer, name, default, help_string, short_name=None, boolean=0, allow_override=0): self.name = name if not help_string: help_string = '(no help available)' self.help = help_string self.short_name = short_name self.boolean = boolean self.present = 0 self.parser = parser self.serializer = serializer self.allow_override = allow_override self.value = None self.validators = [] self.SetDefault(default) def __hash__(self): return hash(id(self)) def __eq__(self, other): return self is other def __lt__(self, other): if isinstance(other, Flag): return id(self) < id(other) return NotImplemented def __GetParsedValueAsString(self, value): if value is None: return None if self.serializer: return repr(self.serializer.Serialize(value)) if self.boolean: if value: return repr('true') else: return repr('false') return repr(_StrOrUnicode(value)) def Parse(self, argument): try: self.value = self.parser.Parse(argument) except ValueError, e: # recast ValueError as IllegalFlagValue raise IllegalFlagValue("flag --%s=%s: %s" % (self.name, argument, e)) self.present += 1 def Unparse(self): if self.default is None: self.value = None else: self.Parse(self.default) self.present = 0 def Serialize(self): if self.value is None: return '' if self.boolean: if self.value: return "--%s" % self.name else: return "--no%s" % self.name else: if not self.serializer: raise FlagsError("Serializer not present for flag %s" % self.name) return "--%s=%s" % (self.name, self.serializer.Serialize(self.value)) def SetDefault(self, value): """Changes the default value (and current value too) for this Flag.""" # We can't allow a None override because it may end up not being # passed to C++ code when we're overriding C++ flags. So we # cowardly bail out until someone fixes the semantics of trying to # pass None to a C++ flag. See swig_flags.Init() for details on # this behavior. # TODO(olexiy): Users can directly call this method, bypassing all flags # validators (we don't have FlagValues here, so we can not check # validators). # The simplest solution I see is to make this method private. # Another approach would be to store reference to the corresponding # FlagValues with each flag, but this seems to be an overkill. if value is None and self.allow_override: raise DuplicateFlagCannotPropagateNoneToSwig(self.name) self.default = value self.Unparse() self.default_as_str = self.__GetParsedValueAsString(self.value) def Type(self): """Returns: a string that describes the type of this Flag.""" # NOTE: we use strings, and not the types.*Type constants because # our flags can have more exotic types, e.g., 'comma separated list # of strings', 'whitespace separated list of strings', etc. return self.parser.Type() def WriteInfoInXMLFormat(self, outfile, module_name, is_key=False, indent=''): """Writes common info about this flag, in XML format. This is information that is relevant to all flags (e.g., name, meaning, etc.). If you defined a flag that has some other pieces of info, then please override _WriteCustomInfoInXMLFormat. Please do NOT override this method. Args: outfile: File object we write to. module_name: A string, the name of the module that defines this flag. is_key: A boolean, True iff this flag is key for main module. indent: A string that is prepended to each generated line. """ outfile.write(indent + '<flag>\n') inner_indent = indent + ' ' if is_key: _WriteSimpleXMLElement(outfile, 'key', 'yes', inner_indent) _WriteSimpleXMLElement(outfile, 'file', module_name, inner_indent) # Print flag features that are relevant for all flags. _WriteSimpleXMLElement(outfile, 'name', self.name, inner_indent) if self.short_name: _WriteSimpleXMLElement(outfile, 'short_name', self.short_name, inner_indent) if self.help: _WriteSimpleXMLElement(outfile, 'meaning', self.help, inner_indent) # The default flag value can either be represented as a string like on the # command line, or as a Python object. We serialize this value in the # latter case in order to remain consistent. if self.serializer and not isinstance(self.default, str): default_serialized = self.serializer.Serialize(self.default) else: default_serialized = self.default _WriteSimpleXMLElement(outfile, 'default', default_serialized, inner_indent) _WriteSimpleXMLElement(outfile, 'current', self.value, inner_indent) _WriteSimpleXMLElement(outfile, 'type', self.Type(), inner_indent) # Print extra flag features this flag may have. self._WriteCustomInfoInXMLFormat(outfile, inner_indent) outfile.write(indent + '</flag>\n') def _WriteCustomInfoInXMLFormat(self, outfile, indent): """Writes extra info about this flag, in XML format. "Extra" means "not already printed by WriteInfoInXMLFormat above." Args: outfile: File object we write to. indent: A string that is prepended to each generated line. """ # Usually, the parser knows the extra details about the flag, so # we just forward the call to it. self.parser.WriteCustomInfoInXMLFormat(outfile, indent) # End of Flag definition class _ArgumentParserCache(type): """Metaclass used to cache and share argument parsers among flags.""" _instances = {} def __call__(mcs, *args, **kwargs): """Returns an instance of the argument parser cls. This method overrides behavior of the __new__ methods in all subclasses of ArgumentParser (inclusive). If an instance for mcs with the same set of arguments exists, this instance is returned, otherwise a new instance is created. If any keyword arguments are defined, or the values in args are not hashable, this method always returns a new instance of cls. Args: args: Positional initializer arguments. kwargs: Initializer keyword arguments. Returns: An instance of cls, shared or new. """ if kwargs: return type.__call__(mcs, *args, **kwargs) else: instances = mcs._instances key = (mcs,) + tuple(args) try: return instances[key] except KeyError: # No cache entry for key exists, create a new one. return instances.setdefault(key, type.__call__(mcs, *args)) except TypeError: # An object in args cannot be hashed, always return # a new instance. return type.__call__(mcs, *args) class ArgumentParser(object): """Base class used to parse and convert arguments. The Parse() method checks to make sure that the string argument is a legal value and convert it to a native type. If the value cannot be converted, it should throw a 'ValueError' exception with a human readable explanation of why the value is illegal. Subclasses should also define a syntactic_help string which may be presented to the user to describe the form of the legal values. Argument parser classes must be stateless, since instances are cached and shared between flags. Initializer arguments are allowed, but all member variables must be derived from initializer arguments only. """ __metaclass__ = _ArgumentParserCache syntactic_help = "" def Parse(self, argument): """Default implementation: always returns its argument unmodified.""" return argument def Type(self): return 'string' def WriteCustomInfoInXMLFormat(self, outfile, indent): pass class ArgumentSerializer: """Base class for generating string representations of a flag value.""" def Serialize(self, value): return _StrOrUnicode(value) class ListSerializer(ArgumentSerializer): def __init__(self, list_sep): self.list_sep = list_sep def Serialize(self, value): return self.list_sep.join([_StrOrUnicode(x) for x in value]) # Flags validators def RegisterValidator(flag_name, checker, message='Flag validation failed', flag_values=FLAGS): """Adds a constraint, which will be enforced during program execution. The constraint is validated when flags are initially parsed, and after each change of the corresponding flag's value. Args: flag_name: string, name of the flag to be checked. checker: method to validate the flag. input - value of the corresponding flag (string, boolean, etc. This value will be passed to checker by the library). See file's docstring for examples. output - Boolean. Must return True if validator constraint is satisfied. If constraint is not satisfied, it should either return False or raise gflags_validators.Error(desired_error_message). message: error text to be shown to the user if checker returns False. If checker raises gflags_validators.Error, message from the raised Error will be shown. flag_values: FlagValues Raises: AttributeError: if flag_name is not registered as a valid flag name. """ flag_values.AddValidator(gflags_validators.SimpleValidator(flag_name, checker, message)) def MarkFlagAsRequired(flag_name, flag_values=FLAGS): """Ensure that flag is not None during program execution. Registers a flag validator, which will follow usual validator rules. Args: flag_name: string, name of the flag flag_values: FlagValues Raises: AttributeError: if flag_name is not registered as a valid flag name. """ RegisterValidator(flag_name, lambda value: value is not None, message='Flag --%s must be specified.' % flag_name, flag_values=flag_values) def _RegisterBoundsValidatorIfNeeded(parser, name, flag_values): """Enforce lower and upper bounds for numeric flags. Args: parser: NumericParser (either FloatParser or IntegerParser). Provides lower and upper bounds, and help text to display. name: string, name of the flag flag_values: FlagValues """ if parser.lower_bound is not None or parser.upper_bound is not None: def Checker(value): if value is not None and parser.IsOutsideBounds(value): message = '%s is not %s' % (value, parser.syntactic_help) raise gflags_validators.Error(message) return True RegisterValidator(name, Checker, flag_values=flag_values) # The DEFINE functions are explained in mode details in the module doc string. def DEFINE(parser, name, default, help, flag_values=FLAGS, serializer=None, **args): """Registers a generic Flag object. NOTE: in the docstrings of all DEFINE* functions, "registers" is short for "creates a new flag and registers it". Auxiliary function: clients should use the specialized DEFINE_<type> function instead. Args: parser: ArgumentParser that is used to parse the flag arguments. name: A string, the flag name. default: The default value of the flag. help: A help string. flag_values: FlagValues object the flag will be registered with. serializer: ArgumentSerializer that serializes the flag value. args: Dictionary with extra keyword args that are passes to the Flag __init__. """ DEFINE_flag(Flag(parser, serializer, name, default, help, **args), flag_values) def DEFINE_flag(flag, flag_values=FLAGS): """Registers a 'Flag' object with a 'FlagValues' object. By default, the global FLAGS 'FlagValue' object is used. Typical users will use one of the more specialized DEFINE_xxx functions, such as DEFINE_string or DEFINE_integer. But developers who need to create Flag objects themselves should use this function to register their flags. """ # copying the reference to flag_values prevents pychecker warnings fv = flag_values fv[flag.name] = flag # Tell flag_values who's defining the flag. if isinstance(flag_values, FlagValues): # Regarding the above isinstance test: some users pass funny # values of flag_values (e.g., {}) in order to avoid the flag # registration (in the past, there used to be a flag_values == # FLAGS test here) and redefine flags with the same name (e.g., # debug). To avoid breaking their code, we perform the # registration only if flag_values is a real FlagValues object. module, module_name = _GetCallingModuleObjectAndName() flag_values._RegisterFlagByModule(module_name, flag) flag_values._RegisterFlagByModuleId(id(module), flag) def _InternalDeclareKeyFlags(flag_names, flag_values=FLAGS, key_flag_values=None): """Declares a flag as key for the calling module. Internal function. User code should call DECLARE_key_flag or ADOPT_module_key_flags instead. Args: flag_names: A list of strings that are names of already-registered Flag objects. flag_values: A FlagValues object that the flags listed in flag_names have registered with (the value of the flag_values argument from the DEFINE_* calls that defined those flags). This should almost never need to be overridden. key_flag_values: A FlagValues object that (among possibly many other things) keeps track of the key flags for each module. Default None means "same as flag_values". This should almost never need to be overridden. Raises: UnrecognizedFlagError: when we refer to a flag that was not defined yet. """ key_flag_values = key_flag_values or flag_values module = _GetCallingModule() for flag_name in flag_names: if flag_name not in flag_values: raise UnrecognizedFlagError(flag_name) flag = flag_values.FlagDict()[flag_name] key_flag_values._RegisterKeyFlagForModule(module, flag) def DECLARE_key_flag(flag_name, flag_values=FLAGS): """Declares one flag as key to the current module. Key flags are flags that are deemed really important for a module. They are important when listing help messages; e.g., if the --helpshort command-line flag is used, then only the key flags of the main module are listed (instead of all flags, as in the case of --help). Sample usage: gflags.DECLARED_key_flag('flag_1') Args: flag_name: A string, the name of an already declared flag. (Redeclaring flags as key, including flags implicitly key because they were declared in this module, is a no-op.) flag_values: A FlagValues object. This should almost never need to be overridden. """ if flag_name in _SPECIAL_FLAGS: # Take care of the special flags, e.g., --flagfile, --undefok. # These flags are defined in _SPECIAL_FLAGS, and are treated # specially during flag parsing, taking precedence over the # user-defined flags. _InternalDeclareKeyFlags([flag_name], flag_values=_SPECIAL_FLAGS, key_flag_values=flag_values) return _InternalDeclareKeyFlags([flag_name], flag_values=flag_values) def ADOPT_module_key_flags(module, flag_values=FLAGS): """Declares that all flags key to a module are key to the current module. Args: module: A module object. flag_values: A FlagValues object. This should almost never need to be overridden. Raises: FlagsError: When given an argument that is a module name (a string), instead of a module object. """ # NOTE(salcianu): an even better test would be if not # isinstance(module, types.ModuleType) but I didn't want to import # types for such a tiny use. if isinstance(module, str): raise FlagsError('Received module name %s; expected a module object.' % module) _InternalDeclareKeyFlags( [f.name for f in flag_values._GetKeyFlagsForModule(module.__name__)], flag_values=flag_values) # If module is this flag module, take _SPECIAL_FLAGS into account. if module == _GetThisModuleObjectAndName()[0]: _InternalDeclareKeyFlags( # As we associate flags with _GetCallingModuleObjectAndName(), the # special flags defined in this module are incorrectly registered with # a different module. So, we can't use _GetKeyFlagsForModule. # Instead, we take all flags from _SPECIAL_FLAGS (a private # FlagValues, where no other module should register flags). [f.name for f in _SPECIAL_FLAGS.FlagDict().values()], flag_values=_SPECIAL_FLAGS, key_flag_values=flag_values) # # STRING FLAGS # def DEFINE_string(name, default, help, flag_values=FLAGS, **args): """Registers a flag whose value can be any string.""" parser = ArgumentParser() serializer = ArgumentSerializer() DEFINE(parser, name, default, help, flag_values, serializer, **args) # # BOOLEAN FLAGS # class BooleanParser(ArgumentParser): """Parser of boolean values.""" def Convert(self, argument): """Converts the argument to a boolean; raise ValueError on errors.""" if type(argument) == str: if argument.lower() in ['true', 't', '1']: return True elif argument.lower() in ['false', 'f', '0']: return False bool_argument = bool(argument) if argument == bool_argument: # The argument is a valid boolean (True, False, 0, or 1), and not just # something that always converts to bool (list, string, int, etc.). return bool_argument raise ValueError('Non-boolean argument to boolean flag', argument) def Parse(self, argument): val = self.Convert(argument) return val def Type(self): return 'bool' class BooleanFlag(Flag): """Basic boolean flag. Boolean flags do not take any arguments, and their value is either True (1) or False (0). The false value is specified on the command line by prepending the word 'no' to either the long or the short flag name. For example, if a Boolean flag was created whose long name was 'update' and whose short name was 'x', then this flag could be explicitly unset through either --noupdate or --nox. """ def __init__(self, name, default, help, short_name=None, **args): p = BooleanParser() Flag.__init__(self, p, None, name, default, help, short_name, 1, **args) if not self.help: self.help = "a boolean value" def DEFINE_boolean(name, default, help, flag_values=FLAGS, **args): """Registers a boolean flag. Such a boolean flag does not take an argument. If a user wants to specify a false value explicitly, the long option beginning with 'no' must be used: i.e. --noflag This flag will have a value of None, True or False. None is possible if default=None and the user does not specify the flag on the command line. """ DEFINE_flag(BooleanFlag(name, default, help, **args), flag_values) # Match C++ API to unconfuse C++ people. DEFINE_bool = DEFINE_boolean class HelpFlag(BooleanFlag): """ HelpFlag is a special boolean flag that prints usage information and raises a SystemExit exception if it is ever found in the command line arguments. Note this is called with allow_override=1, so other apps can define their own --help flag, replacing this one, if they want. """ def __init__(self): BooleanFlag.__init__(self, "help", 0, "show this help", short_name="?", allow_override=1) def Parse(self, arg): if arg: doc = sys.modules["__main__"].__doc__ flags = str(FLAGS) print doc or ("\nUSAGE: %s [flags]\n" % sys.argv[0]) if flags: print "flags:" print flags sys.exit(1) class HelpXMLFlag(BooleanFlag): """Similar to HelpFlag, but generates output in XML format.""" def __init__(self): BooleanFlag.__init__(self, 'helpxml', False, 'like --help, but generates XML output', allow_override=1) def Parse(self, arg): if arg: FLAGS.WriteHelpInXMLFormat(sys.stdout) sys.exit(1) class HelpshortFlag(BooleanFlag): """ HelpshortFlag is a special boolean flag that prints usage information for the "main" module, and rasies a SystemExit exception if it is ever found in the command line arguments. Note this is called with allow_override=1, so other apps can define their own --helpshort flag, replacing this one, if they want. """ def __init__(self): BooleanFlag.__init__(self, "helpshort", 0, "show usage only for this module", allow_override=1) def Parse(self, arg): if arg: doc = sys.modules["__main__"].__doc__ flags = FLAGS.MainModuleHelp() print doc or ("\nUSAGE: %s [flags]\n" % sys.argv[0]) if flags: print "flags:" print flags sys.exit(1) # # Numeric parser - base class for Integer and Float parsers # class NumericParser(ArgumentParser): """Parser of numeric values. Parsed value may be bounded to a given upper and lower bound. """ def IsOutsideBounds(self, val): return ((self.lower_bound is not None and val < self.lower_bound) or (self.upper_bound is not None and val > self.upper_bound)) def Parse(self, argument): val = self.Convert(argument) if self.IsOutsideBounds(val): raise ValueError("%s is not %s" % (val, self.syntactic_help)) return val def WriteCustomInfoInXMLFormat(self, outfile, indent): if self.lower_bound is not None: _WriteSimpleXMLElement(outfile, 'lower_bound', self.lower_bound, indent) if self.upper_bound is not None: _WriteSimpleXMLElement(outfile, 'upper_bound', self.upper_bound, indent) def Convert(self, argument): """Default implementation: always returns its argument unmodified.""" return argument # End of Numeric Parser # # FLOAT FLAGS # class FloatParser(NumericParser): """Parser of floating point values. Parsed value may be bounded to a given upper and lower bound. """ number_article = "a" number_name = "number" syntactic_help = " ".join((number_article, number_name)) def __init__(self, lower_bound=None, upper_bound=None): super(FloatParser, self).__init__() self.lower_bound = lower_bound self.upper_bound = upper_bound sh = self.syntactic_help if lower_bound is not None and upper_bound is not None: sh = ("%s in the range [%s, %s]" % (sh, lower_bound, upper_bound)) elif lower_bound == 0: sh = "a non-negative %s" % self.number_name elif upper_bound == 0: sh = "a non-positive %s" % self.number_name elif upper_bound is not None: sh = "%s <= %s" % (self.number_name, upper_bound) elif lower_bound is not None: sh = "%s >= %s" % (self.number_name, lower_bound) self.syntactic_help = sh def Convert(self, argument): """Converts argument to a float; raises ValueError on errors.""" return float(argument) def Type(self): return 'float' # End of FloatParser def DEFINE_float(name, default, help, lower_bound=None, upper_bound=None, flag_values=FLAGS, **args): """Registers a flag whose value must be a float. If lower_bound or upper_bound are set, then this flag must be within the given range. """ parser = FloatParser(lower_bound, upper_bound) serializer = ArgumentSerializer() DEFINE(parser, name, default, help, flag_values, serializer, **args) _RegisterBoundsValidatorIfNeeded(parser, name, flag_values=flag_values) # # INTEGER FLAGS # class IntegerParser(NumericParser): """Parser of an integer value. Parsed value may be bounded to a given upper and lower bound. """ number_article = "an" number_name = "integer" syntactic_help = " ".join((number_article, number_name)) def __init__(self, lower_bound=None, upper_bound=None): super(IntegerParser, self).__init__() self.lower_bound = lower_bound self.upper_bound = upper_bound sh = self.syntactic_help if lower_bound is not None and upper_bound is not None: sh = ("%s in the range [%s, %s]" % (sh, lower_bound, upper_bound)) elif lower_bound == 1: sh = "a positive %s" % self.number_name elif upper_bound == -1: sh = "a negative %s" % self.number_name elif lower_bound == 0: sh = "a non-negative %s" % self.number_name elif upper_bound == 0: sh = "a non-positive %s" % self.number_name elif upper_bound is not None: sh = "%s <= %s" % (self.number_name, upper_bound) elif lower_bound is not None: sh = "%s >= %s" % (self.number_name, lower_bound) self.syntactic_help = sh def Convert(self, argument): __pychecker__ = 'no-returnvalues' if type(argument) == str: base = 10 if len(argument) > 2 and argument[0] == "0" and argument[1] == "x": base = 16 return int(argument, base) else: return int(argument) def Type(self): return 'int' def DEFINE_integer(name, default, help, lower_bound=None, upper_bound=None, flag_values=FLAGS, **args): """Registers a flag whose value must be an integer. If lower_bound, or upper_bound are set, then this flag must be within the given range. """ parser = IntegerParser(lower_bound, upper_bound) serializer = ArgumentSerializer() DEFINE(parser, name, default, help, flag_values, serializer, **args) _RegisterBoundsValidatorIfNeeded(parser, name, flag_values=flag_values) # # ENUM FLAGS # class EnumParser(ArgumentParser): """Parser of a string enum value (a string value from a given set). If enum_values (see below) is not specified, any string is allowed. """ def __init__(self, enum_values=None): super(EnumParser, self).__init__() self.enum_values = enum_values def Parse(self, argument): if self.enum_values and argument not in self.enum_values: raise ValueError("value should be one of <%s>" % "|".join(self.enum_values)) return argument def Type(self): return 'string enum' class EnumFlag(Flag): """Basic enum flag; its value can be any string from list of enum_values.""" def __init__(self, name, default, help, enum_values=None, short_name=None, **args): enum_values = enum_values or [] p = EnumParser(enum_values) g = ArgumentSerializer() Flag.__init__(self, p, g, name, default, help, short_name, **args) if not self.help: self.help = "an enum string" self.help = "<%s>: %s" % ("|".join(enum_values), self.help) def _WriteCustomInfoInXMLFormat(self, outfile, indent): for enum_value in self.parser.enum_values: _WriteSimpleXMLElement(outfile, 'enum_value', enum_value, indent) def DEFINE_enum(name, default, enum_values, help, flag_values=FLAGS, **args): """Registers a flag whose value can be any string from enum_values.""" DEFINE_flag(EnumFlag(name, default, help, enum_values, ** args), flag_values) # # LIST FLAGS # class BaseListParser(ArgumentParser): """Base class for a parser of lists of strings. To extend, inherit from this class; from the subclass __init__, call BaseListParser.__init__(self, token, name) where token is a character used to tokenize, and name is a description of the separator. """ def __init__(self, token=None, name=None): assert name super(BaseListParser, self).__init__() self._token = token self._name = name self.syntactic_help = "a %s separated list" % self._name def Parse(self, argument): if isinstance(argument, list): return argument elif argument == '': return [] else: return [s.strip() for s in argument.split(self._token)] def Type(self): return '%s separated list of strings' % self._name class ListParser(BaseListParser): """Parser for a comma-separated list of strings.""" def __init__(self): BaseListParser.__init__(self, ',', 'comma') def WriteCustomInfoInXMLFormat(self, outfile, indent): BaseListParser.WriteCustomInfoInXMLFormat(self, outfile, indent) _WriteSimpleXMLElement(outfile, 'list_separator', repr(','), indent) class WhitespaceSeparatedListParser(BaseListParser): """Parser for a whitespace-separated list of strings.""" def __init__(self): BaseListParser.__init__(self, None, 'whitespace') def WriteCustomInfoInXMLFormat(self, outfile, indent): BaseListParser.WriteCustomInfoInXMLFormat(self, outfile, indent) separators = list(string.whitespace) separators.sort() for ws_char in string.whitespace: _WriteSimpleXMLElement(outfile, 'list_separator', repr(ws_char), indent) def DEFINE_list(name, default, help, flag_values=FLAGS, **args): """Registers a flag whose value is a comma-separated list of strings.""" parser = ListParser() serializer = ListSerializer(',') DEFINE(parser, name, default, help, flag_values, serializer, **args) def DEFINE_spaceseplist(name, default, help, flag_values=FLAGS, **args): """Registers a flag whose value is a whitespace-separated list of strings. Any whitespace can be used as a separator. """ parser = WhitespaceSeparatedListParser() serializer = ListSerializer(' ') DEFINE(parser, name, default, help, flag_values, serializer, **args) # # MULTI FLAGS # class MultiFlag(Flag): """A flag that can appear multiple time on the command-line. The value of such a flag is a list that contains the individual values from all the appearances of that flag on the command-line. See the __doc__ for Flag for most behavior of this class. Only differences in behavior are described here: * The default value may be either a single value or a list of values. A single value is interpreted as the [value] singleton list. * The value of the flag is always a list, even if the option was only supplied once, and even if the default value is a single value """ def __init__(self, *args, **kwargs): Flag.__init__(self, *args, **kwargs) self.help += ';\n repeat this option to specify a list of values' def Parse(self, arguments): """Parses one or more arguments with the installed parser. Args: arguments: a single argument or a list of arguments (typically a list of default values); a single argument is converted internally into a list containing one item. """ if not isinstance(arguments, list): # Default value may be a list of values. Most other arguments # will not be, so convert them into a single-item list to make # processing simpler below. arguments = [arguments] if self.present: # keep a backup reference to list of previously supplied option values values = self.value else: # "erase" the defaults with an empty list values = [] for item in arguments: # have Flag superclass parse argument, overwriting self.value reference Flag.Parse(self, item) # also increments self.present values.append(self.value) # put list of option values back in the 'value' attribute self.value = values def Serialize(self): if not self.serializer: raise FlagsError("Serializer not present for flag %s" % self.name) if self.value is None: return '' s = '' multi_value = self.value for self.value in multi_value: if s: s += ' ' s += Flag.Serialize(self) self.value = multi_value return s def Type(self): return 'multi ' + self.parser.Type() def DEFINE_multi(parser, serializer, name, default, help, flag_values=FLAGS, **args): """Registers a generic MultiFlag that parses its args with a given parser. Auxiliary function. Normal users should NOT use it directly. Developers who need to create their own 'Parser' classes for options which can appear multiple times can call this module function to register their flags. """ DEFINE_flag(MultiFlag(parser, serializer, name, default, help, **args), flag_values) def DEFINE_multistring(name, default, help, flag_values=FLAGS, **args): """Registers a flag whose value can be a list of any strings. Use the flag on the command line multiple times to place multiple string values into the list. The 'default' may be a single string (which will be converted into a single-element list) or a list of strings. """ parser = ArgumentParser() serializer = ArgumentSerializer() DEFINE_multi(parser, serializer, name, default, help, flag_values, **args) def DEFINE_multi_int(name, default, help, lower_bound=None, upper_bound=None, flag_values=FLAGS, **args): """Registers a flag whose value can be a list of arbitrary integers. Use the flag on the command line multiple times to place multiple integer values into the list. The 'default' may be a single integer (which will be converted into a single-element list) or a list of integers. """ parser = IntegerParser(lower_bound, upper_bound) serializer = ArgumentSerializer() DEFINE_multi(parser, serializer, name, default, help, flag_values, **args) def DEFINE_multi_float(name, default, help, lower_bound=None, upper_bound=None, flag_values=FLAGS, **args): """Registers a flag whose value can be a list of arbitrary floats. Use the flag on the command line multiple times to place multiple float values into the list. The 'default' may be a single float (which will be converted into a single-element list) or a list of floats. """ parser = FloatParser(lower_bound, upper_bound) serializer = ArgumentSerializer() DEFINE_multi(parser, serializer, name, default, help, flag_values, **args) # Now register the flags that we want to exist in all applications. # These are all defined with allow_override=1, so user-apps can use # these flagnames for their own purposes, if they want. DEFINE_flag(HelpFlag()) DEFINE_flag(HelpshortFlag()) DEFINE_flag(HelpXMLFlag()) # Define special flags here so that help may be generated for them. # NOTE: Please do NOT use _SPECIAL_FLAGS from outside this module. _SPECIAL_FLAGS = FlagValues() DEFINE_string( 'flagfile', "", "Insert flag definitions from the given file into the command line.", _SPECIAL_FLAGS) DEFINE_string( 'undefok', "", "comma-separated list of flag names that it is okay to specify " "on the command line even if the program does not define a flag " "with that name. IMPORTANT: flags in this list that have " "arguments MUST use the --flag=value format.", _SPECIAL_FLAGS)
Python
#!/usr/bin/env python # Copyright (c) 2010, Google Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following disclaimer # in the documentation and/or other materials provided with the # distribution. # * Neither the name of Google Inc. nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """Module to enforce different constraints on flags. A validator represents an invariant, enforced over a one or more flags. See 'FLAGS VALIDATORS' in gflags.py's docstring for a usage manual. """ __author__ = 'olexiy@google.com (Olexiy Oryeshko)' class Error(Exception): """Thrown If validator constraint is not satisfied.""" class Validator(object): """Base class for flags validators. Users should NOT overload these classes, and use gflags.Register... methods instead. """ # Used to assign each validator an unique insertion_index validators_count = 0 def __init__(self, checker, message): """Constructor to create all validators. Args: checker: function to verify the constraint. Input of this method varies, see SimpleValidator and DictionaryValidator for a detailed description. message: string, error message to be shown to the user """ self.checker = checker self.message = message Validator.validators_count += 1 # Used to assert validators in the order they were registered (CL/18694236) self.insertion_index = Validator.validators_count def Verify(self, flag_values): """Verify that constraint is satisfied. flags library calls this method to verify Validator's constraint. Args: flag_values: gflags.FlagValues, containing all flags Raises: Error: if constraint is not satisfied. """ param = self._GetInputToCheckerFunction(flag_values) if not self.checker(param): raise Error(self.message) def GetFlagsNames(self): """Return the names of the flags checked by this validator. Returns: [string], names of the flags """ raise NotImplementedError('This method should be overloaded') def PrintFlagsWithValues(self, flag_values): raise NotImplementedError('This method should be overloaded') def _GetInputToCheckerFunction(self, flag_values): """Given flag values, construct the input to be given to checker. Args: flag_values: gflags.FlagValues, containing all flags. Returns: Return type depends on the specific validator. """ raise NotImplementedError('This method should be overloaded') class SimpleValidator(Validator): """Validator behind RegisterValidator() method. Validates that a single flag passes its checker function. The checker function takes the flag value and returns True (if value looks fine) or, if flag value is not valid, either returns False or raises an Exception.""" def __init__(self, flag_name, checker, message): """Constructor. Args: flag_name: string, name of the flag. checker: function to verify the validator. input - value of the corresponding flag (string, boolean, etc). output - Boolean. Must return True if validator constraint is satisfied. If constraint is not satisfied, it should either return False or raise Error. message: string, error message to be shown to the user if validator's condition is not satisfied """ super(SimpleValidator, self).__init__(checker, message) self.flag_name = flag_name def GetFlagsNames(self): return [self.flag_name] def PrintFlagsWithValues(self, flag_values): return 'flag --%s=%s' % (self.flag_name, flag_values[self.flag_name].value) def _GetInputToCheckerFunction(self, flag_values): """Given flag values, construct the input to be given to checker. Args: flag_values: gflags.FlagValues Returns: value of the corresponding flag. """ return flag_values[self.flag_name].value class DictionaryValidator(Validator): """Validator behind RegisterDictionaryValidator method. Validates that flag values pass their common checker function. The checker function takes flag values and returns True (if values look fine) or, if values are not valid, either returns False or raises an Exception. """ def __init__(self, flag_names, checker, message): """Constructor. Args: flag_names: [string], containing names of the flags used by checker. checker: function to verify the validator. input - dictionary, with keys() being flag_names, and value for each key being the value of the corresponding flag (string, boolean, etc). output - Boolean. Must return True if validator constraint is satisfied. If constraint is not satisfied, it should either return False or raise Error. message: string, error message to be shown to the user if validator's condition is not satisfied """ super(DictionaryValidator, self).__init__(checker, message) self.flag_names = flag_names def _GetInputToCheckerFunction(self, flag_values): """Given flag values, construct the input to be given to checker. Args: flag_values: gflags.FlagValues Returns: dictionary, with keys() being self.lag_names, and value for each key being the value of the corresponding flag (string, boolean, etc). """ return dict([key, flag_values[key].value] for key in self.flag_names) def PrintFlagsWithValues(self, flag_values): prefix = 'flags ' flags_with_values = [] for key in self.flag_names: flags_with_values.append('%s=%s' % (key, flag_values[key].value)) return prefix + ', '.join(flags_with_values) def GetFlagsNames(self): return self.flag_names
Python
# Copyright (C) 2010 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Utilities for Google App Engine Utilities for making it easier to use OAuth 2.0 on Google App Engine. """ __author__ = 'jcgregorio@google.com (Joe Gregorio)' import base64 import httplib2 import logging import pickle import time import clientsecrets from anyjson import simplejson from client import AccessTokenRefreshError from client import AssertionCredentials from client import Credentials from client import Flow from client import OAuth2WebServerFlow from client import Storage from google.appengine.api import memcache from google.appengine.api import users from google.appengine.api import app_identity from google.appengine.ext import db from google.appengine.ext import webapp from google.appengine.ext.webapp.util import login_required from google.appengine.ext.webapp.util import run_wsgi_app OAUTH2CLIENT_NAMESPACE = 'oauth2client#ns' class InvalidClientSecretsError(Exception): """The client_secrets.json file is malformed or missing required fields.""" pass class AppAssertionCredentials(AssertionCredentials): """Credentials object for App Engine Assertion Grants This object will allow an App Engine application to identify itself to Google and other OAuth 2.0 servers that can verify assertions. It can be used for the purpose of accessing data stored under an account assigned to the App Engine application itself. This credential does not require a flow to instantiate because it represents a two legged flow, and therefore has all of the required information to generate and refresh its own access tokens. """ def __init__(self, scope, **kwargs): """Constructor for AppAssertionCredentials Args: scope: string or list of strings, scope(s) of the credentials being requested. """ if type(scope) is list: scope = ' '.join(scope) self.scope = scope super(AppAssertionCredentials, self).__init__( None, None, None) @classmethod def from_json(cls, json): data = simplejson.loads(json) return AppAssertionCredentials(data['scope']) def _refresh(self, http_request): """Refreshes the access_token. Since the underlying App Engine app_identity implementation does its own caching we can skip all the storage hoops and just to a refresh using the API. Args: http_request: callable, a callable that matches the method signature of httplib2.Http.request, used to make the refresh request. Raises: AccessTokenRefreshError: When the refresh fails. """ try: (token, _) = app_identity.get_access_token(self.scope) except app_identity.Error, e: raise AccessTokenRefreshError(str(e)) self.access_token = token class FlowProperty(db.Property): """App Engine datastore Property for Flow. Utility property that allows easy storage and retreival of an oauth2client.Flow""" # Tell what the user type is. data_type = Flow # For writing to datastore. def get_value_for_datastore(self, model_instance): flow = super(FlowProperty, self).get_value_for_datastore(model_instance) return db.Blob(pickle.dumps(flow)) # For reading from datastore. def make_value_from_datastore(self, value): if value is None: return None return pickle.loads(value) def validate(self, value): if value is not None and not isinstance(value, Flow): raise db.BadValueError('Property %s must be convertible ' 'to a FlowThreeLegged instance (%s)' % (self.name, value)) return super(FlowProperty, self).validate(value) def empty(self, value): return not value class CredentialsProperty(db.Property): """App Engine datastore Property for Credentials. Utility property that allows easy storage and retrieval of oath2client.Credentials """ # Tell what the user type is. data_type = Credentials # For writing to datastore. def get_value_for_datastore(self, model_instance): logging.info("get: Got type " + str(type(model_instance))) cred = super(CredentialsProperty, self).get_value_for_datastore(model_instance) if cred is None: cred = '' else: cred = cred.to_json() return db.Blob(cred) # For reading from datastore. def make_value_from_datastore(self, value): logging.info("make: Got type " + str(type(value))) if value is None: return None if len(value) == 0: return None try: credentials = Credentials.new_from_json(value) except ValueError: credentials = None return credentials def validate(self, value): value = super(CredentialsProperty, self).validate(value) logging.info("validate: Got type " + str(type(value))) if value is not None and not isinstance(value, Credentials): raise db.BadValueError('Property %s must be convertible ' 'to a Credentials instance (%s)' % (self.name, value)) #if value is not None and not isinstance(value, Credentials): # return None return value class StorageByKeyName(Storage): """Store and retrieve a single credential to and from the App Engine datastore. This Storage helper presumes the Credentials have been stored as a CredenialsProperty on a datastore model class, and that entities are stored by key_name. """ def __init__(self, model, key_name, property_name, cache=None): """Constructor for Storage. Args: model: db.Model, model class key_name: string, key name for the entity that has the credentials property_name: string, name of the property that is a CredentialsProperty cache: memcache, a write-through cache to put in front of the datastore """ self._model = model self._key_name = key_name self._property_name = property_name self._cache = cache def locked_get(self): """Retrieve Credential from datastore. Returns: oauth2client.Credentials """ if self._cache: json = self._cache.get(self._key_name) if json: return Credentials.new_from_json(json) credential = None entity = self._model.get_by_key_name(self._key_name) if entity is not None: credential = getattr(entity, self._property_name) if credential and hasattr(credential, 'set_store'): credential.set_store(self) if self._cache: self._cache.set(self._key_name, credential.to_json()) return credential def locked_put(self, credentials): """Write a Credentials to the datastore. Args: credentials: Credentials, the credentials to store. """ entity = self._model.get_or_insert(self._key_name) setattr(entity, self._property_name, credentials) entity.put() if self._cache: self._cache.set(self._key_name, credentials.to_json()) def locked_delete(self): """Delete Credential from datastore.""" if self._cache: self._cache.delete(self._key_name) entity = self._model.get_by_key_name(self._key_name) if entity is not None: entity.delete() class CredentialsModel(db.Model): """Storage for OAuth 2.0 Credentials Storage of the model is keyed by the user.user_id(). """ credentials = CredentialsProperty() class OAuth2Decorator(object): """Utility for making OAuth 2.0 easier. Instantiate and then use with oauth_required or oauth_aware as decorators on webapp.RequestHandler methods. Example: decorator = OAuth2Decorator( client_id='837...ent.com', client_secret='Qh...wwI', scope='https://www.googleapis.com/auth/plus') class MainHandler(webapp.RequestHandler): @decorator.oauth_required def get(self): http = decorator.http() # http is authorized with the user's Credentials and can be used # in API calls """ def __init__(self, client_id, client_secret, scope, auth_uri='https://accounts.google.com/o/oauth2/auth', token_uri='https://accounts.google.com/o/oauth2/token', user_agent=None, message=None, **kwargs): """Constructor for OAuth2Decorator Args: client_id: string, client identifier. client_secret: string client secret. scope: string or list of strings, scope(s) of the credentials being requested. auth_uri: string, URI for authorization endpoint. For convenience defaults to Google's endpoints but any OAuth 2.0 provider can be used. token_uri: string, URI for token endpoint. For convenience defaults to Google's endpoints but any OAuth 2.0 provider can be used. user_agent: string, User agent of your application, default to None. message: Message to display if there are problems with the OAuth 2.0 configuration. The message may contain HTML and will be presented on the web interface for any method that uses the decorator. **kwargs: dict, Keyword arguments are be passed along as kwargs to the OAuth2WebServerFlow constructor. """ self.flow = OAuth2WebServerFlow(client_id, client_secret, scope, user_agent, auth_uri, token_uri, **kwargs) self.credentials = None self._request_handler = None self._message = message self._in_error = False def _display_error_message(self, request_handler): request_handler.response.out.write('<html><body>') request_handler.response.out.write(self._message) request_handler.response.out.write('</body></html>') def oauth_required(self, method): """Decorator that starts the OAuth 2.0 dance. Starts the OAuth dance for the logged in user if they haven't already granted access for this application. Args: method: callable, to be decorated method of a webapp.RequestHandler instance. """ def check_oauth(request_handler, *args, **kwargs): if self._in_error: self._display_error_message(request_handler) return user = users.get_current_user() # Don't use @login_decorator as this could be used in a POST request. if not user: request_handler.redirect(users.create_login_url( request_handler.request.uri)) return # Store the request URI in 'state' so we can use it later self.flow.params['state'] = request_handler.request.url self._request_handler = request_handler self.credentials = StorageByKeyName( CredentialsModel, user.user_id(), 'credentials').get() if not self.has_credentials(): return request_handler.redirect(self.authorize_url()) try: method(request_handler, *args, **kwargs) except AccessTokenRefreshError: return request_handler.redirect(self.authorize_url()) return check_oauth def oauth_aware(self, method): """Decorator that sets up for OAuth 2.0 dance, but doesn't do it. Does all the setup for the OAuth dance, but doesn't initiate it. This decorator is useful if you want to create a page that knows whether or not the user has granted access to this application. From within a method decorated with @oauth_aware the has_credentials() and authorize_url() methods can be called. Args: method: callable, to be decorated method of a webapp.RequestHandler instance. """ def setup_oauth(request_handler, *args, **kwargs): if self._in_error: self._display_error_message(request_handler) return user = users.get_current_user() # Don't use @login_decorator as this could be used in a POST request. if not user: request_handler.redirect(users.create_login_url( request_handler.request.uri)) return self.flow.params['state'] = request_handler.request.url self._request_handler = request_handler self.credentials = StorageByKeyName( CredentialsModel, user.user_id(), 'credentials').get() method(request_handler, *args, **kwargs) return setup_oauth def has_credentials(self): """True if for the logged in user there are valid access Credentials. Must only be called from with a webapp.RequestHandler subclassed method that had been decorated with either @oauth_required or @oauth_aware. """ return self.credentials is not None and not self.credentials.invalid def authorize_url(self): """Returns the URL to start the OAuth dance. Must only be called from with a webapp.RequestHandler subclassed method that had been decorated with either @oauth_required or @oauth_aware. """ callback = self._request_handler.request.relative_url('/oauth2callback') url = self.flow.step1_get_authorize_url(callback) user = users.get_current_user() memcache.set(user.user_id(), pickle.dumps(self.flow), namespace=OAUTH2CLIENT_NAMESPACE) return str(url) def http(self): """Returns an authorized http instance. Must only be called from within an @oauth_required decorated method, or from within an @oauth_aware decorated method where has_credentials() returns True. """ return self.credentials.authorize(httplib2.Http()) class OAuth2DecoratorFromClientSecrets(OAuth2Decorator): """An OAuth2Decorator that builds from a clientsecrets file. Uses a clientsecrets file as the source for all the information when constructing an OAuth2Decorator. Example: decorator = OAuth2DecoratorFromClientSecrets( os.path.join(os.path.dirname(__file__), 'client_secrets.json') scope='https://www.googleapis.com/auth/plus') class MainHandler(webapp.RequestHandler): @decorator.oauth_required def get(self): http = decorator.http() # http is authorized with the user's Credentials and can be used # in API calls """ def __init__(self, filename, scope, message=None): """Constructor Args: filename: string, File name of client secrets. scope: string or list of strings, scope(s) of the credentials being requested. message: string, A friendly string to display to the user if the clientsecrets file is missing or invalid. The message may contain HTML and will be presented on the web interface for any method that uses the decorator. """ try: client_type, client_info = clientsecrets.loadfile(filename) if client_type not in [clientsecrets.TYPE_WEB, clientsecrets.TYPE_INSTALLED]: raise InvalidClientSecretsError('OAuth2Decorator doesn\'t support this OAuth 2.0 flow.') super(OAuth2DecoratorFromClientSecrets, self).__init__( client_info['client_id'], client_info['client_secret'], scope, client_info['auth_uri'], client_info['token_uri'], message) except clientsecrets.InvalidClientSecretsError: self._in_error = True if message is not None: self._message = message else: self._message = "Please configure your application for OAuth 2.0" def oauth2decorator_from_clientsecrets(filename, scope, message=None): """Creates an OAuth2Decorator populated from a clientsecrets file. Args: filename: string, File name of client secrets. scope: string or list of strings, scope(s) of the credentials being requested. message: string, A friendly string to display to the user if the clientsecrets file is missing or invalid. The message may contain HTML and will be presented on the web interface for any method that uses the decorator. Returns: An OAuth2Decorator """ return OAuth2DecoratorFromClientSecrets(filename, scope, message) class OAuth2Handler(webapp.RequestHandler): """Handler for the redirect_uri of the OAuth 2.0 dance.""" @login_required def get(self): error = self.request.get('error') if error: errormsg = self.request.get('error_description', error) self.response.out.write( 'The authorization request failed: %s' % errormsg) else: user = users.get_current_user() flow = pickle.loads(memcache.get(user.user_id(), namespace=OAUTH2CLIENT_NAMESPACE)) # This code should be ammended with application specific error # handling. The following cases should be considered: # 1. What if the flow doesn't exist in memcache? Or is corrupt? # 2. What if the step2_exchange fails? if flow: credentials = flow.step2_exchange(self.request.params) StorageByKeyName( CredentialsModel, user.user_id(), 'credentials').put(credentials) self.redirect(str(self.request.get('state'))) else: # TODO Add error handling here. pass application = webapp.WSGIApplication([('/oauth2callback', OAuth2Handler)]) def main(): run_wsgi_app(application)
Python
#!/usr/bin/python2.4 # -*- coding: utf-8 -*- # # Copyright (C) 2011 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import base64 import hashlib import logging import time from OpenSSL import crypto from anyjson import simplejson CLOCK_SKEW_SECS = 300 # 5 minutes in seconds AUTH_TOKEN_LIFETIME_SECS = 300 # 5 minutes in seconds MAX_TOKEN_LIFETIME_SECS = 86400 # 1 day in seconds class AppIdentityError(Exception): pass class Verifier(object): """Verifies the signature on a message.""" def __init__(self, pubkey): """Constructor. Args: pubkey, OpenSSL.crypto.PKey, The public key to verify with. """ self._pubkey = pubkey def verify(self, message, signature): """Verifies a message against a signature. Args: message: string, The message to verify. signature: string, The signature on the message. Returns: True if message was singed by the private key associated with the public key that this object was constructed with. """ try: crypto.verify(self._pubkey, signature, message, 'sha256') return True except: return False @staticmethod def from_string(key_pem, is_x509_cert): """Construct a Verified instance from a string. Args: key_pem: string, public key in PEM format. is_x509_cert: bool, True if key_pem is an X509 cert, otherwise it is expected to be an RSA key in PEM format. Returns: Verifier instance. Raises: OpenSSL.crypto.Error if the key_pem can't be parsed. """ if is_x509_cert: pubkey = crypto.load_certificate(crypto.FILETYPE_PEM, key_pem) else: pubkey = crypto.load_privatekey(crypto.FILETYPE_PEM, key_pem) return Verifier(pubkey) class Signer(object): """Signs messages with a private key.""" def __init__(self, pkey): """Constructor. Args: pkey, OpenSSL.crypto.PKey, The private key to sign with. """ self._key = pkey def sign(self, message): """Signs a message. Args: message: string, Message to be signed. Returns: string, The signature of the message for the given key. """ return crypto.sign(self._key, message, 'sha256') @staticmethod def from_string(key, password='notasecret'): """Construct a Signer instance from a string. Args: key: string, private key in P12 format. password: string, password for the private key file. Returns: Signer instance. Raises: OpenSSL.crypto.Error if the key can't be parsed. """ pkey = crypto.load_pkcs12(key, password).get_privatekey() return Signer(pkey) def _urlsafe_b64encode(raw_bytes): return base64.urlsafe_b64encode(raw_bytes).rstrip('=') def _urlsafe_b64decode(b64string): # Guard against unicode strings, which base64 can't handle. b64string = b64string.encode('ascii') padded = b64string + '=' * (4 - len(b64string) % 4) return base64.urlsafe_b64decode(padded) def _json_encode(data): return simplejson.dumps(data, separators = (',', ':')) def make_signed_jwt(signer, payload): """Make a signed JWT. See http://self-issued.info/docs/draft-jones-json-web-token.html. Args: signer: crypt.Signer, Cryptographic signer. payload: dict, Dictionary of data to convert to JSON and then sign. Returns: string, The JWT for the payload. """ header = {'typ': 'JWT', 'alg': 'RS256'} segments = [ _urlsafe_b64encode(_json_encode(header)), _urlsafe_b64encode(_json_encode(payload)), ] signing_input = '.'.join(segments) signature = signer.sign(signing_input) segments.append(_urlsafe_b64encode(signature)) logging.debug(str(segments)) return '.'.join(segments) def verify_signed_jwt_with_certs(jwt, certs, audience): """Verify a JWT against public certs. See http://self-issued.info/docs/draft-jones-json-web-token.html. Args: jwt: string, A JWT. certs: dict, Dictionary where values of public keys in PEM format. audience: string, The audience, 'aud', that this JWT should contain. If None then the JWT's 'aud' parameter is not verified. Returns: dict, The deserialized JSON payload in the JWT. Raises: AppIdentityError if any checks are failed. """ segments = jwt.split('.') if (len(segments) != 3): raise AppIdentityError( 'Wrong number of segments in token: %s' % jwt) signed = '%s.%s' % (segments[0], segments[1]) signature = _urlsafe_b64decode(segments[2]) # Parse token. json_body = _urlsafe_b64decode(segments[1]) try: parsed = simplejson.loads(json_body) except: raise AppIdentityError('Can\'t parse token: %s' % json_body) # Check signature. verified = False for (keyname, pem) in certs.items(): verifier = Verifier.from_string(pem, True) if (verifier.verify(signed, signature)): verified = True break if not verified: raise AppIdentityError('Invalid token signature: %s' % jwt) # Check creation timestamp. iat = parsed.get('iat') if iat is None: raise AppIdentityError('No iat field in token: %s' % json_body) earliest = iat - CLOCK_SKEW_SECS # Check expiration timestamp. now = long(time.time()) exp = parsed.get('exp') if exp is None: raise AppIdentityError('No exp field in token: %s' % json_body) if exp >= now + MAX_TOKEN_LIFETIME_SECS: raise AppIdentityError( 'exp field too far in future: %s' % json_body) latest = exp + CLOCK_SKEW_SECS if now < earliest: raise AppIdentityError('Token used too early, %d < %d: %s' % (now, earliest, json_body)) if now > latest: raise AppIdentityError('Token used too late, %d > %d: %s' % (now, latest, json_body)) # Check audience. if audience is not None: aud = parsed.get('aud') if aud is None: raise AppIdentityError('No aud field in token: %s' % json_body) if aud != audience: raise AppIdentityError('Wrong recipient, %s != %s: %s' % (aud, audience, json_body)) return parsed
Python
# Copyright 2011 Google Inc. All Rights Reserved. """Locked file interface that should work on Unix and Windows pythons. This module first tries to use fcntl locking to ensure serialized access to a file, then falls back on a lock file if that is unavialable. Usage: f = LockedFile('filename', 'r+b', 'rb') f.open_and_lock() if f.is_locked(): print 'Acquired filename with r+b mode' f.file_handle().write('locked data') else: print 'Aquired filename with rb mode' f.unlock_and_close() """ __author__ = 'cache@google.com (David T McWherter)' import errno import logging import os import time logger = logging.getLogger(__name__) class AlreadyLockedException(Exception): """Trying to lock a file that has already been locked by the LockedFile.""" pass class _Opener(object): """Base class for different locking primitives.""" def __init__(self, filename, mode, fallback_mode): """Create an Opener. Args: filename: string, The pathname of the file. mode: string, The preferred mode to access the file with. fallback_mode: string, The mode to use if locking fails. """ self._locked = False self._filename = filename self._mode = mode self._fallback_mode = fallback_mode self._fh = None def is_locked(self): """Was the file locked.""" return self._locked def file_handle(self): """The file handle to the file. Valid only after opened.""" return self._fh def filename(self): """The filename that is being locked.""" return self._filename def open_and_lock(self, timeout, delay): """Open the file and lock it. Args: timeout: float, How long to try to lock for. delay: float, How long to wait between retries. """ pass def unlock_and_close(self): """Unlock and close the file.""" pass class _PosixOpener(_Opener): """Lock files using Posix advisory lock files.""" def open_and_lock(self, timeout, delay): """Open the file and lock it. Tries to create a .lock file next to the file we're trying to open. Args: timeout: float, How long to try to lock for. delay: float, How long to wait between retries. Raises: AlreadyLockedException: if the lock is already acquired. IOError: if the open fails. """ if self._locked: raise AlreadyLockedException('File %s is already locked' % self._filename) self._locked = False try: self._fh = open(self._filename, self._mode) except IOError, e: # If we can't access with _mode, try _fallback_mode and don't lock. if e.errno == errno.EACCES: self._fh = open(self._filename, self._fallback_mode) return lock_filename = self._posix_lockfile(self._filename) start_time = time.time() while True: try: self._lock_fd = os.open(lock_filename, os.O_CREAT|os.O_EXCL|os.O_RDWR) self._locked = True break except OSError, e: if e.errno != errno.EEXIST: raise if (time.time() - start_time) >= timeout: logger.warn('Could not acquire lock %s in %s seconds' % ( lock_filename, timeout)) # Close the file and open in fallback_mode. if self._fh: self._fh.close() self._fh = open(self._filename, self._fallback_mode) return time.sleep(delay) def unlock_and_close(self): """Unlock a file by removing the .lock file, and close the handle.""" if self._locked: lock_filename = self._posix_lockfile(self._filename) os.unlink(lock_filename) os.close(self._lock_fd) self._locked = False self._lock_fd = None if self._fh: self._fh.close() def _posix_lockfile(self, filename): """The name of the lock file to use for posix locking.""" return '%s.lock' % filename try: import fcntl class _FcntlOpener(_Opener): """Open, lock, and unlock a file using fcntl.lockf.""" def open_and_lock(self, timeout, delay): """Open the file and lock it. Args: timeout: float, How long to try to lock for. delay: float, How long to wait between retries Raises: AlreadyLockedException: if the lock is already acquired. IOError: if the open fails. """ if self._locked: raise AlreadyLockedException('File %s is already locked' % self._filename) start_time = time.time() try: self._fh = open(self._filename, self._mode) except IOError, e: # If we can't access with _mode, try _fallback_mode and don't lock. if e.errno == errno.EACCES: self._fh = open(self._filename, self._fallback_mode) return # We opened in _mode, try to lock the file. while True: try: fcntl.lockf(self._fh.fileno(), fcntl.LOCK_EX) self._locked = True return except IOError, e: # If not retrying, then just pass on the error. if timeout == 0: raise e if e.errno != errno.EACCES: raise e # We could not acquire the lock. Try again. if (time.time() - start_time) >= timeout: logger.warn('Could not lock %s in %s seconds' % ( self._filename, timeout)) if self._fh: self._fh.close() self._fh = open(self._filename, self._fallback_mode) return time.sleep(delay) def unlock_and_close(self): """Close and unlock the file using the fcntl.lockf primitive.""" if self._locked: fcntl.lockf(self._fh.fileno(), fcntl.LOCK_UN) self._locked = False if self._fh: self._fh.close() except ImportError: _FcntlOpener = None try: import pywintypes import win32con import win32file class _Win32Opener(_Opener): """Open, lock, and unlock a file using windows primitives.""" # Error #33: # 'The process cannot access the file because another process' FILE_IN_USE_ERROR = 33 # Error #158: # 'The segment is already unlocked.' FILE_ALREADY_UNLOCKED_ERROR = 158 def open_and_lock(self, timeout, delay): """Open the file and lock it. Args: timeout: float, How long to try to lock for. delay: float, How long to wait between retries Raises: AlreadyLockedException: if the lock is already acquired. IOError: if the open fails. """ if self._locked: raise AlreadyLockedException('File %s is already locked' % self._filename) start_time = time.time() try: self._fh = open(self._filename, self._mode) except IOError, e: # If we can't access with _mode, try _fallback_mode and don't lock. if e.errno == errno.EACCES: self._fh = open(self._filename, self._fallback_mode) return # We opened in _mode, try to lock the file. while True: try: hfile = win32file._get_osfhandle(self._fh.fileno()) win32file.LockFileEx( hfile, (win32con.LOCKFILE_FAIL_IMMEDIATELY| win32con.LOCKFILE_EXCLUSIVE_LOCK), 0, -0x10000, pywintypes.OVERLAPPED()) self._locked = True return except pywintypes.error, e: if timeout == 0: raise e # If the error is not that the file is already in use, raise. if e[0] != _Win32Opener.FILE_IN_USE_ERROR: raise # We could not acquire the lock. Try again. if (time.time() - start_time) >= timeout: logger.warn('Could not lock %s in %s seconds' % ( self._filename, timeout)) if self._fh: self._fh.close() self._fh = open(self._filename, self._fallback_mode) return time.sleep(delay) def unlock_and_close(self): """Close and unlock the file using the win32 primitive.""" if self._locked: try: hfile = win32file._get_osfhandle(self._fh.fileno()) win32file.UnlockFileEx(hfile, 0, -0x10000, pywintypes.OVERLAPPED()) except pywintypes.error, e: if e[0] != _Win32Opener.FILE_ALREADY_UNLOCKED_ERROR: raise self._locked = False if self._fh: self._fh.close() except ImportError: _Win32Opener = None class LockedFile(object): """Represent a file that has exclusive access.""" def __init__(self, filename, mode, fallback_mode, use_native_locking=True): """Construct a LockedFile. Args: filename: string, The path of the file to open. mode: string, The mode to try to open the file with. fallback_mode: string, The mode to use if locking fails. use_native_locking: bool, Whether or not fcntl/win32 locking is used. """ opener = None if not opener and use_native_locking: if _Win32Opener: opener = _Win32Opener(filename, mode, fallback_mode) if _FcntlOpener: opener = _FcntlOpener(filename, mode, fallback_mode) if not opener: opener = _PosixOpener(filename, mode, fallback_mode) self._opener = opener def filename(self): """Return the filename we were constructed with.""" return self._opener._filename def file_handle(self): """Return the file_handle to the opened file.""" return self._opener.file_handle() def is_locked(self): """Return whether we successfully locked the file.""" return self._opener.is_locked() def open_and_lock(self, timeout=0, delay=0.05): """Open the file, trying to lock it. Args: timeout: float, The number of seconds to try to acquire the lock. delay: float, The number of seconds to wait between retry attempts. Raises: AlreadyLockedException: if the lock is already acquired. IOError: if the open fails. """ self._opener.open_and_lock(timeout, delay) def unlock_and_close(self): """Unlock and close a file.""" self._opener.unlock_and_close()
Python
# Copyright 2011 Google Inc. All Rights Reserved. """Multi-credential file store with lock support. This module implements a JSON credential store where multiple credentials can be stored in one file. That file supports locking both in a single process and across processes. The credential themselves are keyed off of: * client_id * user_agent * scope The format of the stored data is like so: { 'file_version': 1, 'data': [ { 'key': { 'clientId': '<client id>', 'userAgent': '<user agent>', 'scope': '<scope>' }, 'credential': { # JSON serialized Credentials. } } ] } """ __author__ = 'jbeda@google.com (Joe Beda)' import base64 import errno import logging import os import threading from anyjson import simplejson from client import Storage as BaseStorage from client import Credentials from locked_file import LockedFile logger = logging.getLogger(__name__) # A dict from 'filename'->_MultiStore instances _multistores = {} _multistores_lock = threading.Lock() class Error(Exception): """Base error for this module.""" pass class NewerCredentialStoreError(Error): """The credential store is a newer version that supported.""" pass def get_credential_storage(filename, client_id, user_agent, scope, warn_on_readonly=True): """Get a Storage instance for a credential. Args: filename: The JSON file storing a set of credentials client_id: The client_id for the credential user_agent: The user agent for the credential scope: string or list of strings, Scope(s) being requested warn_on_readonly: if True, log a warning if the store is readonly Returns: An object derived from client.Storage for getting/setting the credential. """ filename = os.path.realpath(os.path.expanduser(filename)) _multistores_lock.acquire() try: multistore = _multistores.setdefault( filename, _MultiStore(filename, warn_on_readonly)) finally: _multistores_lock.release() if type(scope) is list: scope = ' '.join(scope) return multistore._get_storage(client_id, user_agent, scope) class _MultiStore(object): """A file backed store for multiple credentials.""" def __init__(self, filename, warn_on_readonly=True): """Initialize the class. This will create the file if necessary. """ self._file = LockedFile(filename, 'r+b', 'rb') self._thread_lock = threading.Lock() self._read_only = False self._warn_on_readonly = warn_on_readonly self._create_file_if_needed() # Cache of deserialized store. This is only valid after the # _MultiStore is locked or _refresh_data_cache is called. This is # of the form of: # # (client_id, user_agent, scope) -> OAuth2Credential # # If this is None, then the store hasn't been read yet. self._data = None class _Storage(BaseStorage): """A Storage object that knows how to read/write a single credential.""" def __init__(self, multistore, client_id, user_agent, scope): self._multistore = multistore self._client_id = client_id self._user_agent = user_agent self._scope = scope def acquire_lock(self): """Acquires any lock necessary to access this Storage. This lock is not reentrant. """ self._multistore._lock() def release_lock(self): """Release the Storage lock. Trying to release a lock that isn't held will result in a RuntimeError. """ self._multistore._unlock() def locked_get(self): """Retrieve credential. The Storage lock must be held when this is called. Returns: oauth2client.client.Credentials """ credential = self._multistore._get_credential( self._client_id, self._user_agent, self._scope) if credential: credential.set_store(self) return credential def locked_put(self, credentials): """Write a credential. The Storage lock must be held when this is called. Args: credentials: Credentials, the credentials to store. """ self._multistore._update_credential(credentials, self._scope) def locked_delete(self): """Delete a credential. The Storage lock must be held when this is called. Args: credentials: Credentials, the credentials to store. """ self._multistore._delete_credential(self._client_id, self._user_agent, self._scope) def _create_file_if_needed(self): """Create an empty file if necessary. This method will not initialize the file. Instead it implements a simple version of "touch" to ensure the file has been created. """ if not os.path.exists(self._file.filename()): old_umask = os.umask(0177) try: open(self._file.filename(), 'a+b').close() finally: os.umask(old_umask) def _lock(self): """Lock the entire multistore.""" self._thread_lock.acquire() self._file.open_and_lock() if not self._file.is_locked(): self._read_only = True if self._warn_on_readonly: logger.warn('The credentials file (%s) is not writable. Opening in ' 'read-only mode. Any refreshed credentials will only be ' 'valid for this run.' % self._file.filename()) if os.path.getsize(self._file.filename()) == 0: logger.debug('Initializing empty multistore file') # The multistore is empty so write out an empty file. self._data = {} self._write() elif not self._read_only or self._data is None: # Only refresh the data if we are read/write or we haven't # cached the data yet. If we are readonly, we assume is isn't # changing out from under us and that we only have to read it # once. This prevents us from whacking any new access keys that # we have cached in memory but were unable to write out. self._refresh_data_cache() def _unlock(self): """Release the lock on the multistore.""" self._file.unlock_and_close() self._thread_lock.release() def _locked_json_read(self): """Get the raw content of the multistore file. The multistore must be locked when this is called. Returns: The contents of the multistore decoded as JSON. """ assert self._thread_lock.locked() self._file.file_handle().seek(0) return simplejson.load(self._file.file_handle()) def _locked_json_write(self, data): """Write a JSON serializable data structure to the multistore. The multistore must be locked when this is called. Args: data: The data to be serialized and written. """ assert self._thread_lock.locked() if self._read_only: return self._file.file_handle().seek(0) simplejson.dump(data, self._file.file_handle(), sort_keys=True, indent=2) self._file.file_handle().truncate() def _refresh_data_cache(self): """Refresh the contents of the multistore. The multistore must be locked when this is called. Raises: NewerCredentialStoreError: Raised when a newer client has written the store. """ self._data = {} try: raw_data = self._locked_json_read() except Exception: logger.warn('Credential data store could not be loaded. ' 'Will ignore and overwrite.') return version = 0 try: version = raw_data['file_version'] except Exception: logger.warn('Missing version for credential data store. It may be ' 'corrupt or an old version. Overwriting.') if version > 1: raise NewerCredentialStoreError( 'Credential file has file_version of %d. ' 'Only file_version of 1 is supported.' % version) credentials = [] try: credentials = raw_data['data'] except (TypeError, KeyError): pass for cred_entry in credentials: try: (key, credential) = self._decode_credential_from_json(cred_entry) self._data[key] = credential except: # If something goes wrong loading a credential, just ignore it logger.info('Error decoding credential, skipping', exc_info=True) def _decode_credential_from_json(self, cred_entry): """Load a credential from our JSON serialization. Args: cred_entry: A dict entry from the data member of our format Returns: (key, cred) where the key is the key tuple and the cred is the OAuth2Credential object. """ raw_key = cred_entry['key'] client_id = raw_key['clientId'] user_agent = raw_key['userAgent'] scope = raw_key['scope'] key = (client_id, user_agent, scope) credential = None credential = Credentials.new_from_json(simplejson.dumps(cred_entry['credential'])) return (key, credential) def _write(self): """Write the cached data back out. The multistore must be locked. """ raw_data = {'file_version': 1} raw_creds = [] raw_data['data'] = raw_creds for (cred_key, cred) in self._data.items(): raw_key = { 'clientId': cred_key[0], 'userAgent': cred_key[1], 'scope': cred_key[2] } raw_cred = simplejson.loads(cred.to_json()) raw_creds.append({'key': raw_key, 'credential': raw_cred}) self._locked_json_write(raw_data) def _get_credential(self, client_id, user_agent, scope): """Get a credential from the multistore. The multistore must be locked. Args: client_id: The client_id for the credential user_agent: The user agent for the credential scope: A string for the scope(s) being requested Returns: The credential specified or None if not present """ key = (client_id, user_agent, scope) return self._data.get(key, None) def _update_credential(self, cred, scope): """Update a credential and write the multistore. This must be called when the multistore is locked. Args: cred: The OAuth2Credential to update/set scope: The scope(s) that this credential covers """ key = (cred.client_id, cred.user_agent, scope) self._data[key] = cred self._write() def _delete_credential(self, client_id, user_agent, scope): """Delete a credential and write the multistore. This must be called when the multistore is locked. Args: client_id: The client_id for the credential user_agent: The user agent for the credential scope: The scope(s) that this credential covers """ key = (client_id, user_agent, scope) try: del self._data[key] except KeyError: pass self._write() def _get_storage(self, client_id, user_agent, scope): """Get a Storage object to get/set a credential. This Storage is a 'view' into the multistore. Args: client_id: The client_id for the credential user_agent: The user agent for the credential scope: A string for the scope(s) being requested Returns: A Storage object that can be used to get/set this cred """ return self._Storage(self, client_id, user_agent, scope)
Python
# Copyright (C) 2010 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Utility module to import a JSON module Hides all the messy details of exactly where we get a simplejson module from. """ __author__ = 'jcgregorio@google.com (Joe Gregorio)' try: # pragma: no cover # Should work for Python2.6 and higher. import json as simplejson except ImportError: # pragma: no cover try: import simplejson except ImportError: # Try to import from django, should work on App Engine from django.utils import simplejson
Python
# Copyright (C) 2010 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Command-line tools for authenticating via OAuth 2.0 Do the OAuth 2.0 Web Server dance for a command line application. Stores the generated credentials in a common file that is used by other example apps in the same directory. """ __author__ = 'jcgregorio@google.com (Joe Gregorio)' __all__ = ['run'] import BaseHTTPServer import gflags import socket import sys import webbrowser from client import FlowExchangeError from client import OOB_CALLBACK_URN try: from urlparse import parse_qsl except ImportError: from cgi import parse_qsl FLAGS = gflags.FLAGS gflags.DEFINE_boolean('auth_local_webserver', True, ('Run a local web server to handle redirects during ' 'OAuth authorization.')) gflags.DEFINE_string('auth_host_name', 'localhost', ('Host name to use when running a local web server to ' 'handle redirects during OAuth authorization.')) gflags.DEFINE_multi_int('auth_host_port', [8080, 8090], ('Port to use when running a local web server to ' 'handle redirects during OAuth authorization.')) class ClientRedirectServer(BaseHTTPServer.HTTPServer): """A server to handle OAuth 2.0 redirects back to localhost. Waits for a single request and parses the query parameters into query_params and then stops serving. """ query_params = {} class ClientRedirectHandler(BaseHTTPServer.BaseHTTPRequestHandler): """A handler for OAuth 2.0 redirects back to localhost. Waits for a single request and parses the query parameters into the servers query_params and then stops serving. """ def do_GET(s): """Handle a GET request. Parses the query parameters and prints a message if the flow has completed. Note that we can't detect if an error occurred. """ s.send_response(200) s.send_header("Content-type", "text/html") s.end_headers() query = s.path.split('?', 1)[-1] query = dict(parse_qsl(query)) s.server.query_params = query s.wfile.write("<html><head><title>Authentication Status</title></head>") s.wfile.write("<body><p>The authentication flow has completed.</p>") s.wfile.write("</body></html>") def log_message(self, format, *args): """Do not log messages to stdout while running as command line program.""" pass def run(flow, storage, http=None): """Core code for a command-line application. Args: flow: Flow, an OAuth 2.0 Flow to step through. storage: Storage, a Storage to store the credential in. http: An instance of httplib2.Http.request or something that acts like it. Returns: Credentials, the obtained credential. """ if FLAGS.auth_local_webserver: success = False port_number = 0 for port in FLAGS.auth_host_port: port_number = port try: httpd = ClientRedirectServer((FLAGS.auth_host_name, port), ClientRedirectHandler) except socket.error, e: pass else: success = True break FLAGS.auth_local_webserver = success if not success: print 'Failed to start a local webserver listening on either port 8080' print 'or port 9090. Please check your firewall settings and locally' print 'running programs that may be blocking or using those ports.' print print 'Falling back to --noauth_local_webserver and continuing with', print 'authorization.' print if FLAGS.auth_local_webserver: oauth_callback = 'http://%s:%s/' % (FLAGS.auth_host_name, port_number) else: oauth_callback = OOB_CALLBACK_URN authorize_url = flow.step1_get_authorize_url(oauth_callback) if FLAGS.auth_local_webserver: webbrowser.open(authorize_url, new=1, autoraise=True) print 'Your browser has been opened to visit:' print print ' ' + authorize_url print print 'If your browser is on a different machine then exit and re-run this' print 'application with the command-line parameter ' print print ' --noauth_local_webserver' print else: print 'Go to the following link in your browser:' print print ' ' + authorize_url print code = None if FLAGS.auth_local_webserver: httpd.handle_request() if 'error' in httpd.query_params: sys.exit('Authentication request was rejected.') if 'code' in httpd.query_params: code = httpd.query_params['code'] else: print 'Failed to find "code" in the query parameters of the redirect.' sys.exit('Try running with --noauth_local_webserver.') else: code = raw_input('Enter verification code: ').strip() try: credential = flow.step2_exchange(code, http) except FlowExchangeError, e: sys.exit('Authentication has failed: %s' % e) storage.put(credential) credential.set_store(storage) print 'Authentication successful.' return credential
Python
# Copyright (C) 2010 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """An OAuth 2.0 client. Tools for interacting with OAuth 2.0 protected resources. """ __author__ = 'jcgregorio@google.com (Joe Gregorio)' import base64 import clientsecrets import copy import datetime import httplib2 import logging import os import sys import time import urllib import urlparse from anyjson import simplejson HAS_OPENSSL = False try: from oauth2client.crypt import Signer from oauth2client.crypt import make_signed_jwt from oauth2client.crypt import verify_signed_jwt_with_certs HAS_OPENSSL = True except ImportError: pass try: from urlparse import parse_qsl except ImportError: from cgi import parse_qsl logger = logging.getLogger(__name__) # Expiry is stored in RFC3339 UTC format EXPIRY_FORMAT = '%Y-%m-%dT%H:%M:%SZ' # Which certs to use to validate id_tokens received. ID_TOKEN_VERIFICATON_CERTS = 'https://www.googleapis.com/oauth2/v1/certs' # Constant to use for the out of band OAuth 2.0 flow. OOB_CALLBACK_URN = 'urn:ietf:wg:oauth:2.0:oob' class Error(Exception): """Base error for this module.""" pass class FlowExchangeError(Error): """Error trying to exchange an authorization grant for an access token.""" pass class AccessTokenRefreshError(Error): """Error trying to refresh an expired access token.""" pass class UnknownClientSecretsFlowError(Error): """The client secrets file called for an unknown type of OAuth 2.0 flow. """ pass class AccessTokenCredentialsError(Error): """Having only the access_token means no refresh is possible.""" pass class VerifyJwtTokenError(Error): """Could on retrieve certificates for validation.""" pass def _abstract(): raise NotImplementedError('You need to override this function') class MemoryCache(object): """httplib2 Cache implementation which only caches locally.""" def __init__(self): self.cache = {} def get(self, key): return self.cache.get(key) def set(self, key, value): self.cache[key] = value def delete(self, key): self.cache.pop(key, None) class Credentials(object): """Base class for all Credentials objects. Subclasses must define an authorize() method that applies the credentials to an HTTP transport. Subclasses must also specify a classmethod named 'from_json' that takes a JSON string as input and returns an instaniated Credentials object. """ NON_SERIALIZED_MEMBERS = ['store'] def authorize(self, http): """Take an httplib2.Http instance (or equivalent) and authorizes it for the set of credentials, usually by replacing http.request() with a method that adds in the appropriate headers and then delegates to the original Http.request() method. """ _abstract() def refresh(self, http): """Forces a refresh of the access_token. Args: http: httplib2.Http, an http object to be used to make the refresh request. """ _abstract() def apply(self, headers): """Add the authorization to the headers. Args: headers: dict, the headers to add the Authorization header to. """ _abstract() def _to_json(self, strip): """Utility function for creating a JSON representation of an instance of Credentials. Args: strip: array, An array of names of members to not include in the JSON. Returns: string, a JSON representation of this instance, suitable to pass to from_json(). """ t = type(self) d = copy.copy(self.__dict__) for member in strip: if member in d: del d[member] if 'token_expiry' in d and isinstance(d['token_expiry'], datetime.datetime): d['token_expiry'] = d['token_expiry'].strftime(EXPIRY_FORMAT) # Add in information we will need later to reconsistitue this instance. d['_class'] = t.__name__ d['_module'] = t.__module__ return simplejson.dumps(d) def to_json(self): """Creating a JSON representation of an instance of Credentials. Returns: string, a JSON representation of this instance, suitable to pass to from_json(). """ return self._to_json(Credentials.NON_SERIALIZED_MEMBERS) @classmethod def new_from_json(cls, s): """Utility class method to instantiate a Credentials subclass from a JSON representation produced by to_json(). Args: s: string, JSON from to_json(). Returns: An instance of the subclass of Credentials that was serialized with to_json(). """ data = simplejson.loads(s) # Find and call the right classmethod from_json() to restore the object. module = data['_module'] try: m = __import__(module) except ImportError: # In case there's an object from the old package structure, update it module = module.replace('.apiclient', '') m = __import__(module) m = __import__(module, fromlist=module.split('.')[:-1]) kls = getattr(m, data['_class']) from_json = getattr(kls, 'from_json') return from_json(s) @classmethod def from_json(cls, s): """Instantiate a Credentials object from a JSON description of it. The JSON should have been produced by calling .to_json() on the object. Args: data: dict, A deserialized JSON object. Returns: An instance of a Credentials subclass. """ return Credentials() class Flow(object): """Base class for all Flow objects.""" pass class Storage(object): """Base class for all Storage objects. Store and retrieve a single credential. This class supports locking such that multiple processes and threads can operate on a single store. """ def acquire_lock(self): """Acquires any lock necessary to access this Storage. This lock is not reentrant. """ pass def release_lock(self): """Release the Storage lock. Trying to release a lock that isn't held will result in a RuntimeError. """ pass def locked_get(self): """Retrieve credential. The Storage lock must be held when this is called. Returns: oauth2client.client.Credentials """ _abstract() def locked_put(self, credentials): """Write a credential. The Storage lock must be held when this is called. Args: credentials: Credentials, the credentials to store. """ _abstract() def locked_delete(self): """Delete a credential. The Storage lock must be held when this is called. """ _abstract() def get(self): """Retrieve credential. The Storage lock must *not* be held when this is called. Returns: oauth2client.client.Credentials """ self.acquire_lock() try: return self.locked_get() finally: self.release_lock() def put(self, credentials): """Write a credential. The Storage lock must be held when this is called. Args: credentials: Credentials, the credentials to store. """ self.acquire_lock() try: self.locked_put(credentials) finally: self.release_lock() def delete(self): """Delete credential. Frees any resources associated with storing the credential. The Storage lock must *not* be held when this is called. Returns: None """ self.acquire_lock() try: return self.locked_delete() finally: self.release_lock() class OAuth2Credentials(Credentials): """Credentials object for OAuth 2.0. Credentials can be applied to an httplib2.Http object using the authorize() method, which then adds the OAuth 2.0 access token to each request. OAuth2Credentials objects may be safely pickled and unpickled. """ def __init__(self, access_token, client_id, client_secret, refresh_token, token_expiry, token_uri, user_agent, id_token=None): """Create an instance of OAuth2Credentials. This constructor is not usually called by the user, instead OAuth2Credentials objects are instantiated by the OAuth2WebServerFlow. Args: access_token: string, access token. client_id: string, client identifier. client_secret: string, client secret. refresh_token: string, refresh token. token_expiry: datetime, when the access_token expires. token_uri: string, URI of token endpoint. user_agent: string, The HTTP User-Agent to provide for this application. id_token: object, The identity of the resource owner. Notes: store: callable, A callable that when passed a Credential will store the credential back to where it came from. This is needed to store the latest access_token if it has expired and been refreshed. """ self.access_token = access_token self.client_id = client_id self.client_secret = client_secret self.refresh_token = refresh_token self.store = None self.token_expiry = token_expiry self.token_uri = token_uri self.user_agent = user_agent self.id_token = id_token # True if the credentials have been revoked or expired and can't be # refreshed. self.invalid = False def authorize(self, http): """Authorize an httplib2.Http instance with these credentials. The modified http.request method will add authentication headers to each request and will refresh access_tokens when a 401 is received on a request. In addition the http.request method has a credentials property, http.request.credentials, which is the Credentials object that authorized it. Args: http: An instance of httplib2.Http or something that acts like it. Returns: A modified instance of http that was passed in. Example: h = httplib2.Http() h = credentials.authorize(h) You can't create a new OAuth subclass of httplib2.Authenication because it never gets passed the absolute URI, which is needed for signing. So instead we have to overload 'request' with a closure that adds in the Authorization header and then calls the original version of 'request()'. """ request_orig = http.request # The closure that will replace 'httplib2.Http.request'. def new_request(uri, method='GET', body=None, headers=None, redirections=httplib2.DEFAULT_MAX_REDIRECTS, connection_type=None): if not self.access_token: logger.info('Attempting refresh to obtain initial access_token') self._refresh(request_orig) # Modify the request headers to add the appropriate # Authorization header. if headers is None: headers = {} self.apply(headers) if self.user_agent is not None: if 'user-agent' in headers: headers['user-agent'] = self.user_agent + ' ' + headers['user-agent'] else: headers['user-agent'] = self.user_agent resp, content = request_orig(uri, method, body, headers, redirections, connection_type) if resp.status == 401: logger.info('Refreshing due to a 401') self._refresh(request_orig) self.apply(headers) return request_orig(uri, method, body, headers, redirections, connection_type) else: return (resp, content) # Replace the request method with our own closure. http.request = new_request # Set credentials as a property of the request method. setattr(http.request, 'credentials', self) return http def refresh(self, http): """Forces a refresh of the access_token. Args: http: httplib2.Http, an http object to be used to make the refresh request. """ self._refresh(http.request) def apply(self, headers): """Add the authorization to the headers. Args: headers: dict, the headers to add the Authorization header to. """ headers['Authorization'] = 'Bearer ' + self.access_token def to_json(self): return self._to_json(Credentials.NON_SERIALIZED_MEMBERS) @classmethod def from_json(cls, s): """Instantiate a Credentials object from a JSON description of it. The JSON should have been produced by calling .to_json() on the object. Args: data: dict, A deserialized JSON object. Returns: An instance of a Credentials subclass. """ data = simplejson.loads(s) if 'token_expiry' in data and not isinstance(data['token_expiry'], datetime.datetime): try: data['token_expiry'] = datetime.datetime.strptime( data['token_expiry'], EXPIRY_FORMAT) except: data['token_expiry'] = None retval = OAuth2Credentials( data['access_token'], data['client_id'], data['client_secret'], data['refresh_token'], data['token_expiry'], data['token_uri'], data['user_agent'], data.get('id_token', None)) retval.invalid = data['invalid'] return retval @property def access_token_expired(self): """True if the credential is expired or invalid. If the token_expiry isn't set, we assume the token doesn't expire. """ if self.invalid: return True if not self.token_expiry: return False now = datetime.datetime.utcnow() if now >= self.token_expiry: logger.info('access_token is expired. Now: %s, token_expiry: %s', now, self.token_expiry) return True return False def set_store(self, store): """Set the Storage for the credential. Args: store: Storage, an implementation of Stroage object. This is needed to store the latest access_token if it has expired and been refreshed. This implementation uses locking to check for updates before updating the access_token. """ self.store = store def _updateFromCredential(self, other): """Update this Credential from another instance.""" self.__dict__.update(other.__getstate__()) def __getstate__(self): """Trim the state down to something that can be pickled.""" d = copy.copy(self.__dict__) del d['store'] return d def __setstate__(self, state): """Reconstitute the state of the object from being pickled.""" self.__dict__.update(state) self.store = None def _generate_refresh_request_body(self): """Generate the body that will be used in the refresh request.""" body = urllib.urlencode({ 'grant_type': 'refresh_token', 'client_id': self.client_id, 'client_secret': self.client_secret, 'refresh_token': self.refresh_token, }) return body def _generate_refresh_request_headers(self): """Generate the headers that will be used in the refresh request.""" headers = { 'content-type': 'application/x-www-form-urlencoded', } if self.user_agent is not None: headers['user-agent'] = self.user_agent return headers def _refresh(self, http_request): """Refreshes the access_token. This method first checks by reading the Storage object if available. If a refresh is still needed, it holds the Storage lock until the refresh is completed. Args: http_request: callable, a callable that matches the method signature of httplib2.Http.request, used to make the refresh request. Raises: AccessTokenRefreshError: When the refresh fails. """ if not self.store: self._do_refresh_request(http_request) else: self.store.acquire_lock() try: new_cred = self.store.locked_get() if (new_cred and not new_cred.invalid and new_cred.access_token != self.access_token): logger.info('Updated access_token read from Storage') self._updateFromCredential(new_cred) else: self._do_refresh_request(http_request) finally: self.store.release_lock() def _do_refresh_request(self, http_request): """Refresh the access_token using the refresh_token. Args: http_request: callable, a callable that matches the method signature of httplib2.Http.request, used to make the refresh request. Raises: AccessTokenRefreshError: When the refresh fails. """ body = self._generate_refresh_request_body() headers = self._generate_refresh_request_headers() logger.info('Refreshing access_token') resp, content = http_request( self.token_uri, method='POST', body=body, headers=headers) if resp.status == 200: # TODO(jcgregorio) Raise an error if loads fails? d = simplejson.loads(content) self.access_token = d['access_token'] self.refresh_token = d.get('refresh_token', self.refresh_token) if 'expires_in' in d: self.token_expiry = datetime.timedelta( seconds=int(d['expires_in'])) + datetime.datetime.utcnow() else: self.token_expiry = None if self.store: self.store.locked_put(self) else: # An {'error':...} response body means the token is expired or revoked, # so we flag the credentials as such. logger.info('Failed to retrieve access token: %s' % content) error_msg = 'Invalid response %s.' % resp['status'] try: d = simplejson.loads(content) if 'error' in d: error_msg = d['error'] self.invalid = True if self.store: self.store.locked_put(self) except: pass raise AccessTokenRefreshError(error_msg) class AccessTokenCredentials(OAuth2Credentials): """Credentials object for OAuth 2.0. Credentials can be applied to an httplib2.Http object using the authorize() method, which then signs each request from that object with the OAuth 2.0 access token. This set of credentials is for the use case where you have acquired an OAuth 2.0 access_token from another place such as a JavaScript client or another web application, and wish to use it from Python. Because only the access_token is present it can not be refreshed and will in time expire. AccessTokenCredentials objects may be safely pickled and unpickled. Usage: credentials = AccessTokenCredentials('<an access token>', 'my-user-agent/1.0') http = httplib2.Http() http = credentials.authorize(http) Exceptions: AccessTokenCredentialsExpired: raised when the access_token expires or is revoked. """ def __init__(self, access_token, user_agent): """Create an instance of OAuth2Credentials This is one of the few types if Credentials that you should contrust, Credentials objects are usually instantiated by a Flow. Args: access_token: string, access token. user_agent: string, The HTTP User-Agent to provide for this application. Notes: store: callable, a callable that when passed a Credential will store the credential back to where it came from. """ super(AccessTokenCredentials, self).__init__( access_token, None, None, None, None, None, user_agent) @classmethod def from_json(cls, s): data = simplejson.loads(s) retval = AccessTokenCredentials( data['access_token'], data['user_agent']) return retval def _refresh(self, http_request): raise AccessTokenCredentialsError( "The access_token is expired or invalid and can't be refreshed.") class AssertionCredentials(OAuth2Credentials): """Abstract Credentials object used for OAuth 2.0 assertion grants. This credential does not require a flow to instantiate because it represents a two legged flow, and therefore has all of the required information to generate and refresh its own access tokens. It must be subclassed to generate the appropriate assertion string. AssertionCredentials objects may be safely pickled and unpickled. """ def __init__(self, assertion_type, user_agent, token_uri='https://accounts.google.com/o/oauth2/token', **unused_kwargs): """Constructor for AssertionFlowCredentials. Args: assertion_type: string, assertion type that will be declared to the auth server user_agent: string, The HTTP User-Agent to provide for this application. token_uri: string, URI for token endpoint. For convenience defaults to Google's endpoints but any OAuth 2.0 provider can be used. """ super(AssertionCredentials, self).__init__( None, None, None, None, None, token_uri, user_agent) self.assertion_type = assertion_type def _generate_refresh_request_body(self): assertion = self._generate_assertion() body = urllib.urlencode({ 'assertion_type': self.assertion_type, 'assertion': assertion, 'grant_type': 'assertion', }) return body def _generate_assertion(self): """Generate the assertion string that will be used in the access token request. """ _abstract() if HAS_OPENSSL: # PyOpenSSL is not a prerequisite for oauth2client, so if it is missing then # don't create the SignedJwtAssertionCredentials or the verify_id_token() # method. class SignedJwtAssertionCredentials(AssertionCredentials): """Credentials object used for OAuth 2.0 Signed JWT assertion grants. This credential does not require a flow to instantiate because it represents a two legged flow, and therefore has all of the required information to generate and refresh its own access tokens. """ MAX_TOKEN_LIFETIME_SECS = 3600 # 1 hour in seconds def __init__(self, service_account_name, private_key, scope, private_key_password='notasecret', user_agent=None, token_uri='https://accounts.google.com/o/oauth2/token', **kwargs): """Constructor for SignedJwtAssertionCredentials. Args: service_account_name: string, id for account, usually an email address. private_key: string, private key in P12 format. scope: string or list of strings, scope(s) of the credentials being requested. private_key_password: string, password for private_key. user_agent: string, HTTP User-Agent to provide for this application. token_uri: string, URI for token endpoint. For convenience defaults to Google's endpoints but any OAuth 2.0 provider can be used. kwargs: kwargs, Additional parameters to add to the JWT token, for example prn=joe@xample.org.""" super(SignedJwtAssertionCredentials, self).__init__( 'http://oauth.net/grant_type/jwt/1.0/bearer', user_agent, token_uri=token_uri, ) if type(scope) is list: scope = ' '.join(scope) self.scope = scope self.private_key = private_key self.private_key_password = private_key_password self.service_account_name = service_account_name self.kwargs = kwargs @classmethod def from_json(cls, s): data = simplejson.loads(s) retval = SignedJwtAssertionCredentials( data['service_account_name'], data['private_key'], data['private_key_password'], data['scope'], data['user_agent'], data['token_uri'], data['kwargs'] ) retval.invalid = data['invalid'] return retval def _generate_assertion(self): """Generate the assertion that will be used in the request.""" now = long(time.time()) payload = { 'aud': self.token_uri, 'scope': self.scope, 'iat': now, 'exp': now + SignedJwtAssertionCredentials.MAX_TOKEN_LIFETIME_SECS, 'iss': self.service_account_name } payload.update(self.kwargs) logger.debug(str(payload)) return make_signed_jwt( Signer.from_string(self.private_key, self.private_key_password), payload) # Only used in verify_id_token(), which is always calling to the same URI # for the certs. _cached_http = httplib2.Http(MemoryCache()) def verify_id_token(id_token, audience, http=None, cert_uri=ID_TOKEN_VERIFICATON_CERTS): """Verifies a signed JWT id_token. Args: id_token: string, A Signed JWT. audience: string, The audience 'aud' that the token should be for. http: httplib2.Http, instance to use to make the HTTP request. Callers should supply an instance that has caching enabled. cert_uri: string, URI of the certificates in JSON format to verify the JWT against. Returns: The deserialized JSON in the JWT. Raises: oauth2client.crypt.AppIdentityError if the JWT fails to verify. """ if http is None: http = _cached_http resp, content = http.request(cert_uri) if resp.status == 200: certs = simplejson.loads(content) return verify_signed_jwt_with_certs(id_token, certs, audience) else: raise VerifyJwtTokenError('Status code: %d' % resp.status) def _urlsafe_b64decode(b64string): # Guard against unicode strings, which base64 can't handle. b64string = b64string.encode('ascii') padded = b64string + '=' * (4 - len(b64string) % 4) return base64.urlsafe_b64decode(padded) def _extract_id_token(id_token): """Extract the JSON payload from a JWT. Does the extraction w/o checking the signature. Args: id_token: string, OAuth 2.0 id_token. Returns: object, The deserialized JSON payload. """ segments = id_token.split('.') if (len(segments) != 3): raise VerifyJwtTokenError( 'Wrong number of segments in token: %s' % id_token) return simplejson.loads(_urlsafe_b64decode(segments[1])) def credentials_from_code(client_id, client_secret, scope, code, redirect_uri = 'postmessage', http=None, user_agent=None, token_uri='https://accounts.google.com/o/oauth2/token'): """Exchanges an authorization code for an OAuth2Credentials object. Args: client_id: string, client identifier. client_secret: string, client secret. scope: string or list of strings, scope(s) to request. code: string, An authroization code, most likely passed down from the client redirect_uri: string, this is generally set to 'postmessage' to match the redirect_uri that the client specified http: httplib2.Http, optional http instance to use to do the fetch token_uri: string, URI for token endpoint. For convenience defaults to Google's endpoints but any OAuth 2.0 provider can be used. Returns: An OAuth2Credentials object. Raises: FlowExchangeError if the authorization code cannot be exchanged for an access token """ flow = OAuth2WebServerFlow(client_id, client_secret, scope, user_agent, 'https://accounts.google.com/o/oauth2/auth', token_uri) # We primarily make this call to set up the redirect_uri in the flow object uriThatWeDontReallyUse = flow.step1_get_authorize_url(redirect_uri) credentials = flow.step2_exchange(code, http) return credentials def credentials_from_clientsecrets_and_code(filename, scope, code, message = None, redirect_uri = 'postmessage', http=None): """Returns OAuth2Credentials from a clientsecrets file and an auth code. Will create the right kind of Flow based on the contents of the clientsecrets file or will raise InvalidClientSecretsError for unknown types of Flows. Args: filename: string, File name of clientsecrets. scope: string or list of strings, scope(s) to request. code: string, An authroization code, most likely passed down from the client message: string, A friendly string to display to the user if the clientsecrets file is missing or invalid. If message is provided then sys.exit will be called in the case of an error. If message in not provided then clientsecrets.InvalidClientSecretsError will be raised. redirect_uri: string, this is generally set to 'postmessage' to match the redirect_uri that the client specified http: httplib2.Http, optional http instance to use to do the fetch Returns: An OAuth2Credentials object. Raises: FlowExchangeError if the authorization code cannot be exchanged for an access token UnknownClientSecretsFlowError if the file describes an unknown kind of Flow. clientsecrets.InvalidClientSecretsError if the clientsecrets file is invalid. """ flow = flow_from_clientsecrets(filename, scope, message) # We primarily make this call to set up the redirect_uri in the flow object uriThatWeDontReallyUse = flow.step1_get_authorize_url(redirect_uri) credentials = flow.step2_exchange(code, http) return credentials class OAuth2WebServerFlow(Flow): """Does the Web Server Flow for OAuth 2.0. OAuth2Credentials objects may be safely pickled and unpickled. """ def __init__(self, client_id, client_secret, scope, user_agent=None, auth_uri='https://accounts.google.com/o/oauth2/auth', token_uri='https://accounts.google.com/o/oauth2/token', **kwargs): """Constructor for OAuth2WebServerFlow. Args: client_id: string, client identifier. client_secret: string client secret. scope: string or list of strings, scope(s) of the credentials being requested. user_agent: string, HTTP User-Agent to provide for this application. auth_uri: string, URI for authorization endpoint. For convenience defaults to Google's endpoints but any OAuth 2.0 provider can be used. token_uri: string, URI for token endpoint. For convenience defaults to Google's endpoints but any OAuth 2.0 provider can be used. **kwargs: dict, The keyword arguments are all optional and required parameters for the OAuth calls. """ self.client_id = client_id self.client_secret = client_secret if type(scope) is list: scope = ' '.join(scope) self.scope = scope self.user_agent = user_agent self.auth_uri = auth_uri self.token_uri = token_uri self.params = { 'access_type': 'offline', } self.params.update(kwargs) self.redirect_uri = None def step1_get_authorize_url(self, redirect_uri=OOB_CALLBACK_URN): """Returns a URI to redirect to the provider. Args: redirect_uri: string, Either the string 'urn:ietf:wg:oauth:2.0:oob' for a non-web-based application, or a URI that handles the callback from the authorization server. If redirect_uri is 'urn:ietf:wg:oauth:2.0:oob' then pass in the generated verification code to step2_exchange, otherwise pass in the query parameters received at the callback uri to step2_exchange. """ self.redirect_uri = redirect_uri query = { 'response_type': 'code', 'client_id': self.client_id, 'redirect_uri': redirect_uri, 'scope': self.scope, } query.update(self.params) parts = list(urlparse.urlparse(self.auth_uri)) query.update(dict(parse_qsl(parts[4]))) # 4 is the index of the query part parts[4] = urllib.urlencode(query) return urlparse.urlunparse(parts) def step2_exchange(self, code, http=None): """Exhanges a code for OAuth2Credentials. Args: code: string or dict, either the code as a string, or a dictionary of the query parameters to the redirect_uri, which contains the code. http: httplib2.Http, optional http instance to use to do the fetch Returns: An OAuth2Credentials object that can be used to authorize requests. Raises: FlowExchangeError if a problem occured exchanging the code for a refresh_token. """ if not (isinstance(code, str) or isinstance(code, unicode)): if 'code' not in code: if 'error' in code: error_msg = code['error'] else: error_msg = 'No code was supplied in the query parameters.' raise FlowExchangeError(error_msg) else: code = code['code'] body = urllib.urlencode({ 'grant_type': 'authorization_code', 'client_id': self.client_id, 'client_secret': self.client_secret, 'code': code, 'redirect_uri': self.redirect_uri, 'scope': self.scope, }) headers = { 'content-type': 'application/x-www-form-urlencoded', } if self.user_agent is not None: headers['user-agent'] = self.user_agent if http is None: http = httplib2.Http() resp, content = http.request(self.token_uri, method='POST', body=body, headers=headers) if resp.status == 200: # TODO(jcgregorio) Raise an error if simplejson.loads fails? d = simplejson.loads(content) access_token = d['access_token'] refresh_token = d.get('refresh_token', None) token_expiry = None if 'expires_in' in d: token_expiry = datetime.datetime.utcnow() + datetime.timedelta( seconds=int(d['expires_in'])) if 'id_token' in d: d['id_token'] = _extract_id_token(d['id_token']) logger.info('Successfully retrieved access token: %s' % content) return OAuth2Credentials(access_token, self.client_id, self.client_secret, refresh_token, token_expiry, self.token_uri, self.user_agent, id_token=d.get('id_token', None)) else: logger.info('Failed to retrieve access token: %s' % content) error_msg = 'Invalid response %s.' % resp['status'] try: d = simplejson.loads(content) if 'error' in d: error_msg = d['error'] except: pass raise FlowExchangeError(error_msg) def flow_from_clientsecrets(filename, scope, message=None): """Create a Flow from a clientsecrets file. Will create the right kind of Flow based on the contents of the clientsecrets file or will raise InvalidClientSecretsError for unknown types of Flows. Args: filename: string, File name of client secrets. scope: string or list of strings, scope(s) to request. message: string, A friendly string to display to the user if the clientsecrets file is missing or invalid. If message is provided then sys.exit will be called in the case of an error. If message in not provided then clientsecrets.InvalidClientSecretsError will be raised. Returns: A Flow object. Raises: UnknownClientSecretsFlowError if the file describes an unknown kind of Flow. clientsecrets.InvalidClientSecretsError if the clientsecrets file is invalid. """ try: client_type, client_info = clientsecrets.loadfile(filename) if client_type in [clientsecrets.TYPE_WEB, clientsecrets.TYPE_INSTALLED]: return OAuth2WebServerFlow( client_info['client_id'], client_info['client_secret'], scope, None, # user_agent client_info['auth_uri'], client_info['token_uri']) except clientsecrets.InvalidClientSecretsError: if message: sys.exit(message) else: raise else: raise UnknownClientSecretsFlowError( 'This OAuth 2.0 flow is unsupported: "%s"' * client_type)
Python
# Copyright (C) 2011 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Utilities for reading OAuth 2.0 client secret files. A client_secrets.json file contains all the information needed to interact with an OAuth 2.0 protected service. """ __author__ = 'jcgregorio@google.com (Joe Gregorio)' from anyjson import simplejson # Properties that make a client_secrets.json file valid. TYPE_WEB = 'web' TYPE_INSTALLED = 'installed' VALID_CLIENT = { TYPE_WEB: { 'required': [ 'client_id', 'client_secret', 'redirect_uris', 'auth_uri', 'token_uri'], 'string': [ 'client_id', 'client_secret' ] }, TYPE_INSTALLED: { 'required': [ 'client_id', 'client_secret', 'redirect_uris', 'auth_uri', 'token_uri'], 'string': [ 'client_id', 'client_secret' ] } } class Error(Exception): """Base error for this module.""" pass class InvalidClientSecretsError(Error): """Format of ClientSecrets file is invalid.""" pass def _validate_clientsecrets(obj): if obj is None or len(obj) != 1: raise InvalidClientSecretsError('Invalid file format.') client_type = obj.keys()[0] if client_type not in VALID_CLIENT.keys(): raise InvalidClientSecretsError('Unknown client type: %s.' % client_type) client_info = obj[client_type] for prop_name in VALID_CLIENT[client_type]['required']: if prop_name not in client_info: raise InvalidClientSecretsError( 'Missing property "%s" in a client type of "%s".' % (prop_name, client_type)) for prop_name in VALID_CLIENT[client_type]['string']: if client_info[prop_name].startswith('[['): raise InvalidClientSecretsError( 'Property "%s" is not configured.' % prop_name) return client_type, client_info def load(fp): obj = simplejson.load(fp) return _validate_clientsecrets(obj) def loads(s): obj = simplejson.loads(s) return _validate_clientsecrets(obj) def loadfile(filename): try: fp = file(filename, 'r') try: obj = simplejson.load(fp) finally: fp.close() except IOError: raise InvalidClientSecretsError('File not found: "%s"' % filename) return _validate_clientsecrets(obj)
Python
# Copyright (C) 2010 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Utilities for OAuth. Utilities for making it easier to work with OAuth 2.0 credentials. """ __author__ = 'jcgregorio@google.com (Joe Gregorio)' import os import stat import threading from anyjson import simplejson from client import Storage as BaseStorage from client import Credentials class Storage(BaseStorage): """Store and retrieve a single credential to and from a file.""" def __init__(self, filename): self._filename = filename self._lock = threading.Lock() def acquire_lock(self): """Acquires any lock necessary to access this Storage. This lock is not reentrant.""" self._lock.acquire() def release_lock(self): """Release the Storage lock. Trying to release a lock that isn't held will result in a RuntimeError. """ self._lock.release() def locked_get(self): """Retrieve Credential from file. Returns: oauth2client.client.Credentials """ credentials = None try: f = open(self._filename, 'rb') content = f.read() f.close() except IOError: return credentials try: credentials = Credentials.new_from_json(content) credentials.set_store(self) except ValueError: pass return credentials def _create_file_if_needed(self): """Create an empty file if necessary. This method will not initialize the file. Instead it implements a simple version of "touch" to ensure the file has been created. """ if not os.path.exists(self._filename): old_umask = os.umask(0177) try: open(self._filename, 'a+b').close() finally: os.umask(old_umask) def locked_put(self, credentials): """Write Credentials to file. Args: credentials: Credentials, the credentials to store. """ self._create_file_if_needed() f = open(self._filename, 'wb') f.write(credentials.to_json()) f.close() def locked_delete(self): """Delete Credentials file. Args: credentials: Credentials, the credentials to store. """ os.unlink(self._filename)
Python
__version__ = "1.0c2"
Python
# Copyright (C) 2010 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """OAuth 2.0 utilities for Django. Utilities for using OAuth 2.0 in conjunction with the Django datastore. """ __author__ = 'jcgregorio@google.com (Joe Gregorio)' import oauth2client import base64 import pickle from django.db import models from oauth2client.client import Storage as BaseStorage class CredentialsField(models.Field): __metaclass__ = models.SubfieldBase def get_internal_type(self): return "TextField" def to_python(self, value): if value is None: return None if isinstance(value, oauth2client.client.Credentials): return value return pickle.loads(base64.b64decode(value)) def get_db_prep_value(self, value, connection, prepared=False): if value is None: return None return base64.b64encode(pickle.dumps(value)) class FlowField(models.Field): __metaclass__ = models.SubfieldBase def get_internal_type(self): return "TextField" def to_python(self, value): if value is None: return None if isinstance(value, oauth2client.client.Flow): return value return pickle.loads(base64.b64decode(value)) def get_db_prep_value(self, value, connection, prepared=False): if value is None: return None return base64.b64encode(pickle.dumps(value)) class Storage(BaseStorage): """Store and retrieve a single credential to and from the datastore. This Storage helper presumes the Credentials have been stored as a CredenialsField on a db model class. """ def __init__(self, model_class, key_name, key_value, property_name): """Constructor for Storage. Args: model: db.Model, model class key_name: string, key name for the entity that has the credentials key_value: string, key value for the entity that has the credentials property_name: string, name of the property that is an CredentialsProperty """ self.model_class = model_class self.key_name = key_name self.key_value = key_value self.property_name = property_name def locked_get(self): """Retrieve Credential from datastore. Returns: oauth2client.Credentials """ credential = None query = {self.key_name: self.key_value} entities = self.model_class.objects.filter(**query) if len(entities) > 0: credential = getattr(entities[0], self.property_name) if credential and hasattr(credential, 'set_store'): credential.set_store(self) return credential def locked_put(self, credentials): """Write a Credentials to the datastore. Args: credentials: Credentials, the credentials to store. """ args = {self.key_name: self.key_value} entity = self.model_class(**args) setattr(entity, self.property_name, credentials) entity.save() def locked_delete(self): """Delete Credentials from the datastore.""" query = {self.key_name: self.key_value} entities = self.model_class.objects.filter(**query).delete()
Python
# Copyright (C) 2012 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Classes to encapsulate a single HTTP request. The classes implement a command pattern, with every object supporting an execute() method that does the actuall HTTP request. """ __author__ = 'jcgregorio@google.com (Joe Gregorio)' import StringIO import base64 import copy import gzip import httplib2 import mimeparse import mimetypes import os import urllib import urlparse import uuid from email.generator import Generator from email.mime.multipart import MIMEMultipart from email.mime.nonmultipart import MIMENonMultipart from email.parser import FeedParser from errors import BatchError from errors import HttpError from errors import ResumableUploadError from errors import UnexpectedBodyError from errors import UnexpectedMethodError from model import JsonModel from oauth2client.anyjson import simplejson DEFAULT_CHUNK_SIZE = 512*1024 class MediaUploadProgress(object): """Status of a resumable upload.""" def __init__(self, resumable_progress, total_size): """Constructor. Args: resumable_progress: int, bytes sent so far. total_size: int, total bytes in complete upload, or None if the total upload size isn't known ahead of time. """ self.resumable_progress = resumable_progress self.total_size = total_size def progress(self): """Percent of upload completed, as a float. Returns: the percentage complete as a float, returning 0.0 if the total size of the upload is unknown. """ if self.total_size is not None: return float(self.resumable_progress) / float(self.total_size) else: return 0.0 class MediaDownloadProgress(object): """Status of a resumable download.""" def __init__(self, resumable_progress, total_size): """Constructor. Args: resumable_progress: int, bytes received so far. total_size: int, total bytes in complete download. """ self.resumable_progress = resumable_progress self.total_size = total_size def progress(self): """Percent of download completed, as a float. Returns: the percentage complete as a float, returning 0.0 if the total size of the download is unknown. """ if self.total_size is not None: return float(self.resumable_progress) / float(self.total_size) else: return 0.0 class MediaUpload(object): """Describes a media object to upload. Base class that defines the interface of MediaUpload subclasses. Note that subclasses of MediaUpload may allow you to control the chunksize when upload a media object. It is important to keep the size of the chunk as large as possible to keep the upload efficient. Other factors may influence the size of the chunk you use, particularly if you are working in an environment where individual HTTP requests may have a hardcoded time limit, such as under certain classes of requests under Google App Engine. """ def chunksize(self): """Chunk size for resumable uploads. Returns: Chunk size in bytes. """ raise NotImplementedError() def mimetype(self): """Mime type of the body. Returns: Mime type. """ return 'application/octet-stream' def size(self): """Size of upload. Returns: Size of the body, or None of the size is unknown. """ return None def resumable(self): """Whether this upload is resumable. Returns: True if resumable upload or False. """ return False def getbytes(self, begin, end): """Get bytes from the media. Args: begin: int, offset from beginning of file. length: int, number of bytes to read, starting at begin. Returns: A string of bytes read. May be shorter than length if EOF was reached first. """ raise NotImplementedError() def _to_json(self, strip=None): """Utility function for creating a JSON representation of a MediaUpload. Args: strip: array, An array of names of members to not include in the JSON. Returns: string, a JSON representation of this instance, suitable to pass to from_json(). """ t = type(self) d = copy.copy(self.__dict__) if strip is not None: for member in strip: del d[member] d['_class'] = t.__name__ d['_module'] = t.__module__ return simplejson.dumps(d) def to_json(self): """Create a JSON representation of an instance of MediaUpload. Returns: string, a JSON representation of this instance, suitable to pass to from_json(). """ return self._to_json() @classmethod def new_from_json(cls, s): """Utility class method to instantiate a MediaUpload subclass from a JSON representation produced by to_json(). Args: s: string, JSON from to_json(). Returns: An instance of the subclass of MediaUpload that was serialized with to_json(). """ data = simplejson.loads(s) # Find and call the right classmethod from_json() to restore the object. module = data['_module'] m = __import__(module, fromlist=module.split('.')[:-1]) kls = getattr(m, data['_class']) from_json = getattr(kls, 'from_json') return from_json(s) class MediaFileUpload(MediaUpload): """A MediaUpload for a file. Construct a MediaFileUpload and pass as the media_body parameter of the method. For example, if we had a service that allowed uploading images: media = MediaFileUpload('cow.png', mimetype='image/png', chunksize=1024*1024, resumable=True) farm.animals()..insert( id='cow', name='cow.png', media_body=media).execute() """ def __init__(self, filename, mimetype=None, chunksize=DEFAULT_CHUNK_SIZE, resumable=False): """Constructor. Args: filename: string, Name of the file. mimetype: string, Mime-type of the file. If None then a mime-type will be guessed from the file extension. chunksize: int, File will be uploaded in chunks of this many bytes. Only used if resumable=True. resumable: bool, True if this is a resumable upload. False means upload in a single request. """ self._filename = filename self._size = os.path.getsize(filename) self._fd = None if mimetype is None: (mimetype, encoding) = mimetypes.guess_type(filename) self._mimetype = mimetype self._chunksize = chunksize self._resumable = resumable def chunksize(self): """Chunk size for resumable uploads. Returns: Chunk size in bytes. """ return self._chunksize def mimetype(self): """Mime type of the body. Returns: Mime type. """ return self._mimetype def size(self): """Size of upload. Returns: Size of the body, or None of the size is unknown. """ return self._size def resumable(self): """Whether this upload is resumable. Returns: True if resumable upload or False. """ return self._resumable def getbytes(self, begin, length): """Get bytes from the media. Args: begin: int, offset from beginning of file. length: int, number of bytes to read, starting at begin. Returns: A string of bytes read. May be shorted than length if EOF was reached first. """ if self._fd is None: self._fd = open(self._filename, 'rb') self._fd.seek(begin) return self._fd.read(length) def to_json(self): """Creating a JSON representation of an instance of MediaFileUpload. Returns: string, a JSON representation of this instance, suitable to pass to from_json(). """ return self._to_json(['_fd']) @staticmethod def from_json(s): d = simplejson.loads(s) return MediaFileUpload( d['_filename'], d['_mimetype'], d['_chunksize'], d['_resumable']) class MediaIoBaseUpload(MediaUpload): """A MediaUpload for a io.Base objects. Note that the Python file object is compatible with io.Base and can be used with this class also. fh = io.BytesIO('...Some data to upload...') media = MediaIoBaseUpload(fh, mimetype='image/png', chunksize=1024*1024, resumable=True) farm.animals().insert( id='cow', name='cow.png', media_body=media).execute() """ def __init__(self, fh, mimetype, chunksize=DEFAULT_CHUNK_SIZE, resumable=False): """Constructor. Args: fh: io.Base or file object, The source of the bytes to upload. MUST be opened in blocking mode, do not use streams opened in non-blocking mode. mimetype: string, Mime-type of the file. If None then a mime-type will be guessed from the file extension. chunksize: int, File will be uploaded in chunks of this many bytes. Only used if resumable=True. resumable: bool, True if this is a resumable upload. False means upload in a single request. """ self._fh = fh self._mimetype = mimetype self._chunksize = chunksize self._resumable = resumable self._size = None try: if hasattr(self._fh, 'fileno'): fileno = self._fh.fileno() # Pipes and such show up as 0 length files. size = os.fstat(fileno).st_size if size: self._size = os.fstat(fileno).st_size except IOError: pass def chunksize(self): """Chunk size for resumable uploads. Returns: Chunk size in bytes. """ return self._chunksize def mimetype(self): """Mime type of the body. Returns: Mime type. """ return self._mimetype def size(self): """Size of upload. Returns: Size of the body, or None of the size is unknown. """ return self._size def resumable(self): """Whether this upload is resumable. Returns: True if resumable upload or False. """ return self._resumable def getbytes(self, begin, length): """Get bytes from the media. Args: begin: int, offset from beginning of file. length: int, number of bytes to read, starting at begin. Returns: A string of bytes read. May be shorted than length if EOF was reached first. """ self._fh.seek(begin) return self._fh.read(length) def to_json(self): """This upload type is not serializable.""" raise NotImplementedError('MediaIoBaseUpload is not serializable.') class MediaInMemoryUpload(MediaUpload): """MediaUpload for a chunk of bytes. Construct a MediaFileUpload and pass as the media_body parameter of the method. """ def __init__(self, body, mimetype='application/octet-stream', chunksize=DEFAULT_CHUNK_SIZE, resumable=False): """Create a new MediaBytesUpload. Args: body: string, Bytes of body content. mimetype: string, Mime-type of the file or default of 'application/octet-stream'. chunksize: int, File will be uploaded in chunks of this many bytes. Only used if resumable=True. resumable: bool, True if this is a resumable upload. False means upload in a single request. """ self._body = body self._mimetype = mimetype self._resumable = resumable self._chunksize = chunksize def chunksize(self): """Chunk size for resumable uploads. Returns: Chunk size in bytes. """ return self._chunksize def mimetype(self): """Mime type of the body. Returns: Mime type. """ return self._mimetype def size(self): """Size of upload. Returns: Size of the body, or None of the size is unknown. """ return len(self._body) def resumable(self): """Whether this upload is resumable. Returns: True if resumable upload or False. """ return self._resumable def getbytes(self, begin, length): """Get bytes from the media. Args: begin: int, offset from beginning of file. length: int, number of bytes to read, starting at begin. Returns: A string of bytes read. May be shorter than length if EOF was reached first. """ return self._body[begin:begin + length] def to_json(self): """Create a JSON representation of a MediaInMemoryUpload. Returns: string, a JSON representation of this instance, suitable to pass to from_json(). """ t = type(self) d = copy.copy(self.__dict__) del d['_body'] d['_class'] = t.__name__ d['_module'] = t.__module__ d['_b64body'] = base64.b64encode(self._body) return simplejson.dumps(d) @staticmethod def from_json(s): d = simplejson.loads(s) return MediaInMemoryUpload(base64.b64decode(d['_b64body']), d['_mimetype'], d['_chunksize'], d['_resumable']) class MediaIoBaseDownload(object): """"Download media resources. Note that the Python file object is compatible with io.Base and can be used with this class also. Example: request = farms.animals().get_media(id='cow') fh = io.FileIO('cow.png', mode='wb') downloader = MediaIoBaseDownload(fh, request, chunksize=1024*1024) done = False while done is False: status, done = downloader.next_chunk() if status: print "Download %d%%." % int(status.progress() * 100) print "Download Complete!" """ def __init__(self, fh, request, chunksize=DEFAULT_CHUNK_SIZE): """Constructor. Args: fh: io.Base or file object, The stream in which to write the downloaded bytes. request: apiclient.http.HttpRequest, the media request to perform in chunks. chunksize: int, File will be downloaded in chunks of this many bytes. """ self.fh_ = fh self.request_ = request self.uri_ = request.uri self.chunksize_ = chunksize self.progress_ = 0 self.total_size_ = None self.done_ = False def next_chunk(self): """Get the next chunk of the download. Returns: (status, done): (MediaDownloadStatus, boolean) The value of 'done' will be True when the media has been fully downloaded. Raises: apiclient.errors.HttpError if the response was not a 2xx. httplib2.Error if a transport error has occured. """ headers = { 'range': 'bytes=%d-%d' % ( self.progress_, self.progress_ + self.chunksize_) } http = self.request_.http http.follow_redirects = False resp, content = http.request(self.uri_, headers=headers) if resp.status in [301, 302, 303, 307, 308] and 'location' in resp: self.uri_ = resp['location'] resp, content = http.request(self.uri_, headers=headers) if resp.status in [200, 206]: self.progress_ += len(content) self.fh_.write(content) if 'content-range' in resp: content_range = resp['content-range'] length = content_range.rsplit('/', 1)[1] self.total_size_ = int(length) if self.progress_ == self.total_size_: self.done_ = True return MediaDownloadProgress(self.progress_, self.total_size_), self.done_ else: raise HttpError(resp, content, self.uri_) class HttpRequest(object): """Encapsulates a single HTTP request.""" def __init__(self, http, postproc, uri, method='GET', body=None, headers=None, methodId=None, resumable=None): """Constructor for an HttpRequest. Args: http: httplib2.Http, the transport object to use to make a request postproc: callable, called on the HTTP response and content to transform it into a data object before returning, or raising an exception on an error. uri: string, the absolute URI to send the request to method: string, the HTTP method to use body: string, the request body of the HTTP request, headers: dict, the HTTP request headers methodId: string, a unique identifier for the API method being called. resumable: MediaUpload, None if this is not a resumbale request. """ self.uri = uri self.method = method self.body = body self.headers = headers or {} self.methodId = methodId self.http = http self.postproc = postproc self.resumable = resumable self._in_error_state = False # Pull the multipart boundary out of the content-type header. major, minor, params = mimeparse.parse_mime_type( headers.get('content-type', 'application/json')) # The size of the non-media part of the request. self.body_size = len(self.body or '') # The resumable URI to send chunks to. self.resumable_uri = None # The bytes that have been uploaded. self.resumable_progress = 0 def execute(self, http=None): """Execute the request. Args: http: httplib2.Http, an http object to be used in place of the one the HttpRequest request object was constructed with. Returns: A deserialized object model of the response body as determined by the postproc. Raises: apiclient.errors.HttpError if the response was not a 2xx. httplib2.Error if a transport error has occured. """ if http is None: http = self.http if self.resumable: body = None while body is None: _, body = self.next_chunk(http) return body else: if 'content-length' not in self.headers: self.headers['content-length'] = str(self.body_size) resp, content = http.request(self.uri, self.method, body=self.body, headers=self.headers) if resp.status >= 300: raise HttpError(resp, content, self.uri) return self.postproc(resp, content) def next_chunk(self, http=None): """Execute the next step of a resumable upload. Can only be used if the method being executed supports media uploads and the MediaUpload object passed in was flagged as using resumable upload. Example: media = MediaFileUpload('cow.png', mimetype='image/png', chunksize=1000, resumable=True) request = farm.animals().insert( id='cow', name='cow.png', media_body=media) response = None while response is None: status, response = request.next_chunk() if status: print "Upload %d%% complete." % int(status.progress() * 100) Returns: (status, body): (ResumableMediaStatus, object) The body will be None until the resumable media is fully uploaded. Raises: apiclient.errors.HttpError if the response was not a 2xx. httplib2.Error if a transport error has occured. """ if http is None: http = self.http if self.resumable.size() is None: size = '*' else: size = str(self.resumable.size()) if self.resumable_uri is None: start_headers = copy.copy(self.headers) start_headers['X-Upload-Content-Type'] = self.resumable.mimetype() if size != '*': start_headers['X-Upload-Content-Length'] = size start_headers['content-length'] = str(self.body_size) resp, content = http.request(self.uri, self.method, body=self.body, headers=start_headers) if resp.status == 200 and 'location' in resp: self.resumable_uri = resp['location'] else: raise ResumableUploadError("Failed to retrieve starting URI.") elif self._in_error_state: # If we are in an error state then query the server for current state of # the upload by sending an empty PUT and reading the 'range' header in # the response. headers = { 'Content-Range': 'bytes */%s' % size, 'content-length': '0' } resp, content = http.request(self.resumable_uri, 'PUT', headers=headers) status, body = self._process_response(resp, content) if body: # The upload was complete. return (status, body) data = self.resumable.getbytes( self.resumable_progress, self.resumable.chunksize()) # A short read implies that we are at EOF, so finish the upload. if len(data) < self.resumable.chunksize(): size = str(self.resumable_progress + len(data)) headers = { 'Content-Range': 'bytes %d-%d/%s' % ( self.resumable_progress, self.resumable_progress + len(data) - 1, size) } try: resp, content = http.request(self.resumable_uri, 'PUT', body=data, headers=headers) except: self._in_error_state = True raise return self._process_response(resp, content) def _process_response(self, resp, content): """Process the response from a single chunk upload. Args: resp: httplib2.Response, the response object. content: string, the content of the response. Returns: (status, body): (ResumableMediaStatus, object) The body will be None until the resumable media is fully uploaded. Raises: apiclient.errors.HttpError if the response was not a 2xx or a 308. """ if resp.status in [200, 201]: self._in_error_state = False return None, self.postproc(resp, content) elif resp.status == 308: self._in_error_state = False # A "308 Resume Incomplete" indicates we are not done. self.resumable_progress = int(resp['range'].split('-')[1]) + 1 if 'location' in resp: self.resumable_uri = resp['location'] else: self._in_error_state = True raise HttpError(resp, content, self.uri) return (MediaUploadProgress(self.resumable_progress, self.resumable.size()), None) def to_json(self): """Returns a JSON representation of the HttpRequest.""" d = copy.copy(self.__dict__) if d['resumable'] is not None: d['resumable'] = self.resumable.to_json() del d['http'] del d['postproc'] return simplejson.dumps(d) @staticmethod def from_json(s, http, postproc): """Returns an HttpRequest populated with info from a JSON object.""" d = simplejson.loads(s) if d['resumable'] is not None: d['resumable'] = MediaUpload.new_from_json(d['resumable']) return HttpRequest( http, postproc, uri=d['uri'], method=d['method'], body=d['body'], headers=d['headers'], methodId=d['methodId'], resumable=d['resumable']) class BatchHttpRequest(object): """Batches multiple HttpRequest objects into a single HTTP request. Example: from apiclient.http import BatchHttpRequest def list_animals(request_id, response): \"\"\"Do something with the animals list response.\"\"\" pass def list_farmers(request_id, response): \"\"\"Do something with the farmers list response.\"\"\" pass service = build('farm', 'v2') batch = BatchHttpRequest() batch.add(service.animals().list(), list_animals) batch.add(service.farmers().list(), list_farmers) batch.execute(http) """ def __init__(self, callback=None, batch_uri=None): """Constructor for a BatchHttpRequest. Args: callback: callable, A callback to be called for each response, of the form callback(id, response). The first parameter is the request id, and the second is the deserialized response object. batch_uri: string, URI to send batch requests to. """ if batch_uri is None: batch_uri = 'https://www.googleapis.com/batch' self._batch_uri = batch_uri # Global callback to be called for each individual response in the batch. self._callback = callback # A map from id to request. self._requests = {} # A map from id to callback. self._callbacks = {} # List of request ids, in the order in which they were added. self._order = [] # The last auto generated id. self._last_auto_id = 0 # Unique ID on which to base the Content-ID headers. self._base_id = None # A map from request id to (headers, content) response pairs self._responses = {} # A map of id(Credentials) that have been refreshed. self._refreshed_credentials = {} def _refresh_and_apply_credentials(self, request, http): """Refresh the credentials and apply to the request. Args: request: HttpRequest, the request. http: httplib2.Http, the global http object for the batch. """ # For the credentials to refresh, but only once per refresh_token # If there is no http per the request then refresh the http passed in # via execute() creds = None if request.http is not None and hasattr(request.http.request, 'credentials'): creds = request.http.request.credentials elif http is not None and hasattr(http.request, 'credentials'): creds = http.request.credentials if creds is not None: if id(creds) not in self._refreshed_credentials: creds.refresh(http) self._refreshed_credentials[id(creds)] = 1 # Only apply the credentials if we are using the http object passed in, # otherwise apply() will get called during _serialize_request(). if request.http is None or not hasattr(request.http.request, 'credentials'): creds.apply(request.headers) def _id_to_header(self, id_): """Convert an id to a Content-ID header value. Args: id_: string, identifier of individual request. Returns: A Content-ID header with the id_ encoded into it. A UUID is prepended to the value because Content-ID headers are supposed to be universally unique. """ if self._base_id is None: self._base_id = uuid.uuid4() return '<%s+%s>' % (self._base_id, urllib.quote(id_)) def _header_to_id(self, header): """Convert a Content-ID header value to an id. Presumes the Content-ID header conforms to the format that _id_to_header() returns. Args: header: string, Content-ID header value. Returns: The extracted id value. Raises: BatchError if the header is not in the expected format. """ if header[0] != '<' or header[-1] != '>': raise BatchError("Invalid value for Content-ID: %s" % header) if '+' not in header: raise BatchError("Invalid value for Content-ID: %s" % header) base, id_ = header[1:-1].rsplit('+', 1) return urllib.unquote(id_) def _serialize_request(self, request): """Convert an HttpRequest object into a string. Args: request: HttpRequest, the request to serialize. Returns: The request as a string in application/http format. """ # Construct status line parsed = urlparse.urlparse(request.uri) request_line = urlparse.urlunparse( (None, None, parsed.path, parsed.params, parsed.query, None) ) status_line = request.method + ' ' + request_line + ' HTTP/1.1\n' major, minor = request.headers.get('content-type', 'application/json').split('/') msg = MIMENonMultipart(major, minor) headers = request.headers.copy() if request.http is not None and hasattr(request.http.request, 'credentials'): request.http.request.credentials.apply(headers) # MIMENonMultipart adds its own Content-Type header. if 'content-type' in headers: del headers['content-type'] for key, value in headers.iteritems(): msg[key] = value msg['Host'] = parsed.netloc msg.set_unixfrom(None) if request.body is not None: msg.set_payload(request.body) msg['content-length'] = str(len(request.body)) # Serialize the mime message. fp = StringIO.StringIO() # maxheaderlen=0 means don't line wrap headers. g = Generator(fp, maxheaderlen=0) g.flatten(msg, unixfrom=False) body = fp.getvalue() # Strip off the \n\n that the MIME lib tacks onto the end of the payload. if request.body is None: body = body[:-2] return status_line.encode('utf-8') + body def _deserialize_response(self, payload): """Convert string into httplib2 response and content. Args: payload: string, headers and body as a string. Returns: A pair (resp, content) like would be returned from httplib2.request. """ # Strip off the status line status_line, payload = payload.split('\n', 1) protocol, status, reason = status_line.split(' ', 2) # Parse the rest of the response parser = FeedParser() parser.feed(payload) msg = parser.close() msg['status'] = status # Create httplib2.Response from the parsed headers. resp = httplib2.Response(msg) resp.reason = reason resp.version = int(protocol.split('/', 1)[1].replace('.', '')) content = payload.split('\r\n\r\n', 1)[1] return resp, content def _new_id(self): """Create a new id. Auto incrementing number that avoids conflicts with ids already used. Returns: string, a new unique id. """ self._last_auto_id += 1 while str(self._last_auto_id) in self._requests: self._last_auto_id += 1 return str(self._last_auto_id) def add(self, request, callback=None, request_id=None): """Add a new request. Every callback added will be paired with a unique id, the request_id. That unique id will be passed back to the callback when the response comes back from the server. The default behavior is to have the library generate it's own unique id. If the caller passes in a request_id then they must ensure uniqueness for each request_id, and if they are not an exception is raised. Callers should either supply all request_ids or nevery supply a request id, to avoid such an error. Args: request: HttpRequest, Request to add to the batch. callback: callable, A callback to be called for this response, of the form callback(id, response). The first parameter is the request id, and the second is the deserialized response object. request_id: string, A unique id for the request. The id will be passed to the callback with the response. Returns: None Raises: BatchError if a media request is added to a batch. KeyError is the request_id is not unique. """ if request_id is None: request_id = self._new_id() if request.resumable is not None: raise BatchError("Media requests cannot be used in a batch request.") if request_id in self._requests: raise KeyError("A request with this ID already exists: %s" % request_id) self._requests[request_id] = request self._callbacks[request_id] = callback self._order.append(request_id) def _execute(self, http, order, requests): """Serialize batch request, send to server, process response. Args: http: httplib2.Http, an http object to be used to make the request with. order: list, list of request ids in the order they were added to the batch. request: list, list of request objects to send. Raises: httplib2.Error if a transport error has occured. apiclient.errors.BatchError if the response is the wrong format. """ message = MIMEMultipart('mixed') # Message should not write out it's own headers. setattr(message, '_write_headers', lambda self: None) # Add all the individual requests. for request_id in order: request = requests[request_id] msg = MIMENonMultipart('application', 'http') msg['Content-Transfer-Encoding'] = 'binary' msg['Content-ID'] = self._id_to_header(request_id) body = self._serialize_request(request) msg.set_payload(body) message.attach(msg) body = message.as_string() headers = {} headers['content-type'] = ('multipart/mixed; ' 'boundary="%s"') % message.get_boundary() resp, content = http.request(self._batch_uri, 'POST', body=body, headers=headers) if resp.status >= 300: raise HttpError(resp, content, self._batch_uri) # Now break out the individual responses and store each one. boundary, _ = content.split(None, 1) # Prepend with a content-type header so FeedParser can handle it. header = 'content-type: %s\r\n\r\n' % resp['content-type'] for_parser = header + content parser = FeedParser() parser.feed(for_parser) mime_response = parser.close() if not mime_response.is_multipart(): raise BatchError("Response not in multipart/mixed format.", resp, content) for part in mime_response.get_payload(): request_id = self._header_to_id(part['Content-ID']) headers, content = self._deserialize_response(part.get_payload()) self._responses[request_id] = (headers, content) def execute(self, http=None): """Execute all the requests as a single batched HTTP request. Args: http: httplib2.Http, an http object to be used in place of the one the HttpRequest request object was constructed with. If one isn't supplied then use a http object from the requests in this batch. Returns: None Raises: httplib2.Error if a transport error has occured. apiclient.errors.BatchError if the response is the wrong format. """ # If http is not supplied use the first valid one given in the requests. if http is None: for request_id in self._order: request = self._requests[request_id] if request is not None: http = request.http break if http is None: raise ValueError("Missing a valid http object.") self._execute(http, self._order, self._requests) # Loop over all the requests and check for 401s. For each 401 request the # credentials should be refreshed and then sent again in a separate batch. redo_requests = {} redo_order = [] for request_id in self._order: headers, content = self._responses[request_id] if headers['status'] == '401': redo_order.append(request_id) request = self._requests[request_id] self._refresh_and_apply_credentials(request, http) redo_requests[request_id] = request if redo_requests: self._execute(http, redo_order, redo_requests) # Now process all callbacks that are erroring, and raise an exception for # ones that return a non-2xx response? Or add extra parameter to callback # that contains an HttpError? for request_id in self._order: headers, content = self._responses[request_id] request = self._requests[request_id] callback = self._callbacks[request_id] response = None exception = None try: r = httplib2.Response(headers) response = request.postproc(r, content) except HttpError, e: exception = e if callback is not None: callback(request_id, response, exception) if self._callback is not None: self._callback(request_id, response, exception) class HttpRequestMock(object): """Mock of HttpRequest. Do not construct directly, instead use RequestMockBuilder. """ def __init__(self, resp, content, postproc): """Constructor for HttpRequestMock Args: resp: httplib2.Response, the response to emulate coming from the request content: string, the response body postproc: callable, the post processing function usually supplied by the model class. See model.JsonModel.response() as an example. """ self.resp = resp self.content = content self.postproc = postproc if resp is None: self.resp = httplib2.Response({'status': 200, 'reason': 'OK'}) if 'reason' in self.resp: self.resp.reason = self.resp['reason'] def execute(self, http=None): """Execute the request. Same behavior as HttpRequest.execute(), but the response is mocked and not really from an HTTP request/response. """ return self.postproc(self.resp, self.content) class RequestMockBuilder(object): """A simple mock of HttpRequest Pass in a dictionary to the constructor that maps request methodIds to tuples of (httplib2.Response, content, opt_expected_body) that should be returned when that method is called. None may also be passed in for the httplib2.Response, in which case a 200 OK response will be generated. If an opt_expected_body (str or dict) is provided, it will be compared to the body and UnexpectedBodyError will be raised on inequality. Example: response = '{"data": {"id": "tag:google.c...' requestBuilder = RequestMockBuilder( { 'plus.activities.get': (None, response), } ) apiclient.discovery.build("plus", "v1", requestBuilder=requestBuilder) Methods that you do not supply a response for will return a 200 OK with an empty string as the response content or raise an excpetion if check_unexpected is set to True. The methodId is taken from the rpcName in the discovery document. For more details see the project wiki. """ def __init__(self, responses, check_unexpected=False): """Constructor for RequestMockBuilder The constructed object should be a callable object that can replace the class HttpResponse. responses - A dictionary that maps methodIds into tuples of (httplib2.Response, content). The methodId comes from the 'rpcName' field in the discovery document. check_unexpected - A boolean setting whether or not UnexpectedMethodError should be raised on unsupplied method. """ self.responses = responses self.check_unexpected = check_unexpected def __call__(self, http, postproc, uri, method='GET', body=None, headers=None, methodId=None, resumable=None): """Implements the callable interface that discovery.build() expects of requestBuilder, which is to build an object compatible with HttpRequest.execute(). See that method for the description of the parameters and the expected response. """ if methodId in self.responses: response = self.responses[methodId] resp, content = response[:2] if len(response) > 2: # Test the body against the supplied expected_body. expected_body = response[2] if bool(expected_body) != bool(body): # Not expecting a body and provided one # or expecting a body and not provided one. raise UnexpectedBodyError(expected_body, body) if isinstance(expected_body, str): expected_body = simplejson.loads(expected_body) body = simplejson.loads(body) if body != expected_body: raise UnexpectedBodyError(expected_body, body) return HttpRequestMock(resp, content, postproc) elif self.check_unexpected: raise UnexpectedMethodError(methodId) else: model = JsonModel(False) return HttpRequestMock(None, '{}', model.response) class HttpMock(object): """Mock of httplib2.Http""" def __init__(self, filename, headers=None): """ Args: filename: string, absolute filename to read response from headers: dict, header to return with response """ if headers is None: headers = {'status': '200 OK'} f = file(filename, 'r') self.data = f.read() f.close() self.headers = headers def request(self, uri, method='GET', body=None, headers=None, redirections=1, connection_type=None): return httplib2.Response(self.headers), self.data class HttpMockSequence(object): """Mock of httplib2.Http Mocks a sequence of calls to request returning different responses for each call. Create an instance initialized with the desired response headers and content and then use as if an httplib2.Http instance. http = HttpMockSequence([ ({'status': '401'}, ''), ({'status': '200'}, '{"access_token":"1/3w","expires_in":3600}'), ({'status': '200'}, 'echo_request_headers'), ]) resp, content = http.request("http://examples.com") There are special values you can pass in for content to trigger behavours that are helpful in testing. 'echo_request_headers' means return the request headers in the response body 'echo_request_headers_as_json' means return the request headers in the response body 'echo_request_body' means return the request body in the response body 'echo_request_uri' means return the request uri in the response body """ def __init__(self, iterable): """ Args: iterable: iterable, a sequence of pairs of (headers, body) """ self._iterable = iterable self.follow_redirects = True def request(self, uri, method='GET', body=None, headers=None, redirections=1, connection_type=None): resp, content = self._iterable.pop(0) if content == 'echo_request_headers': content = headers elif content == 'echo_request_headers_as_json': content = simplejson.dumps(headers) elif content == 'echo_request_body': content = body elif content == 'echo_request_uri': content = uri return httplib2.Response(resp), content def set_user_agent(http, user_agent): """Set the user-agent on every request. Args: http - An instance of httplib2.Http or something that acts like it. user_agent: string, the value for the user-agent header. Returns: A modified instance of http that was passed in. Example: h = httplib2.Http() h = set_user_agent(h, "my-app-name/6.0") Most of the time the user-agent will be set doing auth, this is for the rare cases where you are accessing an unauthenticated endpoint. """ request_orig = http.request # The closure that will replace 'httplib2.Http.request'. def new_request(uri, method='GET', body=None, headers=None, redirections=httplib2.DEFAULT_MAX_REDIRECTS, connection_type=None): """Modify the request headers to add the user-agent.""" if headers is None: headers = {} if 'user-agent' in headers: headers['user-agent'] = user_agent + ' ' + headers['user-agent'] else: headers['user-agent'] = user_agent resp, content = request_orig(uri, method, body, headers, redirections, connection_type) return resp, content http.request = new_request return http def tunnel_patch(http): """Tunnel PATCH requests over POST. Args: http - An instance of httplib2.Http or something that acts like it. Returns: A modified instance of http that was passed in. Example: h = httplib2.Http() h = tunnel_patch(h, "my-app-name/6.0") Useful if you are running on a platform that doesn't support PATCH. Apply this last if you are using OAuth 1.0, as changing the method will result in a different signature. """ request_orig = http.request # The closure that will replace 'httplib2.Http.request'. def new_request(uri, method='GET', body=None, headers=None, redirections=httplib2.DEFAULT_MAX_REDIRECTS, connection_type=None): """Modify the request headers to add the user-agent.""" if headers is None: headers = {} if method == 'PATCH': if 'oauth_token' in headers.get('authorization', ''): logging.warning( 'OAuth 1.0 request made with Credentials after tunnel_patch.') headers['x-http-method-override'] = "PATCH" method = 'POST' resp, content = request_orig(uri, method, body, headers, redirections, connection_type) return resp, content http.request = new_request return http
Python
# Copyright (C) 2007 Joe Gregorio # # Licensed under the MIT License """MIME-Type Parser This module provides basic functions for handling mime-types. It can handle matching mime-types against a list of media-ranges. See section 14.1 of the HTTP specification [RFC 2616] for a complete explanation. http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.1 Contents: - parse_mime_type(): Parses a mime-type into its component parts. - parse_media_range(): Media-ranges are mime-types with wild-cards and a 'q' quality parameter. - quality(): Determines the quality ('q') of a mime-type when compared against a list of media-ranges. - quality_parsed(): Just like quality() except the second parameter must be pre-parsed. - best_match(): Choose the mime-type with the highest quality ('q') from a list of candidates. """ __version__ = '0.1.3' __author__ = 'Joe Gregorio' __email__ = 'joe@bitworking.org' __license__ = 'MIT License' __credits__ = '' def parse_mime_type(mime_type): """Parses a mime-type into its component parts. Carves up a mime-type and returns a tuple of the (type, subtype, params) where 'params' is a dictionary of all the parameters for the media range. For example, the media range 'application/xhtml;q=0.5' would get parsed into: ('application', 'xhtml', {'q', '0.5'}) """ parts = mime_type.split(';') params = dict([tuple([s.strip() for s in param.split('=', 1)])\ for param in parts[1:] ]) full_type = parts[0].strip() # Java URLConnection class sends an Accept header that includes a # single '*'. Turn it into a legal wildcard. if full_type == '*': full_type = '*/*' (type, subtype) = full_type.split('/') return (type.strip(), subtype.strip(), params) def parse_media_range(range): """Parse a media-range into its component parts. Carves up a media range and returns a tuple of the (type, subtype, params) where 'params' is a dictionary of all the parameters for the media range. For example, the media range 'application/*;q=0.5' would get parsed into: ('application', '*', {'q', '0.5'}) In addition this function also guarantees that there is a value for 'q' in the params dictionary, filling it in with a proper default if necessary. """ (type, subtype, params) = parse_mime_type(range) if not params.has_key('q') or not params['q'] or \ not float(params['q']) or float(params['q']) > 1\ or float(params['q']) < 0: params['q'] = '1' return (type, subtype, params) def fitness_and_quality_parsed(mime_type, parsed_ranges): """Find the best match for a mime-type amongst parsed media-ranges. Find the best match for a given mime-type against a list of media_ranges that have already been parsed by parse_media_range(). Returns a tuple of the fitness value and the value of the 'q' quality parameter of the best match, or (-1, 0) if no match was found. Just as for quality_parsed(), 'parsed_ranges' must be a list of parsed media ranges. """ best_fitness = -1 best_fit_q = 0 (target_type, target_subtype, target_params) =\ parse_media_range(mime_type) for (type, subtype, params) in parsed_ranges: type_match = (type == target_type or\ type == '*' or\ target_type == '*') subtype_match = (subtype == target_subtype or\ subtype == '*' or\ target_subtype == '*') if type_match and subtype_match: param_matches = reduce(lambda x, y: x + y, [1 for (key, value) in \ target_params.iteritems() if key != 'q' and \ params.has_key(key) and value == params[key]], 0) fitness = (type == target_type) and 100 or 0 fitness += (subtype == target_subtype) and 10 or 0 fitness += param_matches if fitness > best_fitness: best_fitness = fitness best_fit_q = params['q'] return best_fitness, float(best_fit_q) def quality_parsed(mime_type, parsed_ranges): """Find the best match for a mime-type amongst parsed media-ranges. Find the best match for a given mime-type against a list of media_ranges that have already been parsed by parse_media_range(). Returns the 'q' quality parameter of the best match, 0 if no match was found. This function bahaves the same as quality() except that 'parsed_ranges' must be a list of parsed media ranges. """ return fitness_and_quality_parsed(mime_type, parsed_ranges)[1] def quality(mime_type, ranges): """Return the quality ('q') of a mime-type against a list of media-ranges. Returns the quality 'q' of a mime-type when compared against the media-ranges in ranges. For example: >>> quality('text/html','text/*;q=0.3, text/html;q=0.7, text/html;level=1, text/html;level=2;q=0.4, */*;q=0.5') 0.7 """ parsed_ranges = [parse_media_range(r) for r in ranges.split(',')] return quality_parsed(mime_type, parsed_ranges) def best_match(supported, header): """Return mime-type with the highest quality ('q') from list of candidates. Takes a list of supported mime-types and finds the best match for all the media-ranges listed in header. The value of header must be a string that conforms to the format of the HTTP Accept: header. The value of 'supported' is a list of mime-types. The list of supported mime-types should be sorted in order of increasing desirability, in case of a situation where there is a tie. >>> best_match(['application/xbel+xml', 'text/xml'], 'text/*;q=0.5,*/*; q=0.1') 'text/xml' """ split_header = _filter_blank(header.split(',')) parsed_header = [parse_media_range(r) for r in split_header] weighted_matches = [] pos = 0 for mime_type in supported: weighted_matches.append((fitness_and_quality_parsed(mime_type, parsed_header), pos, mime_type)) pos += 1 weighted_matches.sort() return weighted_matches[-1][0][1] and weighted_matches[-1][2] or '' def _filter_blank(i): for s in i: if s.strip(): yield s
Python
# Copyright (C) 2010 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Schema processing for discovery based APIs Schemas holds an APIs discovery schemas. It can return those schema as deserialized JSON objects, or pretty print them as prototype objects that conform to the schema. For example, given the schema: schema = \"\"\"{ "Foo": { "type": "object", "properties": { "etag": { "type": "string", "description": "ETag of the collection." }, "kind": { "type": "string", "description": "Type of the collection ('calendar#acl').", "default": "calendar#acl" }, "nextPageToken": { "type": "string", "description": "Token used to access the next page of this result. Omitted if no further results are available." } } } }\"\"\" s = Schemas(schema) print s.prettyPrintByName('Foo') Produces the following output: { "nextPageToken": "A String", # Token used to access the # next page of this result. Omitted if no further results are available. "kind": "A String", # Type of the collection ('calendar#acl'). "etag": "A String", # ETag of the collection. }, The constructor takes a discovery document in which to look up named schema. """ # TODO(jcgregorio) support format, enum, minimum, maximum __author__ = 'jcgregorio@google.com (Joe Gregorio)' import copy from oauth2client.anyjson import simplejson class Schemas(object): """Schemas for an API.""" def __init__(self, discovery): """Constructor. Args: discovery: object, Deserialized discovery document from which we pull out the named schema. """ self.schemas = discovery.get('schemas', {}) # Cache of pretty printed schemas. self.pretty = {} def _prettyPrintByName(self, name, seen=None, dent=0): """Get pretty printed object prototype from the schema name. Args: name: string, Name of schema in the discovery document. seen: list of string, Names of schema already seen. Used to handle recursive definitions. Returns: string, A string that contains a prototype object with comments that conforms to the given schema. """ if seen is None: seen = [] if name in seen: # Do not fall into an infinite loop over recursive definitions. return '# Object with schema name: %s' % name seen.append(name) if name not in self.pretty: self.pretty[name] = _SchemaToStruct(self.schemas[name], seen, dent).to_str(self._prettyPrintByName) seen.pop() return self.pretty[name] def prettyPrintByName(self, name): """Get pretty printed object prototype from the schema name. Args: name: string, Name of schema in the discovery document. Returns: string, A string that contains a prototype object with comments that conforms to the given schema. """ # Return with trailing comma and newline removed. return self._prettyPrintByName(name, seen=[], dent=1)[:-2] def _prettyPrintSchema(self, schema, seen=None, dent=0): """Get pretty printed object prototype of schema. Args: schema: object, Parsed JSON schema. seen: list of string, Names of schema already seen. Used to handle recursive definitions. Returns: string, A string that contains a prototype object with comments that conforms to the given schema. """ if seen is None: seen = [] return _SchemaToStruct(schema, seen, dent).to_str(self._prettyPrintByName) def prettyPrintSchema(self, schema): """Get pretty printed object prototype of schema. Args: schema: object, Parsed JSON schema. Returns: string, A string that contains a prototype object with comments that conforms to the given schema. """ # Return with trailing comma and newline removed. return self._prettyPrintSchema(schema, dent=1)[:-2] def get(self, name): """Get deserialized JSON schema from the schema name. Args: name: string, Schema name. """ return self.schemas[name] class _SchemaToStruct(object): """Convert schema to a prototype object.""" def __init__(self, schema, seen, dent=0): """Constructor. Args: schema: object, Parsed JSON schema. seen: list, List of names of schema already seen while parsing. Used to handle recursive definitions. dent: int, Initial indentation depth. """ # The result of this parsing kept as list of strings. self.value = [] # The final value of the parsing. self.string = None # The parsed JSON schema. self.schema = schema # Indentation level. self.dent = dent # Method that when called returns a prototype object for the schema with # the given name. self.from_cache = None # List of names of schema already seen while parsing. self.seen = seen def emit(self, text): """Add text as a line to the output. Args: text: string, Text to output. """ self.value.extend([" " * self.dent, text, '\n']) def emitBegin(self, text): """Add text to the output, but with no line terminator. Args: text: string, Text to output. """ self.value.extend([" " * self.dent, text]) def emitEnd(self, text, comment): """Add text and comment to the output with line terminator. Args: text: string, Text to output. comment: string, Python comment. """ if comment: divider = '\n' + ' ' * (self.dent + 2) + '# ' lines = comment.splitlines() lines = [x.rstrip() for x in lines] comment = divider.join(lines) self.value.extend([text, ' # ', comment, '\n']) else: self.value.extend([text, '\n']) def indent(self): """Increase indentation level.""" self.dent += 1 def undent(self): """Decrease indentation level.""" self.dent -= 1 def _to_str_impl(self, schema): """Prototype object based on the schema, in Python code with comments. Args: schema: object, Parsed JSON schema file. Returns: Prototype object based on the schema, in Python code with comments. """ stype = schema.get('type') if stype == 'object': self.emitEnd('{', schema.get('description', '')) self.indent() for pname, pschema in schema.get('properties', {}).iteritems(): self.emitBegin('"%s": ' % pname) self._to_str_impl(pschema) self.undent() self.emit('},') elif '$ref' in schema: schemaName = schema['$ref'] description = schema.get('description', '') s = self.from_cache(schemaName, self.seen) parts = s.splitlines() self.emitEnd(parts[0], description) for line in parts[1:]: self.emit(line.rstrip()) elif stype == 'boolean': value = schema.get('default', 'True or False') self.emitEnd('%s,' % str(value), schema.get('description', '')) elif stype == 'string': value = schema.get('default', 'A String') self.emitEnd('"%s",' % str(value), schema.get('description', '')) elif stype == 'integer': value = schema.get('default', '42') self.emitEnd('%s,' % str(value), schema.get('description', '')) elif stype == 'number': value = schema.get('default', '3.14') self.emitEnd('%s,' % str(value), schema.get('description', '')) elif stype == 'null': self.emitEnd('None,', schema.get('description', '')) elif stype == 'any': self.emitEnd('"",', schema.get('description', '')) elif stype == 'array': self.emitEnd('[', schema.get('description')) self.indent() self.emitBegin('') self._to_str_impl(schema['items']) self.undent() self.emit('],') else: self.emit('Unknown type! %s' % stype) self.emitEnd('', '') self.string = ''.join(self.value) return self.string def to_str(self, from_cache): """Prototype object based on the schema, in Python code with comments. Args: from_cache: callable(name, seen), Callable that retrieves an object prototype for a schema with the given name. Seen is a list of schema names already seen as we recursively descend the schema definition. Returns: Prototype object based on the schema, in Python code with comments. The lines of the code will all be properly indented. """ self.from_cache = from_cache return self._to_str_impl(self.schema)
Python
# Copyright (C) 2010 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Utility module to import a JSON module Hides all the messy details of exactly where we get a simplejson module from. """ __author__ = 'jcgregorio@google.com (Joe Gregorio)' try: # pragma: no cover import simplejson except ImportError: # pragma: no cover try: # Try to import from django, should work on App Engine from django.utils import simplejson except ImportError: # Should work for Python2.6 and higher. import json as simplejson
Python
# Copyright (C) 2010 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Utilities for OAuth. Utilities for making it easier to work with OAuth. """ __author__ = 'jcgregorio@google.com (Joe Gregorio)' import copy import httplib2 import logging import oauth2 as oauth import urllib import urlparse from anyjson import simplejson try: from urlparse import parse_qsl except ImportError: from cgi import parse_qsl class Error(Exception): """Base error for this module.""" pass class RequestError(Error): """Error occurred during request.""" pass class MissingParameter(Error): pass class CredentialsInvalidError(Error): pass def _abstract(): raise NotImplementedError('You need to override this function') def _oauth_uri(name, discovery, params): """Look up the OAuth URI from the discovery document and add query parameters based on params. name - The name of the OAuth URI to lookup, one of 'request', 'access', or 'authorize'. discovery - Portion of discovery document the describes the OAuth endpoints. params - Dictionary that is used to form the query parameters for the specified URI. """ if name not in ['request', 'access', 'authorize']: raise KeyError(name) keys = discovery[name]['parameters'].keys() query = {} for key in keys: if key in params: query[key] = params[key] return discovery[name]['url'] + '?' + urllib.urlencode(query) class Credentials(object): """Base class for all Credentials objects. Subclasses must define an authorize() method that applies the credentials to an HTTP transport. """ def authorize(self, http): """Take an httplib2.Http instance (or equivalent) and authorizes it for the set of credentials, usually by replacing http.request() with a method that adds in the appropriate headers and then delegates to the original Http.request() method. """ _abstract() class Flow(object): """Base class for all Flow objects.""" pass class Storage(object): """Base class for all Storage objects. Store and retrieve a single credential. """ def get(self): """Retrieve credential. Returns: apiclient.oauth.Credentials """ _abstract() def put(self, credentials): """Write a credential. Args: credentials: Credentials, the credentials to store. """ _abstract() class OAuthCredentials(Credentials): """Credentials object for OAuth 1.0a """ def __init__(self, consumer, token, user_agent): """ consumer - An instance of oauth.Consumer. token - An instance of oauth.Token constructed with the access token and secret. user_agent - The HTTP User-Agent to provide for this application. """ self.consumer = consumer self.token = token self.user_agent = user_agent self.store = None # True if the credentials have been revoked self._invalid = False @property def invalid(self): """True if the credentials are invalid, such as being revoked.""" return getattr(self, "_invalid", False) def set_store(self, store): """Set the storage for the credential. Args: store: callable, a callable that when passed a Credential will store the credential back to where it came from. This is needed to store the latest access_token if it has been revoked. """ self.store = store def __getstate__(self): """Trim the state down to something that can be pickled.""" d = copy.copy(self.__dict__) del d['store'] return d def __setstate__(self, state): """Reconstitute the state of the object from being pickled.""" self.__dict__.update(state) self.store = None def authorize(self, http): """Authorize an httplib2.Http instance with these Credentials Args: http - An instance of httplib2.Http or something that acts like it. Returns: A modified instance of http that was passed in. Example: h = httplib2.Http() h = credentials.authorize(h) You can't create a new OAuth subclass of httplib2.Authenication because it never gets passed the absolute URI, which is needed for signing. So instead we have to overload 'request' with a closure that adds in the Authorization header and then calls the original version of 'request()'. """ request_orig = http.request signer = oauth.SignatureMethod_HMAC_SHA1() # The closure that will replace 'httplib2.Http.request'. def new_request(uri, method='GET', body=None, headers=None, redirections=httplib2.DEFAULT_MAX_REDIRECTS, connection_type=None): """Modify the request headers to add the appropriate Authorization header.""" response_code = 302 http.follow_redirects = False while response_code in [301, 302]: req = oauth.Request.from_consumer_and_token( self.consumer, self.token, http_method=method, http_url=uri) req.sign_request(signer, self.consumer, self.token) if headers is None: headers = {} headers.update(req.to_header()) if 'user-agent' in headers: headers['user-agent'] = self.user_agent + ' ' + headers['user-agent'] else: headers['user-agent'] = self.user_agent resp, content = request_orig(uri, method, body, headers, redirections, connection_type) response_code = resp.status if response_code in [301, 302]: uri = resp['location'] # Update the stored credential if it becomes invalid. if response_code == 401: logging.info('Access token no longer valid: %s' % content) self._invalid = True if self.store is not None: self.store(self) raise CredentialsInvalidError("Credentials are no longer valid.") return resp, content http.request = new_request return http class TwoLeggedOAuthCredentials(Credentials): """Two Legged Credentials object for OAuth 1.0a. The Two Legged object is created directly, not from a flow. Once you authorize and httplib2.Http instance you can change the requestor and that change will propogate to the authorized httplib2.Http instance. For example: http = httplib2.Http() http = credentials.authorize(http) credentials.requestor = 'foo@example.info' http.request(...) credentials.requestor = 'bar@example.info' http.request(...) """ def __init__(self, consumer_key, consumer_secret, user_agent): """ Args: consumer_key: string, An OAuth 1.0 consumer key consumer_secret: string, An OAuth 1.0 consumer secret user_agent: string, The HTTP User-Agent to provide for this application. """ self.consumer = oauth.Consumer(consumer_key, consumer_secret) self.user_agent = user_agent self.store = None # email address of the user to act on the behalf of. self._requestor = None @property def invalid(self): """True if the credentials are invalid, such as being revoked. Always returns False for Two Legged Credentials. """ return False def getrequestor(self): return self._requestor def setrequestor(self, email): self._requestor = email requestor = property(getrequestor, setrequestor, None, 'The email address of the user to act on behalf of') def set_store(self, store): """Set the storage for the credential. Args: store: callable, a callable that when passed a Credential will store the credential back to where it came from. This is needed to store the latest access_token if it has been revoked. """ self.store = store def __getstate__(self): """Trim the state down to something that can be pickled.""" d = copy.copy(self.__dict__) del d['store'] return d def __setstate__(self, state): """Reconstitute the state of the object from being pickled.""" self.__dict__.update(state) self.store = None def authorize(self, http): """Authorize an httplib2.Http instance with these Credentials Args: http - An instance of httplib2.Http or something that acts like it. Returns: A modified instance of http that was passed in. Example: h = httplib2.Http() h = credentials.authorize(h) You can't create a new OAuth subclass of httplib2.Authenication because it never gets passed the absolute URI, which is needed for signing. So instead we have to overload 'request' with a closure that adds in the Authorization header and then calls the original version of 'request()'. """ request_orig = http.request signer = oauth.SignatureMethod_HMAC_SHA1() # The closure that will replace 'httplib2.Http.request'. def new_request(uri, method='GET', body=None, headers=None, redirections=httplib2.DEFAULT_MAX_REDIRECTS, connection_type=None): """Modify the request headers to add the appropriate Authorization header.""" response_code = 302 http.follow_redirects = False while response_code in [301, 302]: # add in xoauth_requestor_id=self._requestor to the uri if self._requestor is None: raise MissingParameter( 'Requestor must be set before using TwoLeggedOAuthCredentials') parsed = list(urlparse.urlparse(uri)) q = parse_qsl(parsed[4]) q.append(('xoauth_requestor_id', self._requestor)) parsed[4] = urllib.urlencode(q) uri = urlparse.urlunparse(parsed) req = oauth.Request.from_consumer_and_token( self.consumer, None, http_method=method, http_url=uri) req.sign_request(signer, self.consumer, None) if headers is None: headers = {} headers.update(req.to_header()) if 'user-agent' in headers: headers['user-agent'] = self.user_agent + ' ' + headers['user-agent'] else: headers['user-agent'] = self.user_agent resp, content = request_orig(uri, method, body, headers, redirections, connection_type) response_code = resp.status if response_code in [301, 302]: uri = resp['location'] if response_code == 401: logging.info('Access token no longer valid: %s' % content) # Do not store the invalid state of the Credentials because # being 2LO they could be reinstated in the future. raise CredentialsInvalidError("Credentials are invalid.") return resp, content http.request = new_request return http class FlowThreeLegged(Flow): """Does the Three Legged Dance for OAuth 1.0a. """ def __init__(self, discovery, consumer_key, consumer_secret, user_agent, **kwargs): """ discovery - Section of the API discovery document that describes the OAuth endpoints. consumer_key - OAuth consumer key consumer_secret - OAuth consumer secret user_agent - The HTTP User-Agent that identifies the application. **kwargs - The keyword arguments are all optional and required parameters for the OAuth calls. """ self.discovery = discovery self.consumer_key = consumer_key self.consumer_secret = consumer_secret self.user_agent = user_agent self.params = kwargs self.request_token = {} required = {} for uriinfo in discovery.itervalues(): for name, value in uriinfo['parameters'].iteritems(): if value['required'] and not name.startswith('oauth_'): required[name] = 1 for key in required.iterkeys(): if key not in self.params: raise MissingParameter('Required parameter %s not supplied' % key) def step1_get_authorize_url(self, oauth_callback='oob'): """Returns a URI to redirect to the provider. oauth_callback - Either the string 'oob' for a non-web-based application, or a URI that handles the callback from the authorization server. If oauth_callback is 'oob' then pass in the generated verification code to step2_exchange, otherwise pass in the query parameters received at the callback uri to step2_exchange. """ consumer = oauth.Consumer(self.consumer_key, self.consumer_secret) client = oauth.Client(consumer) headers = { 'user-agent': self.user_agent, 'content-type': 'application/x-www-form-urlencoded' } body = urllib.urlencode({'oauth_callback': oauth_callback}) uri = _oauth_uri('request', self.discovery, self.params) resp, content = client.request(uri, 'POST', headers=headers, body=body) if resp['status'] != '200': logging.error('Failed to retrieve temporary authorization: %s', content) raise RequestError('Invalid response %s.' % resp['status']) self.request_token = dict(parse_qsl(content)) auth_params = copy.copy(self.params) auth_params['oauth_token'] = self.request_token['oauth_token'] return _oauth_uri('authorize', self.discovery, auth_params) def step2_exchange(self, verifier): """Exhanges an authorized request token for OAuthCredentials. Args: verifier: string, dict - either the verifier token, or a dictionary of the query parameters to the callback, which contains the oauth_verifier. Returns: The Credentials object. """ if not (isinstance(verifier, str) or isinstance(verifier, unicode)): verifier = verifier['oauth_verifier'] token = oauth.Token( self.request_token['oauth_token'], self.request_token['oauth_token_secret']) token.set_verifier(verifier) consumer = oauth.Consumer(self.consumer_key, self.consumer_secret) client = oauth.Client(consumer, token) headers = { 'user-agent': self.user_agent, 'content-type': 'application/x-www-form-urlencoded' } uri = _oauth_uri('access', self.discovery, self.params) resp, content = client.request(uri, 'POST', headers=headers) if resp['status'] != '200': logging.error('Failed to retrieve access token: %s', content) raise RequestError('Invalid response %s.' % resp['status']) oauth_params = dict(parse_qsl(content)) token = oauth.Token( oauth_params['oauth_token'], oauth_params['oauth_token_secret']) return OAuthCredentials(consumer, token, self.user_agent)
Python
# Copyright (C) 2010 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Client for discovery based APIs A client library for Google's discovery based APIs. """ __author__ = 'jcgregorio@google.com (Joe Gregorio)' __all__ = [ 'build', 'build_from_document' 'fix_method_name', 'key2param' ] import copy import httplib2 import logging import os import random import re import uritemplate import urllib import urlparse import mimeparse import mimetypes try: from urlparse import parse_qsl except ImportError: from cgi import parse_qsl from apiclient.errors import HttpError from apiclient.errors import InvalidJsonError from apiclient.errors import MediaUploadSizeError from apiclient.errors import UnacceptableMimeTypeError from apiclient.errors import UnknownApiNameOrVersion from apiclient.errors import UnknownLinkType from apiclient.http import HttpRequest from apiclient.http import MediaFileUpload from apiclient.http import MediaUpload from apiclient.model import JsonModel from apiclient.model import MediaModel from apiclient.model import RawModel from apiclient.schema import Schemas from email.mime.multipart import MIMEMultipart from email.mime.nonmultipart import MIMENonMultipart from oauth2client.anyjson import simplejson logger = logging.getLogger(__name__) URITEMPLATE = re.compile('{[^}]*}') VARNAME = re.compile('[a-zA-Z0-9_-]+') DISCOVERY_URI = ('https://www.googleapis.com/discovery/v1/apis/' '{api}/{apiVersion}/rest') DEFAULT_METHOD_DOC = 'A description of how to use this function' # Parameters accepted by the stack, but not visible via discovery. STACK_QUERY_PARAMETERS = ['trace', 'pp', 'userip', 'strict'] # Python reserved words. RESERVED_WORDS = ['and', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'exec', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'not', 'or', 'pass', 'print', 'raise', 'return', 'try', 'while' ] def fix_method_name(name): """Fix method names to avoid reserved word conflicts. Args: name: string, method name. Returns: The name with a '_' prefixed if the name is a reserved word. """ if name in RESERVED_WORDS: return name + '_' else: return name def _add_query_parameter(url, name, value): """Adds a query parameter to a url. Replaces the current value if it already exists in the URL. Args: url: string, url to add the query parameter to. name: string, query parameter name. value: string, query parameter value. Returns: Updated query parameter. Does not update the url if value is None. """ if value is None: return url else: parsed = list(urlparse.urlparse(url)) q = dict(parse_qsl(parsed[4])) q[name] = value parsed[4] = urllib.urlencode(q) return urlparse.urlunparse(parsed) def key2param(key): """Converts key names into parameter names. For example, converting "max-results" -> "max_results" Args: key: string, the method key name. Returns: A safe method name based on the key name. """ result = [] key = list(key) if not key[0].isalpha(): result.append('x') for c in key: if c.isalnum(): result.append(c) else: result.append('_') return ''.join(result) def build(serviceName, version, http=None, discoveryServiceUrl=DISCOVERY_URI, developerKey=None, model=None, requestBuilder=HttpRequest): """Construct a Resource for interacting with an API. Construct a Resource object for interacting with an API. The serviceName and version are the names from the Discovery service. Args: serviceName: string, name of the service. version: string, the version of the service. http: httplib2.Http, An instance of httplib2.Http or something that acts like it that HTTP requests will be made through. discoveryServiceUrl: string, a URI Template that points to the location of the discovery service. It should have two parameters {api} and {apiVersion} that when filled in produce an absolute URI to the discovery document for that service. developerKey: string, key obtained from https://code.google.com/apis/console. model: apiclient.Model, converts to and from the wire format. requestBuilder: apiclient.http.HttpRequest, encapsulator for an HTTP request. Returns: A Resource object with methods for interacting with the service. """ params = { 'api': serviceName, 'apiVersion': version } if http is None: http = httplib2.Http() requested_url = uritemplate.expand(discoveryServiceUrl, params) # REMOTE_ADDR is defined by the CGI spec [RFC3875] as the environment # variable that contains the network address of the client sending the # request. If it exists then add that to the request for the discovery # document to avoid exceeding the quota on discovery requests. if 'REMOTE_ADDR' in os.environ: requested_url = _add_query_parameter(requested_url, 'userIp', os.environ['REMOTE_ADDR']) logger.info('URL being requested: %s' % requested_url) resp, content = http.request(requested_url) if resp.status == 404: raise UnknownApiNameOrVersion("name: %s version: %s" % (serviceName, version)) if resp.status >= 400: raise HttpError(resp, content, requested_url) try: service = simplejson.loads(content) except ValueError, e: logger.error('Failed to parse as JSON: ' + content) raise InvalidJsonError() return build_from_document(content, discoveryServiceUrl, http=http, developerKey=developerKey, model=model, requestBuilder=requestBuilder) def build_from_document( service, base, future=None, http=None, developerKey=None, model=None, requestBuilder=HttpRequest): """Create a Resource for interacting with an API. Same as `build()`, but constructs the Resource object from a discovery document that is it given, as opposed to retrieving one over HTTP. Args: service: string, discovery document. base: string, base URI for all HTTP requests, usually the discovery URI. future: string, discovery document with future capabilities (deprecated). http: httplib2.Http, An instance of httplib2.Http or something that acts like it that HTTP requests will be made through. developerKey: string, Key for controlling API usage, generated from the API Console. model: Model class instance that serializes and de-serializes requests and responses. requestBuilder: Takes an http request and packages it up to be executed. Returns: A Resource object with methods for interacting with the service. """ # future is no longer used. future = {} service = simplejson.loads(service) base = urlparse.urljoin(base, service['basePath']) schema = Schemas(service) if model is None: features = service.get('features', []) model = JsonModel('dataWrapper' in features) resource = _createResource(http, base, model, requestBuilder, developerKey, service, service, schema) return resource def _cast(value, schema_type): """Convert value to a string based on JSON Schema type. See http://tools.ietf.org/html/draft-zyp-json-schema-03 for more details on JSON Schema. Args: value: any, the value to convert schema_type: string, the type that value should be interpreted as Returns: A string representation of 'value' based on the schema_type. """ if schema_type == 'string': if type(value) == type('') or type(value) == type(u''): return value else: return str(value) elif schema_type == 'integer': return str(int(value)) elif schema_type == 'number': return str(float(value)) elif schema_type == 'boolean': return str(bool(value)).lower() else: if type(value) == type('') or type(value) == type(u''): return value else: return str(value) MULTIPLIERS = { "KB": 2 ** 10, "MB": 2 ** 20, "GB": 2 ** 30, "TB": 2 ** 40, } def _media_size_to_long(maxSize): """Convert a string media size, such as 10GB or 3TB into an integer. Args: maxSize: string, size as a string, such as 2MB or 7GB. Returns: The size as an integer value. """ if len(maxSize) < 2: return 0 units = maxSize[-2:].upper() multiplier = MULTIPLIERS.get(units, 0) if multiplier: return int(maxSize[:-2]) * multiplier else: return int(maxSize) def _createResource(http, baseUrl, model, requestBuilder, developerKey, resourceDesc, rootDesc, schema): """Build a Resource from the API description. Args: http: httplib2.Http, Object to make http requests with. baseUrl: string, base URL for the API. All requests are relative to this URI. model: apiclient.Model, converts to and from the wire format. requestBuilder: class or callable that instantiates an apiclient.HttpRequest object. developerKey: string, key obtained from https://code.google.com/apis/console resourceDesc: object, section of deserialized discovery document that describes a resource. Note that the top level discovery document is considered a resource. rootDesc: object, the entire deserialized discovery document. schema: object, mapping of schema names to schema descriptions. Returns: An instance of Resource with all the methods attached for interacting with that resource. """ class Resource(object): """A class for interacting with a resource.""" def __init__(self): self._http = http self._baseUrl = baseUrl self._model = model self._developerKey = developerKey self._requestBuilder = requestBuilder def createMethod(theclass, methodName, methodDesc, rootDesc): """Creates a method for attaching to a Resource. Args: theclass: type, the class to attach methods to. methodName: string, name of the method to use. methodDesc: object, fragment of deserialized discovery document that describes the method. rootDesc: object, the entire deserialized discovery document. """ methodName = fix_method_name(methodName) pathUrl = methodDesc['path'] httpMethod = methodDesc['httpMethod'] methodId = methodDesc['id'] mediaPathUrl = None accept = [] maxSize = 0 if 'mediaUpload' in methodDesc: mediaUpload = methodDesc['mediaUpload'] # TODO(jcgregorio) Use URLs from discovery once it is updated. parsed = list(urlparse.urlparse(baseUrl)) basePath = parsed[2] mediaPathUrl = '/upload' + basePath + pathUrl accept = mediaUpload['accept'] maxSize = _media_size_to_long(mediaUpload.get('maxSize', '')) if 'parameters' not in methodDesc: methodDesc['parameters'] = {} # Add in the parameters common to all methods. for name, desc in rootDesc.get('parameters', {}).iteritems(): methodDesc['parameters'][name] = desc # Add in undocumented query parameters. for name in STACK_QUERY_PARAMETERS: methodDesc['parameters'][name] = { 'type': 'string', 'location': 'query' } if httpMethod in ['PUT', 'POST', 'PATCH'] and 'request' in methodDesc: methodDesc['parameters']['body'] = { 'description': 'The request body.', 'type': 'object', 'required': True, } if 'request' in methodDesc: methodDesc['parameters']['body'].update(methodDesc['request']) else: methodDesc['parameters']['body']['type'] = 'object' if 'mediaUpload' in methodDesc: methodDesc['parameters']['media_body'] = { 'description': 'The filename of the media request body.', 'type': 'string', 'required': False, } if 'body' in methodDesc['parameters']: methodDesc['parameters']['body']['required'] = False argmap = {} # Map from method parameter name to query parameter name required_params = [] # Required parameters repeated_params = [] # Repeated parameters pattern_params = {} # Parameters that must match a regex query_params = [] # Parameters that will be used in the query string path_params = {} # Parameters that will be used in the base URL param_type = {} # The type of the parameter enum_params = {} # Allowable enumeration values for each parameter if 'parameters' in methodDesc: for arg, desc in methodDesc['parameters'].iteritems(): param = key2param(arg) argmap[param] = arg if desc.get('pattern', ''): pattern_params[param] = desc['pattern'] if desc.get('enum', ''): enum_params[param] = desc['enum'] if desc.get('required', False): required_params.append(param) if desc.get('repeated', False): repeated_params.append(param) if desc.get('location') == 'query': query_params.append(param) if desc.get('location') == 'path': path_params[param] = param param_type[param] = desc.get('type', 'string') for match in URITEMPLATE.finditer(pathUrl): for namematch in VARNAME.finditer(match.group(0)): name = key2param(namematch.group(0)) path_params[name] = name if name in query_params: query_params.remove(name) def method(self, **kwargs): # Don't bother with doc string, it will be over-written by createMethod. for name in kwargs.iterkeys(): if name not in argmap: raise TypeError('Got an unexpected keyword argument "%s"' % name) # Remove args that have a value of None. keys = kwargs.keys() for name in keys: if kwargs[name] is None: del kwargs[name] for name in required_params: if name not in kwargs: raise TypeError('Missing required parameter "%s"' % name) for name, regex in pattern_params.iteritems(): if name in kwargs: if isinstance(kwargs[name], basestring): pvalues = [kwargs[name]] else: pvalues = kwargs[name] for pvalue in pvalues: if re.match(regex, pvalue) is None: raise TypeError( 'Parameter "%s" value "%s" does not match the pattern "%s"' % (name, pvalue, regex)) for name, enums in enum_params.iteritems(): if name in kwargs: # We need to handle the case of a repeated enum # name differently, since we want to handle both # arg='value' and arg=['value1', 'value2'] if (name in repeated_params and not isinstance(kwargs[name], basestring)): values = kwargs[name] else: values = [kwargs[name]] for value in values: if value not in enums: raise TypeError( 'Parameter "%s" value "%s" is not an allowed value in "%s"' % (name, value, str(enums))) actual_query_params = {} actual_path_params = {} for key, value in kwargs.iteritems(): to_type = param_type.get(key, 'string') # For repeated parameters we cast each member of the list. if key in repeated_params and type(value) == type([]): cast_value = [_cast(x, to_type) for x in value] else: cast_value = _cast(value, to_type) if key in query_params: actual_query_params[argmap[key]] = cast_value if key in path_params: actual_path_params[argmap[key]] = cast_value body_value = kwargs.get('body', None) media_filename = kwargs.get('media_body', None) if self._developerKey: actual_query_params['key'] = self._developerKey model = self._model # If there is no schema for the response then presume a binary blob. if methodName.endswith('_media'): model = MediaModel() elif 'response' not in methodDesc: model = RawModel() headers = {} headers, params, query, body = model.request(headers, actual_path_params, actual_query_params, body_value) expanded_url = uritemplate.expand(pathUrl, params) url = urlparse.urljoin(self._baseUrl, expanded_url + query) resumable = None multipart_boundary = '' if media_filename: # Ensure we end up with a valid MediaUpload object. if isinstance(media_filename, basestring): (media_mime_type, encoding) = mimetypes.guess_type(media_filename) if media_mime_type is None: raise UnknownFileType(media_filename) if not mimeparse.best_match([media_mime_type], ','.join(accept)): raise UnacceptableMimeTypeError(media_mime_type) media_upload = MediaFileUpload(media_filename, media_mime_type) elif isinstance(media_filename, MediaUpload): media_upload = media_filename else: raise TypeError('media_filename must be str or MediaUpload.') # Check the maxSize if maxSize > 0 and media_upload.size() > maxSize: raise MediaUploadSizeError("Media larger than: %s" % maxSize) # Use the media path uri for media uploads expanded_url = uritemplate.expand(mediaPathUrl, params) url = urlparse.urljoin(self._baseUrl, expanded_url + query) if media_upload.resumable(): url = _add_query_parameter(url, 'uploadType', 'resumable') if media_upload.resumable(): # This is all we need to do for resumable, if the body exists it gets # sent in the first request, otherwise an empty body is sent. resumable = media_upload else: # A non-resumable upload if body is None: # This is a simple media upload headers['content-type'] = media_upload.mimetype() body = media_upload.getbytes(0, media_upload.size()) url = _add_query_parameter(url, 'uploadType', 'media') else: # This is a multipart/related upload. msgRoot = MIMEMultipart('related') # msgRoot should not write out it's own headers setattr(msgRoot, '_write_headers', lambda self: None) # attach the body as one part msg = MIMENonMultipart(*headers['content-type'].split('/')) msg.set_payload(body) msgRoot.attach(msg) # attach the media as the second part msg = MIMENonMultipart(*media_upload.mimetype().split('/')) msg['Content-Transfer-Encoding'] = 'binary' payload = media_upload.getbytes(0, media_upload.size()) msg.set_payload(payload) msgRoot.attach(msg) body = msgRoot.as_string() multipart_boundary = msgRoot.get_boundary() headers['content-type'] = ('multipart/related; ' 'boundary="%s"') % multipart_boundary url = _add_query_parameter(url, 'uploadType', 'multipart') logger.info('URL being requested: %s' % url) return self._requestBuilder(self._http, model.response, url, method=httpMethod, body=body, headers=headers, methodId=methodId, resumable=resumable) docs = [methodDesc.get('description', DEFAULT_METHOD_DOC), '\n\n'] if len(argmap) > 0: docs.append('Args:\n') # Skip undocumented params and params common to all methods. skip_parameters = rootDesc.get('parameters', {}).keys() skip_parameters.append(STACK_QUERY_PARAMETERS) for arg in argmap.iterkeys(): if arg in skip_parameters: continue repeated = '' if arg in repeated_params: repeated = ' (repeated)' required = '' if arg in required_params: required = ' (required)' paramdesc = methodDesc['parameters'][argmap[arg]] paramdoc = paramdesc.get('description', 'A parameter') if '$ref' in paramdesc: docs.append( (' %s: object, %s%s%s\n The object takes the' ' form of:\n\n%s\n\n') % (arg, paramdoc, required, repeated, schema.prettyPrintByName(paramdesc['$ref']))) else: paramtype = paramdesc.get('type', 'string') docs.append(' %s: %s, %s%s%s\n' % (arg, paramtype, paramdoc, required, repeated)) enum = paramdesc.get('enum', []) enumDesc = paramdesc.get('enumDescriptions', []) if enum and enumDesc: docs.append(' Allowed values\n') for (name, desc) in zip(enum, enumDesc): docs.append(' %s - %s\n' % (name, desc)) if 'response' in methodDesc: if methodName.endswith('_media'): docs.append('\nReturns:\n The media object as a string.\n\n ') else: docs.append('\nReturns:\n An object of the form:\n\n ') docs.append(schema.prettyPrintSchema(methodDesc['response'])) setattr(method, '__doc__', ''.join(docs)) setattr(theclass, methodName, method) def createNextMethod(theclass, methodName, methodDesc, rootDesc): """Creates any _next methods for attaching to a Resource. The _next methods allow for easy iteration through list() responses. Args: theclass: type, the class to attach methods to. methodName: string, name of the method to use. methodDesc: object, fragment of deserialized discovery document that describes the method. rootDesc: object, the entire deserialized discovery document. """ methodName = fix_method_name(methodName) methodId = methodDesc['id'] + '.next' def methodNext(self, previous_request, previous_response): """Retrieves the next page of results. Args: previous_request: The request for the previous page. previous_response: The response from the request for the previous page. Returns: A request object that you can call 'execute()' on to request the next page. Returns None if there are no more items in the collection. """ # Retrieve nextPageToken from previous_response # Use as pageToken in previous_request to create new request. if 'nextPageToken' not in previous_response: return None request = copy.copy(previous_request) pageToken = previous_response['nextPageToken'] parsed = list(urlparse.urlparse(request.uri)) q = parse_qsl(parsed[4]) # Find and remove old 'pageToken' value from URI newq = [(key, value) for (key, value) in q if key != 'pageToken'] newq.append(('pageToken', pageToken)) parsed[4] = urllib.urlencode(newq) uri = urlparse.urlunparse(parsed) request.uri = uri logger.info('URL being requested: %s' % uri) return request setattr(theclass, methodName, methodNext) # Add basic methods to Resource if 'methods' in resourceDesc: for methodName, methodDesc in resourceDesc['methods'].iteritems(): createMethod(Resource, methodName, methodDesc, rootDesc) # Add in _media methods. The functionality of the attached method will # change when it sees that the method name ends in _media. if methodDesc.get('supportsMediaDownload', False): createMethod(Resource, methodName + '_media', methodDesc, rootDesc) # Add in nested resources if 'resources' in resourceDesc: def createResourceMethod(theclass, methodName, methodDesc, rootDesc): """Create a method on the Resource to access a nested Resource. Args: theclass: type, the class to attach methods to. methodName: string, name of the method to use. methodDesc: object, fragment of deserialized discovery document that describes the method. rootDesc: object, the entire deserialized discovery document. """ methodName = fix_method_name(methodName) def methodResource(self): return _createResource(self._http, self._baseUrl, self._model, self._requestBuilder, self._developerKey, methodDesc, rootDesc, schema) setattr(methodResource, '__doc__', 'A collection resource.') setattr(methodResource, '__is_resource__', True) setattr(theclass, methodName, methodResource) for methodName, methodDesc in resourceDesc['resources'].iteritems(): createResourceMethod(Resource, methodName, methodDesc, rootDesc) # Add _next() methods # Look for response bodies in schema that contain nextPageToken, and methods # that take a pageToken parameter. if 'methods' in resourceDesc: for methodName, methodDesc in resourceDesc['methods'].iteritems(): if 'response' in methodDesc: responseSchema = methodDesc['response'] if '$ref' in responseSchema: responseSchema = schema.get(responseSchema['$ref']) hasNextPageToken = 'nextPageToken' in responseSchema.get('properties', {}) hasPageToken = 'pageToken' in methodDesc.get('parameters', {}) if hasNextPageToken and hasPageToken: createNextMethod(Resource, methodName + '_next', resourceDesc['methods'][methodName], methodName) return Resource()
Python
# Copyright (C) 2010 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Utilities for Google App Engine Utilities for making it easier to use the Google API Client for Python on Google App Engine. """ __author__ = 'jcgregorio@google.com (Joe Gregorio)' import pickle from google.appengine.ext import db from apiclient.oauth import OAuthCredentials from apiclient.oauth import FlowThreeLegged class FlowThreeLeggedProperty(db.Property): """Utility property that allows easy storage and retreival of an apiclient.oauth.FlowThreeLegged""" # Tell what the user type is. data_type = FlowThreeLegged # For writing to datastore. def get_value_for_datastore(self, model_instance): flow = super(FlowThreeLeggedProperty, self).get_value_for_datastore(model_instance) return db.Blob(pickle.dumps(flow)) # For reading from datastore. def make_value_from_datastore(self, value): if value is None: return None return pickle.loads(value) def validate(self, value): if value is not None and not isinstance(value, FlowThreeLegged): raise BadValueError('Property %s must be convertible ' 'to a FlowThreeLegged instance (%s)' % (self.name, value)) return super(FlowThreeLeggedProperty, self).validate(value) def empty(self, value): return not value class OAuthCredentialsProperty(db.Property): """Utility property that allows easy storage and retrieval of apiclient.oath.OAuthCredentials """ # Tell what the user type is. data_type = OAuthCredentials # For writing to datastore. def get_value_for_datastore(self, model_instance): cred = super(OAuthCredentialsProperty, self).get_value_for_datastore(model_instance) return db.Blob(pickle.dumps(cred)) # For reading from datastore. def make_value_from_datastore(self, value): if value is None: return None return pickle.loads(value) def validate(self, value): if value is not None and not isinstance(value, OAuthCredentials): raise BadValueError('Property %s must be convertible ' 'to an OAuthCredentials instance (%s)' % (self.name, value)) return super(OAuthCredentialsProperty, self).validate(value) def empty(self, value): return not value class StorageByKeyName(object): """Store and retrieve a single credential to and from the App Engine datastore. This Storage helper presumes the Credentials have been stored as a CredenialsProperty on a datastore model class, and that entities are stored by key_name. """ def __init__(self, model, key_name, property_name): """Constructor for Storage. Args: model: db.Model, model class key_name: string, key name for the entity that has the credentials property_name: string, name of the property that is a CredentialsProperty """ self.model = model self.key_name = key_name self.property_name = property_name def get(self): """Retrieve Credential from datastore. Returns: Credentials """ entity = self.model.get_or_insert(self.key_name) credential = getattr(entity, self.property_name) if credential and hasattr(credential, 'set_store'): credential.set_store(self.put) return credential def put(self, credentials): """Write a Credentials to the datastore. Args: credentials: Credentials, the credentials to store. """ entity = self.model.get_or_insert(self.key_name) setattr(entity, self.property_name, credentials) entity.put()
Python
# Copyright (C) 2010 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Command-line tools for authenticating via OAuth 1.0 Do the OAuth 1.0 Three Legged Dance for a command line application. Stores the generated credentials in a common file that is used by other example apps in the same directory. """ __author__ = 'jcgregorio@google.com (Joe Gregorio)' __all__ = ["run"] import BaseHTTPServer import gflags import logging import socket import sys from optparse import OptionParser from apiclient.oauth import RequestError try: from urlparse import parse_qsl except ImportError: from cgi import parse_qsl FLAGS = gflags.FLAGS gflags.DEFINE_boolean('auth_local_webserver', True, ('Run a local web server to handle redirects during ' 'OAuth authorization.')) gflags.DEFINE_string('auth_host_name', 'localhost', ('Host name to use when running a local web server to ' 'handle redirects during OAuth authorization.')) gflags.DEFINE_multi_int('auth_host_port', [8080, 8090], ('Port to use when running a local web server to ' 'handle redirects during OAuth authorization.')) class ClientRedirectServer(BaseHTTPServer.HTTPServer): """A server to handle OAuth 1.0 redirects back to localhost. Waits for a single request and parses the query parameters into query_params and then stops serving. """ query_params = {} class ClientRedirectHandler(BaseHTTPServer.BaseHTTPRequestHandler): """A handler for OAuth 1.0 redirects back to localhost. Waits for a single request and parses the query parameters into the servers query_params and then stops serving. """ def do_GET(s): """Handle a GET request Parses the query parameters and prints a message if the flow has completed. Note that we can't detect if an error occurred. """ s.send_response(200) s.send_header("Content-type", "text/html") s.end_headers() query = s.path.split('?', 1)[-1] query = dict(parse_qsl(query)) s.server.query_params = query s.wfile.write("<html><head><title>Authentication Status</title></head>") s.wfile.write("<body><p>The authentication flow has completed.</p>") s.wfile.write("</body></html>") def log_message(self, format, *args): """Do not log messages to stdout while running as command line program.""" pass def run(flow, storage): """Core code for a command-line application. Args: flow: Flow, an OAuth 1.0 Flow to step through. storage: Storage, a Storage to store the credential in. Returns: Credentials, the obtained credential. Exceptions: RequestError: if step2 of the flow fails. Args: """ if FLAGS.auth_local_webserver: success = False port_number = 0 for port in FLAGS.auth_host_port: port_number = port try: httpd = BaseHTTPServer.HTTPServer((FLAGS.auth_host_name, port), ClientRedirectHandler) except socket.error, e: pass else: success = True break FLAGS.auth_local_webserver = success if FLAGS.auth_local_webserver: oauth_callback = 'http://%s:%s/' % (FLAGS.auth_host_name, port_number) else: oauth_callback = 'oob' authorize_url = flow.step1_get_authorize_url(oauth_callback) print 'Go to the following link in your browser:' print authorize_url print if FLAGS.auth_local_webserver: print 'If your browser is on a different machine then exit and re-run this' print 'application with the command-line parameter --noauth_local_webserver.' print if FLAGS.auth_local_webserver: httpd.handle_request() if 'error' in httpd.query_params: sys.exit('Authentication request was rejected.') if 'oauth_verifier' in httpd.query_params: code = httpd.query_params['oauth_verifier'] else: accepted = 'n' while accepted.lower() == 'n': accepted = raw_input('Have you authorized me? (y/n) ') code = raw_input('What is the verification code? ').strip() try: credentials = flow.step2_exchange(code) except RequestError: sys.exit('The authentication has failed.') storage.put(credentials) credentials.set_store(storage.put) print "You have successfully authenticated." return credentials
Python
# Copyright (C) 2010 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Utilities for OAuth. Utilities for making it easier to work with OAuth 1.0 credentials. """ __author__ = 'jcgregorio@google.com (Joe Gregorio)' import pickle import threading from apiclient.oauth import Storage as BaseStorage class Storage(BaseStorage): """Store and retrieve a single credential to and from a file.""" def __init__(self, filename): self._filename = filename self._lock = threading.Lock() def get(self): """Retrieve Credential from file. Returns: apiclient.oauth.Credentials """ self._lock.acquire() try: f = open(self._filename, 'r') credentials = pickle.loads(f.read()) f.close() credentials.set_store(self.put) except: credentials = None self._lock.release() return credentials def put(self, credentials): """Write a pickled Credentials to file. Args: credentials: Credentials, the credentials to store. """ self._lock.acquire() f = open(self._filename, 'w') f.write(pickle.dumps(credentials)) f.close() self._lock.release()
Python
# Copyright (C) 2010 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import apiclient import base64 import pickle from django.db import models class OAuthCredentialsField(models.Field): __metaclass__ = models.SubfieldBase def db_type(self): return 'VARCHAR' def to_python(self, value): if value is None: return None if isinstance(value, apiclient.oauth.Credentials): return value return pickle.loads(base64.b64decode(value)) def get_db_prep_value(self, value): return base64.b64encode(pickle.dumps(value)) class FlowThreeLeggedField(models.Field): __metaclass__ = models.SubfieldBase def db_type(self): return 'VARCHAR' def to_python(self, value): print "In to_python", value if value is None: return None if isinstance(value, apiclient.oauth.FlowThreeLegged): return value return pickle.loads(base64.b64decode(value)) def get_db_prep_value(self, value): return base64.b64encode(pickle.dumps(value))
Python
__version__ = "1.0c2"
Python
#!/usr/bin/python2.4 # # Copyright (C) 2010 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Model objects for requests and responses. Each API may support one or more serializations, such as JSON, Atom, etc. The model classes are responsible for converting between the wire format and the Python object representation. """ __author__ = 'jcgregorio@google.com (Joe Gregorio)' import gflags import logging import urllib from errors import HttpError from oauth2client.anyjson import simplejson FLAGS = gflags.FLAGS gflags.DEFINE_boolean('dump_request_response', False, 'Dump all http server requests and responses. ' ) def _abstract(): raise NotImplementedError('You need to override this function') class Model(object): """Model base class. All Model classes should implement this interface. The Model serializes and de-serializes between a wire format such as JSON and a Python object representation. """ def request(self, headers, path_params, query_params, body_value): """Updates outgoing requests with a serialized body. Args: headers: dict, request headers path_params: dict, parameters that appear in the request path query_params: dict, parameters that appear in the query body_value: object, the request body as a Python object, which must be serializable. Returns: A tuple of (headers, path_params, query, body) headers: dict, request headers path_params: dict, parameters that appear in the request path query: string, query part of the request URI body: string, the body serialized in the desired wire format. """ _abstract() def response(self, resp, content): """Convert the response wire format into a Python object. Args: resp: httplib2.Response, the HTTP response headers and status content: string, the body of the HTTP response Returns: The body de-serialized as a Python object. Raises: apiclient.errors.HttpError if a non 2xx response is received. """ _abstract() class BaseModel(Model): """Base model class. Subclasses should provide implementations for the "serialize" and "deserialize" methods, as well as values for the following class attributes. Attributes: accept: The value to use for the HTTP Accept header. content_type: The value to use for the HTTP Content-type header. no_content_response: The value to return when deserializing a 204 "No Content" response. alt_param: The value to supply as the "alt" query parameter for requests. """ accept = None content_type = None no_content_response = None alt_param = None def _log_request(self, headers, path_params, query, body): """Logs debugging information about the request if requested.""" if FLAGS.dump_request_response: logging.info('--request-start--') logging.info('-headers-start-') for h, v in headers.iteritems(): logging.info('%s: %s', h, v) logging.info('-headers-end-') logging.info('-path-parameters-start-') for h, v in path_params.iteritems(): logging.info('%s: %s', h, v) logging.info('-path-parameters-end-') logging.info('body: %s', body) logging.info('query: %s', query) logging.info('--request-end--') def request(self, headers, path_params, query_params, body_value): """Updates outgoing requests with a serialized body. Args: headers: dict, request headers path_params: dict, parameters that appear in the request path query_params: dict, parameters that appear in the query body_value: object, the request body as a Python object, which must be serializable by simplejson. Returns: A tuple of (headers, path_params, query, body) headers: dict, request headers path_params: dict, parameters that appear in the request path query: string, query part of the request URI body: string, the body serialized as JSON """ query = self._build_query(query_params) headers['accept'] = self.accept headers['accept-encoding'] = 'gzip, deflate' if 'user-agent' in headers: headers['user-agent'] += ' ' else: headers['user-agent'] = '' headers['user-agent'] += 'google-api-python-client/1.0' if body_value is not None: headers['content-type'] = self.content_type body_value = self.serialize(body_value) self._log_request(headers, path_params, query, body_value) return (headers, path_params, query, body_value) def _build_query(self, params): """Builds a query string. Args: params: dict, the query parameters Returns: The query parameters properly encoded into an HTTP URI query string. """ if self.alt_param is not None: params.update({'alt': self.alt_param}) astuples = [] for key, value in params.iteritems(): if type(value) == type([]): for x in value: x = x.encode('utf-8') astuples.append((key, x)) else: if getattr(value, 'encode', False) and callable(value.encode): value = value.encode('utf-8') astuples.append((key, value)) return '?' + urllib.urlencode(astuples) def _log_response(self, resp, content): """Logs debugging information about the response if requested.""" if FLAGS.dump_request_response: logging.info('--response-start--') for h, v in resp.iteritems(): logging.info('%s: %s', h, v) if content: logging.info(content) logging.info('--response-end--') def response(self, resp, content): """Convert the response wire format into a Python object. Args: resp: httplib2.Response, the HTTP response headers and status content: string, the body of the HTTP response Returns: The body de-serialized as a Python object. Raises: apiclient.errors.HttpError if a non 2xx response is received. """ self._log_response(resp, content) # Error handling is TBD, for example, do we retry # for some operation/error combinations? if resp.status < 300: if resp.status == 204: # A 204: No Content response should be treated differently # to all the other success states return self.no_content_response return self.deserialize(content) else: logging.debug('Content from bad request was: %s' % content) raise HttpError(resp, content) def serialize(self, body_value): """Perform the actual Python object serialization. Args: body_value: object, the request body as a Python object. Returns: string, the body in serialized form. """ _abstract() def deserialize(self, content): """Perform the actual deserialization from response string to Python object. Args: content: string, the body of the HTTP response Returns: The body de-serialized as a Python object. """ _abstract() class JsonModel(BaseModel): """Model class for JSON. Serializes and de-serializes between JSON and the Python object representation of HTTP request and response bodies. """ accept = 'application/json' content_type = 'application/json' alt_param = 'json' def __init__(self, data_wrapper=False): """Construct a JsonModel. Args: data_wrapper: boolean, wrap requests and responses in a data wrapper """ self._data_wrapper = data_wrapper def serialize(self, body_value): if (isinstance(body_value, dict) and 'data' not in body_value and self._data_wrapper): body_value = {'data': body_value} return simplejson.dumps(body_value) def deserialize(self, content): body = simplejson.loads(content) if isinstance(body, dict) and 'data' in body: body = body['data'] return body @property def no_content_response(self): return {} class RawModel(JsonModel): """Model class for requests that don't return JSON. Serializes and de-serializes between JSON and the Python object representation of HTTP request, and returns the raw bytes of the response body. """ accept = '*/*' content_type = 'application/json' alt_param = None def deserialize(self, content): return content @property def no_content_response(self): return '' class MediaModel(JsonModel): """Model class for requests that return Media. Serializes and de-serializes between JSON and the Python object representation of HTTP request, and returns the raw bytes of the response body. """ accept = '*/*' content_type = 'application/json' alt_param = 'media' def deserialize(self, content): return content @property def no_content_response(self): return '' class ProtocolBufferModel(BaseModel): """Model class for protocol buffers. Serializes and de-serializes the binary protocol buffer sent in the HTTP request and response bodies. """ accept = 'application/x-protobuf' content_type = 'application/x-protobuf' alt_param = 'proto' def __init__(self, protocol_buffer): """Constructs a ProtocolBufferModel. The serialzed protocol buffer returned in an HTTP response will be de-serialized using the given protocol buffer class. Args: protocol_buffer: The protocol buffer class used to de-serialize a response from the API. """ self._protocol_buffer = protocol_buffer def serialize(self, body_value): return body_value.SerializeToString() def deserialize(self, content): return self._protocol_buffer.FromString(content) @property def no_content_response(self): return self._protocol_buffer() def makepatch(original, modified): """Create a patch object. Some methods support PATCH, an efficient way to send updates to a resource. This method allows the easy construction of patch bodies by looking at the differences between a resource before and after it was modified. Args: original: object, the original deserialized resource modified: object, the modified deserialized resource Returns: An object that contains only the changes from original to modified, in a form suitable to pass to a PATCH method. Example usage: item = service.activities().get(postid=postid, userid=userid).execute() original = copy.deepcopy(item) item['object']['content'] = 'This is updated.' service.activities.patch(postid=postid, userid=userid, body=makepatch(original, item)).execute() """ patch = {} for key, original_value in original.iteritems(): modified_value = modified.get(key, None) if modified_value is None: # Use None to signal that the element is deleted patch[key] = None elif original_value != modified_value: if type(original_value) == type({}): # Recursively descend objects patch[key] = makepatch(original_value, modified_value) else: # In the case of simple types or arrays we just replace patch[key] = modified_value else: # Don't add anything to patch if there's no change pass for key in modified: if key not in original: patch[key] = modified[key] return patch
Python
#!/usr/bin/python2.4 # # Copyright (C) 2010 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Errors for the library. All exceptions defined by the library should be defined in this file. """ __author__ = 'jcgregorio@google.com (Joe Gregorio)' from oauth2client.anyjson import simplejson class Error(Exception): """Base error for this module.""" pass class HttpError(Error): """HTTP data was invalid or unexpected.""" def __init__(self, resp, content, uri=None): self.resp = resp self.content = content self.uri = uri def _get_reason(self): """Calculate the reason for the error from the response content.""" if self.resp.get('content-type', '').startswith('application/json'): try: data = simplejson.loads(self.content) reason = data['error']['message'] except (ValueError, KeyError): reason = self.content else: reason = self.resp.reason return reason def __repr__(self): if self.uri: return '<HttpError %s when requesting %s returned "%s">' % ( self.resp.status, self.uri, self._get_reason()) else: return '<HttpError %s "%s">' % (self.resp.status, self._get_reason()) __str__ = __repr__ class InvalidJsonError(Error): """The JSON returned could not be parsed.""" pass class UnknownLinkType(Error): """Link type unknown or unexpected.""" pass class UnknownApiNameOrVersion(Error): """No API with that name and version exists.""" pass class UnacceptableMimeTypeError(Error): """That is an unacceptable mimetype for this operation.""" pass class MediaUploadSizeError(Error): """Media is larger than the method can accept.""" pass class ResumableUploadError(Error): """Error occured during resumable upload.""" pass class BatchError(HttpError): """Error occured during batch operations.""" def __init__(self, reason, resp=None, content=None): self.resp = resp self.content = content self.reason = reason def __repr__(self): return '<BatchError %s "%s">' % (self.resp.status, self.reason) __str__ = __repr__ class UnexpectedMethodError(Error): """Exception raised by RequestMockBuilder on unexpected calls.""" def __init__(self, methodId=None): """Constructor for an UnexpectedMethodError.""" super(UnexpectedMethodError, self).__init__( 'Received unexpected call %s' % methodId) class UnexpectedBodyError(Error): """Exception raised by RequestMockBuilder on unexpected bodies.""" def __init__(self, expected, provided): """Constructor for an UnexpectedMethodError.""" super(UnexpectedBodyError, self).__init__( 'Expected: [%s] - Provided: [%s]' % (expected, provided))
Python
""" iri2uri Converts an IRI to a URI. """ __author__ = "Joe Gregorio (joe@bitworking.org)" __copyright__ = "Copyright 2006, Joe Gregorio" __contributors__ = [] __version__ = "1.0.0" __license__ = "MIT" __history__ = """ """ import urlparse # Convert an IRI to a URI following the rules in RFC 3987 # # The characters we need to enocde and escape are defined in the spec: # # iprivate = %xE000-F8FF / %xF0000-FFFFD / %x100000-10FFFD # ucschar = %xA0-D7FF / %xF900-FDCF / %xFDF0-FFEF # / %x10000-1FFFD / %x20000-2FFFD / %x30000-3FFFD # / %x40000-4FFFD / %x50000-5FFFD / %x60000-6FFFD # / %x70000-7FFFD / %x80000-8FFFD / %x90000-9FFFD # / %xA0000-AFFFD / %xB0000-BFFFD / %xC0000-CFFFD # / %xD0000-DFFFD / %xE1000-EFFFD escape_range = [ (0xA0, 0xD7FF ), (0xE000, 0xF8FF ), (0xF900, 0xFDCF ), (0xFDF0, 0xFFEF), (0x10000, 0x1FFFD ), (0x20000, 0x2FFFD ), (0x30000, 0x3FFFD), (0x40000, 0x4FFFD ), (0x50000, 0x5FFFD ), (0x60000, 0x6FFFD), (0x70000, 0x7FFFD ), (0x80000, 0x8FFFD ), (0x90000, 0x9FFFD), (0xA0000, 0xAFFFD ), (0xB0000, 0xBFFFD ), (0xC0000, 0xCFFFD), (0xD0000, 0xDFFFD ), (0xE1000, 0xEFFFD), (0xF0000, 0xFFFFD ), (0x100000, 0x10FFFD) ] def encode(c): retval = c i = ord(c) for low, high in escape_range: if i < low: break if i >= low and i <= high: retval = "".join(["%%%2X" % ord(o) for o in c.encode('utf-8')]) break return retval def iri2uri(uri): """Convert an IRI to a URI. Note that IRIs must be passed in a unicode strings. That is, do not utf-8 encode the IRI before passing it into the function.""" if isinstance(uri ,unicode): (scheme, authority, path, query, fragment) = urlparse.urlsplit(uri) authority = authority.encode('idna') # For each character in 'ucschar' or 'iprivate' # 1. encode as utf-8 # 2. then %-encode each octet of that utf-8 uri = urlparse.urlunsplit((scheme, authority, path, query, fragment)) uri = "".join([encode(c) for c in uri]) return uri if __name__ == "__main__": import unittest class Test(unittest.TestCase): def test_uris(self): """Test that URIs are invariant under the transformation.""" invariant = [ u"ftp://ftp.is.co.za/rfc/rfc1808.txt", u"http://www.ietf.org/rfc/rfc2396.txt", u"ldap://[2001:db8::7]/c=GB?objectClass?one", u"mailto:John.Doe@example.com", u"news:comp.infosystems.www.servers.unix", u"tel:+1-816-555-1212", u"telnet://192.0.2.16:80/", u"urn:oasis:names:specification:docbook:dtd:xml:4.1.2" ] for uri in invariant: self.assertEqual(uri, iri2uri(uri)) def test_iri(self): """ Test that the right type of escaping is done for each part of the URI.""" self.assertEqual("http://xn--o3h.com/%E2%98%84", iri2uri(u"http://\N{COMET}.com/\N{COMET}")) self.assertEqual("http://bitworking.org/?fred=%E2%98%84", iri2uri(u"http://bitworking.org/?fred=\N{COMET}")) self.assertEqual("http://bitworking.org/#%E2%98%84", iri2uri(u"http://bitworking.org/#\N{COMET}")) self.assertEqual("#%E2%98%84", iri2uri(u"#\N{COMET}")) self.assertEqual("/fred?bar=%E2%98%9A#%E2%98%84", iri2uri(u"/fred?bar=\N{BLACK LEFT POINTING INDEX}#\N{COMET}")) self.assertEqual("/fred?bar=%E2%98%9A#%E2%98%84", iri2uri(iri2uri(u"/fred?bar=\N{BLACK LEFT POINTING INDEX}#\N{COMET}"))) self.assertNotEqual("/fred?bar=%E2%98%9A#%E2%98%84", iri2uri(u"/fred?bar=\N{BLACK LEFT POINTING INDEX}#\N{COMET}".encode('utf-8'))) unittest.main()
Python
from __future__ import generators """ httplib2 A caching http interface that supports ETags and gzip to conserve bandwidth. Requires Python 2.3 or later Changelog: 2007-08-18, Rick: Modified so it's able to use a socks proxy if needed. """ __author__ = "Joe Gregorio (joe@bitworking.org)" __copyright__ = "Copyright 2006, Joe Gregorio" __contributors__ = ["Thomas Broyer (t.broyer@ltgt.net)", "James Antill", "Xavier Verges Farrero", "Jonathan Feinberg", "Blair Zajac", "Sam Ruby", "Louis Nyffenegger"] __license__ = "MIT" __version__ = "0.7.2" import re import sys import email import email.Utils import email.Message import email.FeedParser import StringIO import gzip import zlib import httplib import urlparse import base64 import os import copy import calendar import time import random import errno # remove depracated warning in python2.6 try: from hashlib import sha1 as _sha, md5 as _md5 except ImportError: import sha import md5 _sha = sha.new _md5 = md5.new import hmac from gettext import gettext as _ import socket try: from httplib2 import socks except ImportError: socks = None # Build the appropriate socket wrapper for ssl try: import ssl # python 2.6 ssl_SSLError = ssl.SSLError def _ssl_wrap_socket(sock, key_file, cert_file, disable_validation, ca_certs): if disable_validation: cert_reqs = ssl.CERT_NONE else: cert_reqs = ssl.CERT_REQUIRED # We should be specifying SSL version 3 or TLS v1, but the ssl module # doesn't expose the necessary knobs. So we need to go with the default # of SSLv23. return ssl.wrap_socket(sock, keyfile=key_file, certfile=cert_file, cert_reqs=cert_reqs, ca_certs=ca_certs) except (AttributeError, ImportError): ssl_SSLError = None def _ssl_wrap_socket(sock, key_file, cert_file, disable_validation, ca_certs): if not disable_validation: raise CertificateValidationUnsupported( "SSL certificate validation is not supported without " "the ssl module installed. To avoid this error, install " "the ssl module, or explicity disable validation.") ssl_sock = socket.ssl(sock, key_file, cert_file) return httplib.FakeSocket(sock, ssl_sock) if sys.version_info >= (2,3): from iri2uri import iri2uri else: def iri2uri(uri): return uri def has_timeout(timeout): # python 2.6 if hasattr(socket, '_GLOBAL_DEFAULT_TIMEOUT'): return (timeout is not None and timeout is not socket._GLOBAL_DEFAULT_TIMEOUT) return (timeout is not None) __all__ = ['Http', 'Response', 'ProxyInfo', 'HttpLib2Error', 'RedirectMissingLocation', 'RedirectLimit', 'FailedToDecompressContent', 'UnimplementedDigestAuthOptionError', 'UnimplementedHmacDigestAuthOptionError', 'debuglevel', 'ProxiesUnavailableError'] # The httplib debug level, set to a non-zero value to get debug output debuglevel = 0 # Python 2.3 support if sys.version_info < (2,4): def sorted(seq): seq.sort() return seq # Python 2.3 support def HTTPResponse__getheaders(self): """Return list of (header, value) tuples.""" if self.msg is None: raise httplib.ResponseNotReady() return self.msg.items() if not hasattr(httplib.HTTPResponse, 'getheaders'): httplib.HTTPResponse.getheaders = HTTPResponse__getheaders # All exceptions raised here derive from HttpLib2Error class HttpLib2Error(Exception): pass # Some exceptions can be caught and optionally # be turned back into responses. class HttpLib2ErrorWithResponse(HttpLib2Error): def __init__(self, desc, response, content): self.response = response self.content = content HttpLib2Error.__init__(self, desc) class RedirectMissingLocation(HttpLib2ErrorWithResponse): pass class RedirectLimit(HttpLib2ErrorWithResponse): pass class FailedToDecompressContent(HttpLib2ErrorWithResponse): pass class UnimplementedDigestAuthOptionError(HttpLib2ErrorWithResponse): pass class UnimplementedHmacDigestAuthOptionError(HttpLib2ErrorWithResponse): pass class MalformedHeader(HttpLib2Error): pass class RelativeURIError(HttpLib2Error): pass class ServerNotFoundError(HttpLib2Error): pass class ProxiesUnavailableError(HttpLib2Error): pass class CertificateValidationUnsupported(HttpLib2Error): pass class SSLHandshakeError(HttpLib2Error): pass class NotSupportedOnThisPlatform(HttpLib2Error): pass class CertificateHostnameMismatch(SSLHandshakeError): def __init__(self, desc, host, cert): HttpLib2Error.__init__(self, desc) self.host = host self.cert = cert # Open Items: # ----------- # Proxy support # Are we removing the cached content too soon on PUT (only delete on 200 Maybe?) # Pluggable cache storage (supports storing the cache in # flat files by default. We need a plug-in architecture # that can support Berkeley DB and Squid) # == Known Issues == # Does not handle a resource that uses conneg and Last-Modified but no ETag as a cache validator. # Does not handle Cache-Control: max-stale # Does not use Age: headers when calculating cache freshness. # The number of redirections to follow before giving up. # Note that only GET redirects are automatically followed. # Will also honor 301 requests by saving that info and never # requesting that URI again. DEFAULT_MAX_REDIRECTS = 5 # Default CA certificates file bundled with httplib2. CA_CERTS = os.path.join( os.path.dirname(os.path.abspath(__file__ )), "cacerts.txt") # Which headers are hop-by-hop headers by default HOP_BY_HOP = ['connection', 'keep-alive', 'proxy-authenticate', 'proxy-authorization', 'te', 'trailers', 'transfer-encoding', 'upgrade'] def _get_end2end_headers(response): hopbyhop = list(HOP_BY_HOP) hopbyhop.extend([x.strip() for x in response.get('connection', '').split(',')]) return [header for header in response.keys() if header not in hopbyhop] URI = re.compile(r"^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?") def parse_uri(uri): """Parses a URI using the regex given in Appendix B of RFC 3986. (scheme, authority, path, query, fragment) = parse_uri(uri) """ groups = URI.match(uri).groups() return (groups[1], groups[3], groups[4], groups[6], groups[8]) def urlnorm(uri): (scheme, authority, path, query, fragment) = parse_uri(uri) if not scheme or not authority: raise RelativeURIError("Only absolute URIs are allowed. uri = %s" % uri) authority = authority.lower() scheme = scheme.lower() if not path: path = "/" # Could do syntax based normalization of the URI before # computing the digest. See Section 6.2.2 of Std 66. request_uri = query and "?".join([path, query]) or path scheme = scheme.lower() defrag_uri = scheme + "://" + authority + request_uri return scheme, authority, request_uri, defrag_uri # Cache filename construction (original borrowed from Venus http://intertwingly.net/code/venus/) re_url_scheme = re.compile(r'^\w+://') re_slash = re.compile(r'[?/:|]+') def safename(filename): """Return a filename suitable for the cache. Strips dangerous and common characters to create a filename we can use to store the cache in. """ try: if re_url_scheme.match(filename): if isinstance(filename,str): filename = filename.decode('utf-8') filename = filename.encode('idna') else: filename = filename.encode('idna') except UnicodeError: pass if isinstance(filename,unicode): filename=filename.encode('utf-8') filemd5 = _md5(filename).hexdigest() filename = re_url_scheme.sub("", filename) filename = re_slash.sub(",", filename) # limit length of filename if len(filename)>200: filename=filename[:200] return ",".join((filename, filemd5)) NORMALIZE_SPACE = re.compile(r'(?:\r\n)?[ \t]+') def _normalize_headers(headers): return dict([ (key.lower(), NORMALIZE_SPACE.sub(value, ' ').strip()) for (key, value) in headers.iteritems()]) def _parse_cache_control(headers): retval = {} if headers.has_key('cache-control'): parts = headers['cache-control'].split(',') parts_with_args = [tuple([x.strip().lower() for x in part.split("=", 1)]) for part in parts if -1 != part.find("=")] parts_wo_args = [(name.strip().lower(), 1) for name in parts if -1 == name.find("=")] retval = dict(parts_with_args + parts_wo_args) return retval # Whether to use a strict mode to parse WWW-Authenticate headers # Might lead to bad results in case of ill-formed header value, # so disabled by default, falling back to relaxed parsing. # Set to true to turn on, usefull for testing servers. USE_WWW_AUTH_STRICT_PARSING = 0 # In regex below: # [^\0-\x1f\x7f-\xff()<>@,;:\\\"/[\]?={} \t]+ matches a "token" as defined by HTTP # "(?:[^\0-\x08\x0A-\x1f\x7f-\xff\\\"]|\\[\0-\x7f])*?" matches a "quoted-string" as defined by HTTP, when LWS have already been replaced by a single space # Actually, as an auth-param value can be either a token or a quoted-string, they are combined in a single pattern which matches both: # \"?((?<=\")(?:[^\0-\x1f\x7f-\xff\\\"]|\\[\0-\x7f])*?(?=\")|(?<!\")[^\0-\x08\x0A-\x1f\x7f-\xff()<>@,;:\\\"/[\]?={} \t]+(?!\"))\"? WWW_AUTH_STRICT = re.compile(r"^(?:\s*(?:,\s*)?([^\0-\x1f\x7f-\xff()<>@,;:\\\"/[\]?={} \t]+)\s*=\s*\"?((?<=\")(?:[^\0-\x08\x0A-\x1f\x7f-\xff\\\"]|\\[\0-\x7f])*?(?=\")|(?<!\")[^\0-\x1f\x7f-\xff()<>@,;:\\\"/[\]?={} \t]+(?!\"))\"?)(.*)$") WWW_AUTH_RELAXED = re.compile(r"^(?:\s*(?:,\s*)?([^ \t\r\n=]+)\s*=\s*\"?((?<=\")(?:[^\\\"]|\\.)*?(?=\")|(?<!\")[^ \t\r\n,]+(?!\"))\"?)(.*)$") UNQUOTE_PAIRS = re.compile(r'\\(.)') def _parse_www_authenticate(headers, headername='www-authenticate'): """Returns a dictionary of dictionaries, one dict per auth_scheme.""" retval = {} if headers.has_key(headername): try: authenticate = headers[headername].strip() www_auth = USE_WWW_AUTH_STRICT_PARSING and WWW_AUTH_STRICT or WWW_AUTH_RELAXED while authenticate: # Break off the scheme at the beginning of the line if headername == 'authentication-info': (auth_scheme, the_rest) = ('digest', authenticate) else: (auth_scheme, the_rest) = authenticate.split(" ", 1) # Now loop over all the key value pairs that come after the scheme, # being careful not to roll into the next scheme match = www_auth.search(the_rest) auth_params = {} while match: if match and len(match.groups()) == 3: (key, value, the_rest) = match.groups() auth_params[key.lower()] = UNQUOTE_PAIRS.sub(r'\1', value) # '\\'.join([x.replace('\\', '') for x in value.split('\\\\')]) match = www_auth.search(the_rest) retval[auth_scheme.lower()] = auth_params authenticate = the_rest.strip() except ValueError: raise MalformedHeader("WWW-Authenticate") return retval def _entry_disposition(response_headers, request_headers): """Determine freshness from the Date, Expires and Cache-Control headers. We don't handle the following: 1. Cache-Control: max-stale 2. Age: headers are not used in the calculations. Not that this algorithm is simpler than you might think because we are operating as a private (non-shared) cache. This lets us ignore 's-maxage'. We can also ignore 'proxy-invalidate' since we aren't a proxy. We will never return a stale document as fresh as a design decision, and thus the non-implementation of 'max-stale'. This also lets us safely ignore 'must-revalidate' since we operate as if every server has sent 'must-revalidate'. Since we are private we get to ignore both 'public' and 'private' parameters. We also ignore 'no-transform' since we don't do any transformations. The 'no-store' parameter is handled at a higher level. So the only Cache-Control parameters we look at are: no-cache only-if-cached max-age min-fresh """ retval = "STALE" cc = _parse_cache_control(request_headers) cc_response = _parse_cache_control(response_headers) if request_headers.has_key('pragma') and request_headers['pragma'].lower().find('no-cache') != -1: retval = "TRANSPARENT" if 'cache-control' not in request_headers: request_headers['cache-control'] = 'no-cache' elif cc.has_key('no-cache'): retval = "TRANSPARENT" elif cc_response.has_key('no-cache'): retval = "STALE" elif cc.has_key('only-if-cached'): retval = "FRESH" elif response_headers.has_key('date'): date = calendar.timegm(email.Utils.parsedate_tz(response_headers['date'])) now = time.time() current_age = max(0, now - date) if cc_response.has_key('max-age'): try: freshness_lifetime = int(cc_response['max-age']) except ValueError: freshness_lifetime = 0 elif response_headers.has_key('expires'): expires = email.Utils.parsedate_tz(response_headers['expires']) if None == expires: freshness_lifetime = 0 else: freshness_lifetime = max(0, calendar.timegm(expires) - date) else: freshness_lifetime = 0 if cc.has_key('max-age'): try: freshness_lifetime = int(cc['max-age']) except ValueError: freshness_lifetime = 0 if cc.has_key('min-fresh'): try: min_fresh = int(cc['min-fresh']) except ValueError: min_fresh = 0 current_age += min_fresh if freshness_lifetime > current_age: retval = "FRESH" return retval def _decompressContent(response, new_content): content = new_content try: encoding = response.get('content-encoding', None) if encoding in ['gzip', 'deflate']: if encoding == 'gzip': content = gzip.GzipFile(fileobj=StringIO.StringIO(new_content)).read() if encoding == 'deflate': content = zlib.decompress(content) response['content-length'] = str(len(content)) # Record the historical presence of the encoding in a way the won't interfere. response['-content-encoding'] = response['content-encoding'] del response['content-encoding'] except IOError: content = "" raise FailedToDecompressContent(_("Content purported to be compressed with %s but failed to decompress.") % response.get('content-encoding'), response, content) return content def _updateCache(request_headers, response_headers, content, cache, cachekey): if cachekey: cc = _parse_cache_control(request_headers) cc_response = _parse_cache_control(response_headers) if cc.has_key('no-store') or cc_response.has_key('no-store'): cache.delete(cachekey) else: info = email.Message.Message() for key, value in response_headers.iteritems(): if key not in ['status','content-encoding','transfer-encoding']: info[key] = value # Add annotations to the cache to indicate what headers # are variant for this request. vary = response_headers.get('vary', None) if vary: vary_headers = vary.lower().replace(' ', '').split(',') for header in vary_headers: key = '-varied-%s' % header try: info[key] = request_headers[header] except KeyError: pass status = response_headers.status if status == 304: status = 200 status_header = 'status: %d\r\n' % status header_str = info.as_string() header_str = re.sub("\r(?!\n)|(?<!\r)\n", "\r\n", header_str) text = "".join([status_header, header_str, content]) cache.set(cachekey, text) def _cnonce(): dig = _md5("%s:%s" % (time.ctime(), ["0123456789"[random.randrange(0, 9)] for i in range(20)])).hexdigest() return dig[:16] def _wsse_username_token(cnonce, iso_now, password): return base64.b64encode(_sha("%s%s%s" % (cnonce, iso_now, password)).digest()).strip() # For credentials we need two things, first # a pool of credential to try (not necesarily tied to BAsic, Digest, etc.) # Then we also need a list of URIs that have already demanded authentication # That list is tricky since sub-URIs can take the same auth, or the # auth scheme may change as you descend the tree. # So we also need each Auth instance to be able to tell us # how close to the 'top' it is. class Authentication(object): def __init__(self, credentials, host, request_uri, headers, response, content, http): (scheme, authority, path, query, fragment) = parse_uri(request_uri) self.path = path self.host = host self.credentials = credentials self.http = http def depth(self, request_uri): (scheme, authority, path, query, fragment) = parse_uri(request_uri) return request_uri[len(self.path):].count("/") def inscope(self, host, request_uri): # XXX Should we normalize the request_uri? (scheme, authority, path, query, fragment) = parse_uri(request_uri) return (host == self.host) and path.startswith(self.path) def request(self, method, request_uri, headers, content): """Modify the request headers to add the appropriate Authorization header. Over-rise this in sub-classes.""" pass def response(self, response, content): """Gives us a chance to update with new nonces or such returned from the last authorized response. Over-rise this in sub-classes if necessary. Return TRUE is the request is to be retried, for example Digest may return stale=true. """ return False class BasicAuthentication(Authentication): def __init__(self, credentials, host, request_uri, headers, response, content, http): Authentication.__init__(self, credentials, host, request_uri, headers, response, content, http) def request(self, method, request_uri, headers, content): """Modify the request headers to add the appropriate Authorization header.""" headers['authorization'] = 'Basic ' + base64.b64encode("%s:%s" % self.credentials).strip() class DigestAuthentication(Authentication): """Only do qop='auth' and MD5, since that is all Apache currently implements""" def __init__(self, credentials, host, request_uri, headers, response, content, http): Authentication.__init__(self, credentials, host, request_uri, headers, response, content, http) challenge = _parse_www_authenticate(response, 'www-authenticate') self.challenge = challenge['digest'] qop = self.challenge.get('qop', 'auth') self.challenge['qop'] = ('auth' in [x.strip() for x in qop.split()]) and 'auth' or None if self.challenge['qop'] is None: raise UnimplementedDigestAuthOptionError( _("Unsupported value for qop: %s." % qop)) self.challenge['algorithm'] = self.challenge.get('algorithm', 'MD5').upper() if self.challenge['algorithm'] != 'MD5': raise UnimplementedDigestAuthOptionError( _("Unsupported value for algorithm: %s." % self.challenge['algorithm'])) self.A1 = "".join([self.credentials[0], ":", self.challenge['realm'], ":", self.credentials[1]]) self.challenge['nc'] = 1 def request(self, method, request_uri, headers, content, cnonce = None): """Modify the request headers""" H = lambda x: _md5(x).hexdigest() KD = lambda s, d: H("%s:%s" % (s, d)) A2 = "".join([method, ":", request_uri]) self.challenge['cnonce'] = cnonce or _cnonce() request_digest = '"%s"' % KD(H(self.A1), "%s:%s:%s:%s:%s" % (self.challenge['nonce'], '%08x' % self.challenge['nc'], self.challenge['cnonce'], self.challenge['qop'], H(A2) )) headers['authorization'] = 'Digest username="%s", realm="%s", nonce="%s", uri="%s", algorithm=%s, response=%s, qop=%s, nc=%08x, cnonce="%s"' % ( self.credentials[0], self.challenge['realm'], self.challenge['nonce'], request_uri, self.challenge['algorithm'], request_digest, self.challenge['qop'], self.challenge['nc'], self.challenge['cnonce'], ) if self.challenge.get('opaque'): headers['authorization'] += ', opaque="%s"' % self.challenge['opaque'] self.challenge['nc'] += 1 def response(self, response, content): if not response.has_key('authentication-info'): challenge = _parse_www_authenticate(response, 'www-authenticate').get('digest', {}) if 'true' == challenge.get('stale'): self.challenge['nonce'] = challenge['nonce'] self.challenge['nc'] = 1 return True else: updated_challenge = _parse_www_authenticate(response, 'authentication-info').get('digest', {}) if updated_challenge.has_key('nextnonce'): self.challenge['nonce'] = updated_challenge['nextnonce'] self.challenge['nc'] = 1 return False class HmacDigestAuthentication(Authentication): """Adapted from Robert Sayre's code and DigestAuthentication above.""" __author__ = "Thomas Broyer (t.broyer@ltgt.net)" def __init__(self, credentials, host, request_uri, headers, response, content, http): Authentication.__init__(self, credentials, host, request_uri, headers, response, content, http) challenge = _parse_www_authenticate(response, 'www-authenticate') self.challenge = challenge['hmacdigest'] # TODO: self.challenge['domain'] self.challenge['reason'] = self.challenge.get('reason', 'unauthorized') if self.challenge['reason'] not in ['unauthorized', 'integrity']: self.challenge['reason'] = 'unauthorized' self.challenge['salt'] = self.challenge.get('salt', '') if not self.challenge.get('snonce'): raise UnimplementedHmacDigestAuthOptionError( _("The challenge doesn't contain a server nonce, or this one is empty.")) self.challenge['algorithm'] = self.challenge.get('algorithm', 'HMAC-SHA-1') if self.challenge['algorithm'] not in ['HMAC-SHA-1', 'HMAC-MD5']: raise UnimplementedHmacDigestAuthOptionError( _("Unsupported value for algorithm: %s." % self.challenge['algorithm'])) self.challenge['pw-algorithm'] = self.challenge.get('pw-algorithm', 'SHA-1') if self.challenge['pw-algorithm'] not in ['SHA-1', 'MD5']: raise UnimplementedHmacDigestAuthOptionError( _("Unsupported value for pw-algorithm: %s." % self.challenge['pw-algorithm'])) if self.challenge['algorithm'] == 'HMAC-MD5': self.hashmod = _md5 else: self.hashmod = _sha if self.challenge['pw-algorithm'] == 'MD5': self.pwhashmod = _md5 else: self.pwhashmod = _sha self.key = "".join([self.credentials[0], ":", self.pwhashmod.new("".join([self.credentials[1], self.challenge['salt']])).hexdigest().lower(), ":", self.challenge['realm'] ]) self.key = self.pwhashmod.new(self.key).hexdigest().lower() def request(self, method, request_uri, headers, content): """Modify the request headers""" keys = _get_end2end_headers(headers) keylist = "".join(["%s " % k for k in keys]) headers_val = "".join([headers[k] for k in keys]) created = time.strftime('%Y-%m-%dT%H:%M:%SZ',time.gmtime()) cnonce = _cnonce() request_digest = "%s:%s:%s:%s:%s" % (method, request_uri, cnonce, self.challenge['snonce'], headers_val) request_digest = hmac.new(self.key, request_digest, self.hashmod).hexdigest().lower() headers['authorization'] = 'HMACDigest username="%s", realm="%s", snonce="%s", cnonce="%s", uri="%s", created="%s", response="%s", headers="%s"' % ( self.credentials[0], self.challenge['realm'], self.challenge['snonce'], cnonce, request_uri, created, request_digest, keylist, ) def response(self, response, content): challenge = _parse_www_authenticate(response, 'www-authenticate').get('hmacdigest', {}) if challenge.get('reason') in ['integrity', 'stale']: return True return False class WsseAuthentication(Authentication): """This is thinly tested and should not be relied upon. At this time there isn't any third party server to test against. Blogger and TypePad implemented this algorithm at one point but Blogger has since switched to Basic over HTTPS and TypePad has implemented it wrong, by never issuing a 401 challenge but instead requiring your client to telepathically know that their endpoint is expecting WSSE profile="UsernameToken".""" def __init__(self, credentials, host, request_uri, headers, response, content, http): Authentication.__init__(self, credentials, host, request_uri, headers, response, content, http) def request(self, method, request_uri, headers, content): """Modify the request headers to add the appropriate Authorization header.""" headers['authorization'] = 'WSSE profile="UsernameToken"' iso_now = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()) cnonce = _cnonce() password_digest = _wsse_username_token(cnonce, iso_now, self.credentials[1]) headers['X-WSSE'] = 'UsernameToken Username="%s", PasswordDigest="%s", Nonce="%s", Created="%s"' % ( self.credentials[0], password_digest, cnonce, iso_now) class GoogleLoginAuthentication(Authentication): def __init__(self, credentials, host, request_uri, headers, response, content, http): from urllib import urlencode Authentication.__init__(self, credentials, host, request_uri, headers, response, content, http) challenge = _parse_www_authenticate(response, 'www-authenticate') service = challenge['googlelogin'].get('service', 'xapi') # Bloggger actually returns the service in the challenge # For the rest we guess based on the URI if service == 'xapi' and request_uri.find("calendar") > 0: service = "cl" # No point in guessing Base or Spreadsheet #elif request_uri.find("spreadsheets") > 0: # service = "wise" auth = dict(Email=credentials[0], Passwd=credentials[1], service=service, source=headers['user-agent']) resp, content = self.http.request("https://www.google.com/accounts/ClientLogin", method="POST", body=urlencode(auth), headers={'Content-Type': 'application/x-www-form-urlencoded'}) lines = content.split('\n') d = dict([tuple(line.split("=", 1)) for line in lines if line]) if resp.status == 403: self.Auth = "" else: self.Auth = d['Auth'] def request(self, method, request_uri, headers, content): """Modify the request headers to add the appropriate Authorization header.""" headers['authorization'] = 'GoogleLogin Auth=' + self.Auth AUTH_SCHEME_CLASSES = { "basic": BasicAuthentication, "wsse": WsseAuthentication, "digest": DigestAuthentication, "hmacdigest": HmacDigestAuthentication, "googlelogin": GoogleLoginAuthentication } AUTH_SCHEME_ORDER = ["hmacdigest", "googlelogin", "digest", "wsse", "basic"] class FileCache(object): """Uses a local directory as a store for cached files. Not really safe to use if multiple threads or processes are going to be running on the same cache. """ def __init__(self, cache, safe=safename): # use safe=lambda x: md5.new(x).hexdigest() for the old behavior self.cache = cache self.safe = safe if not os.path.exists(cache): os.makedirs(self.cache) def get(self, key): retval = None cacheFullPath = os.path.join(self.cache, self.safe(key)) try: f = file(cacheFullPath, "rb") retval = f.read() f.close() except IOError: pass return retval def set(self, key, value): cacheFullPath = os.path.join(self.cache, self.safe(key)) f = file(cacheFullPath, "wb") f.write(value) f.close() def delete(self, key): cacheFullPath = os.path.join(self.cache, self.safe(key)) if os.path.exists(cacheFullPath): os.remove(cacheFullPath) class Credentials(object): def __init__(self): self.credentials = [] def add(self, name, password, domain=""): self.credentials.append((domain.lower(), name, password)) def clear(self): self.credentials = [] def iter(self, domain): for (cdomain, name, password) in self.credentials: if cdomain == "" or domain == cdomain: yield (name, password) class KeyCerts(Credentials): """Identical to Credentials except that name/password are mapped to key/cert.""" pass class ProxyInfo(object): """Collect information required to use a proxy.""" def __init__(self, proxy_type, proxy_host, proxy_port, proxy_rdns=None, proxy_user=None, proxy_pass=None): """The parameter proxy_type must be set to one of socks.PROXY_TYPE_XXX constants. For example: p = ProxyInfo(proxy_type=socks.PROXY_TYPE_HTTP, proxy_host='localhost', proxy_port=8000) """ self.proxy_type, self.proxy_host, self.proxy_port, self.proxy_rdns, self.proxy_user, self.proxy_pass = proxy_type, proxy_host, proxy_port, proxy_rdns, proxy_user, proxy_pass def astuple(self): return (self.proxy_type, self.proxy_host, self.proxy_port, self.proxy_rdns, self.proxy_user, self.proxy_pass) def isgood(self): return (self.proxy_host != None) and (self.proxy_port != None) class HTTPConnectionWithTimeout(httplib.HTTPConnection): """ HTTPConnection subclass that supports timeouts All timeouts are in seconds. If None is passed for timeout then Python's default timeout for sockets will be used. See for example the docs of socket.setdefaulttimeout(): http://docs.python.org/library/socket.html#socket.setdefaulttimeout """ def __init__(self, host, port=None, strict=None, timeout=None, proxy_info=None): httplib.HTTPConnection.__init__(self, host, port, strict) self.timeout = timeout self.proxy_info = proxy_info def connect(self): """Connect to the host and port specified in __init__.""" # Mostly verbatim from httplib.py. if self.proxy_info and socks is None: raise ProxiesUnavailableError( 'Proxy support missing but proxy use was requested!') msg = "getaddrinfo returns an empty list" for res in socket.getaddrinfo(self.host, self.port, 0, socket.SOCK_STREAM): af, socktype, proto, canonname, sa = res try: if self.proxy_info and self.proxy_info.isgood(): self.sock = socks.socksocket(af, socktype, proto) self.sock.setproxy(*self.proxy_info.astuple()) else: self.sock = socket.socket(af, socktype, proto) self.sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) # Different from httplib: support timeouts. if has_timeout(self.timeout): self.sock.settimeout(self.timeout) # End of difference from httplib. if self.debuglevel > 0: print "connect: (%s, %s)" % (self.host, self.port) self.sock.connect(sa) except socket.error, msg: if self.debuglevel > 0: print 'connect fail:', (self.host, self.port) if self.sock: self.sock.close() self.sock = None continue break if not self.sock: raise socket.error, msg class HTTPSConnectionWithTimeout(httplib.HTTPSConnection): """ This class allows communication via SSL. All timeouts are in seconds. If None is passed for timeout then Python's default timeout for sockets will be used. See for example the docs of socket.setdefaulttimeout(): http://docs.python.org/library/socket.html#socket.setdefaulttimeout """ def __init__(self, host, port=None, key_file=None, cert_file=None, strict=None, timeout=None, proxy_info=None, ca_certs=None, disable_ssl_certificate_validation=False): httplib.HTTPSConnection.__init__(self, host, port=port, key_file=key_file, cert_file=cert_file, strict=strict) self.timeout = timeout self.proxy_info = proxy_info if ca_certs is None: ca_certs = CA_CERTS self.ca_certs = ca_certs self.disable_ssl_certificate_validation = \ disable_ssl_certificate_validation # The following two methods were adapted from https_wrapper.py, released # with the Google Appengine SDK at # http://googleappengine.googlecode.com/svn-history/r136/trunk/python/google/appengine/tools/https_wrapper.py # under the following license: # # Copyright 2007 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # def _GetValidHostsForCert(self, cert): """Returns a list of valid host globs for an SSL certificate. Args: cert: A dictionary representing an SSL certificate. Returns: list: A list of valid host globs. """ if 'subjectAltName' in cert: return [x[1] for x in cert['subjectAltName'] if x[0].lower() == 'dns'] else: return [x[0][1] for x in cert['subject'] if x[0][0].lower() == 'commonname'] def _ValidateCertificateHostname(self, cert, hostname): """Validates that a given hostname is valid for an SSL certificate. Args: cert: A dictionary representing an SSL certificate. hostname: The hostname to test. Returns: bool: Whether or not the hostname is valid for this certificate. """ hosts = self._GetValidHostsForCert(cert) for host in hosts: host_re = host.replace('.', '\.').replace('*', '[^.]*') if re.search('^%s$' % (host_re,), hostname, re.I): return True return False def connect(self): "Connect to a host on a given (SSL) port." msg = "getaddrinfo returns an empty list" for family, socktype, proto, canonname, sockaddr in socket.getaddrinfo( self.host, self.port, 0, socket.SOCK_STREAM): try: if self.proxy_info and self.proxy_info.isgood(): sock = socks.socksocket(family, socktype, proto) sock.setproxy(*self.proxy_info.astuple()) else: sock = socket.socket(family, socktype, proto) sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) if has_timeout(self.timeout): sock.settimeout(self.timeout) sock.connect((self.host, self.port)) self.sock =_ssl_wrap_socket( sock, self.key_file, self.cert_file, self.disable_ssl_certificate_validation, self.ca_certs) if self.debuglevel > 0: print "connect: (%s, %s)" % (self.host, self.port) if not self.disable_ssl_certificate_validation: cert = self.sock.getpeercert() hostname = self.host.split(':', 0)[0] if not self._ValidateCertificateHostname(cert, hostname): raise CertificateHostnameMismatch( 'Server presented certificate that does not match ' 'host %s: %s' % (hostname, cert), hostname, cert) except ssl_SSLError, e: if sock: sock.close() if self.sock: self.sock.close() self.sock = None # Unfortunately the ssl module doesn't seem to provide any way # to get at more detailed error information, in particular # whether the error is due to certificate validation or # something else (such as SSL protocol mismatch). if e.errno == ssl.SSL_ERROR_SSL: raise SSLHandshakeError(e) else: raise except (socket.timeout, socket.gaierror): raise except socket.error, msg: if self.debuglevel > 0: print 'connect fail:', (self.host, self.port) if self.sock: self.sock.close() self.sock = None continue break if not self.sock: raise socket.error, msg SCHEME_TO_CONNECTION = { 'http': HTTPConnectionWithTimeout, 'https': HTTPSConnectionWithTimeout } # Use a different connection object for Google App Engine try: from google.appengine.api import apiproxy_stub_map if apiproxy_stub_map.apiproxy.GetStub('urlfetch') is None: raise ImportError # Bail out; we're not actually running on App Engine. from google.appengine.api.urlfetch import fetch from google.appengine.api.urlfetch import InvalidURLError from google.appengine.api.urlfetch import DownloadError from google.appengine.api.urlfetch import ResponseTooLargeError from google.appengine.api.urlfetch import SSLCertificateError class ResponseDict(dict): """Is a dictionary that also has a read() method, so that it can pass itself off as an httlib.HTTPResponse().""" def read(self): pass class AppEngineHttpConnection(object): """Emulates an httplib.HTTPConnection object, but actually uses the Google App Engine urlfetch library. This allows the timeout to be properly used on Google App Engine, and avoids using httplib, which on Google App Engine is just another wrapper around urlfetch. """ def __init__(self, host, port=None, key_file=None, cert_file=None, strict=None, timeout=None, proxy_info=None, ca_certs=None, disable_certificate_validation=False): self.host = host self.port = port self.timeout = timeout if key_file or cert_file or proxy_info or ca_certs: raise NotSupportedOnThisPlatform() self.response = None self.scheme = 'http' self.validate_certificate = not disable_certificate_validation self.sock = True def request(self, method, url, body, headers): # Calculate the absolute URI, which fetch requires netloc = self.host if self.port: netloc = '%s:%s' % (self.host, self.port) absolute_uri = '%s://%s%s' % (self.scheme, netloc, url) try: response = fetch(absolute_uri, payload=body, method=method, headers=headers, allow_truncated=False, follow_redirects=False, deadline=self.timeout, validate_certificate=self.validate_certificate) self.response = ResponseDict(response.headers) self.response['status'] = str(response.status_code) self.response.status = response.status_code setattr(self.response, 'read', lambda : response.content) # Make sure the exceptions raised match the exceptions expected. except InvalidURLError: raise socket.gaierror('') except (DownloadError, ResponseTooLargeError, SSLCertificateError): raise httplib.HTTPException() def getresponse(self): if self.response: return self.response else: raise httplib.HTTPException() def set_debuglevel(self, level): pass def connect(self): pass def close(self): pass class AppEngineHttpsConnection(AppEngineHttpConnection): """Same as AppEngineHttpConnection, but for HTTPS URIs.""" def __init__(self, host, port=None, key_file=None, cert_file=None, strict=None, timeout=None, proxy_info=None): AppEngineHttpConnection.__init__(self, host, port, key_file, cert_file, strict, timeout, proxy_info) self.scheme = 'https' # Update the connection classes to use the Googel App Engine specific ones. SCHEME_TO_CONNECTION = { 'http': AppEngineHttpConnection, 'https': AppEngineHttpsConnection } except ImportError: pass class Http(object): """An HTTP client that handles: - all methods - caching - ETags - compression, - HTTPS - Basic - Digest - WSSE and more. """ def __init__(self, cache=None, timeout=None, proxy_info=None, ca_certs=None, disable_ssl_certificate_validation=False): """ The value of proxy_info is a ProxyInfo instance. If 'cache' is a string then it is used as a directory name for a disk cache. Otherwise it must be an object that supports the same interface as FileCache. All timeouts are in seconds. If None is passed for timeout then Python's default timeout for sockets will be used. See for example the docs of socket.setdefaulttimeout(): http://docs.python.org/library/socket.html#socket.setdefaulttimeout ca_certs is the path of a file containing root CA certificates for SSL server certificate validation. By default, a CA cert file bundled with httplib2 is used. If disable_ssl_certificate_validation is true, SSL cert validation will not be performed. """ self.proxy_info = proxy_info self.ca_certs = ca_certs self.disable_ssl_certificate_validation = \ disable_ssl_certificate_validation # Map domain name to an httplib connection self.connections = {} # The location of the cache, for now a directory # where cached responses are held. if cache and isinstance(cache, basestring): self.cache = FileCache(cache) else: self.cache = cache # Name/password self.credentials = Credentials() # Key/cert self.certificates = KeyCerts() # authorization objects self.authorizations = [] # If set to False then no redirects are followed, even safe ones. self.follow_redirects = True # Which HTTP methods do we apply optimistic concurrency to, i.e. # which methods get an "if-match:" etag header added to them. self.optimistic_concurrency_methods = ["PUT", "PATCH"] # If 'follow_redirects' is True, and this is set to True then # all redirecs are followed, including unsafe ones. self.follow_all_redirects = False self.ignore_etag = False self.force_exception_to_status_code = False self.timeout = timeout def _auth_from_challenge(self, host, request_uri, headers, response, content): """A generator that creates Authorization objects that can be applied to requests. """ challenges = _parse_www_authenticate(response, 'www-authenticate') for cred in self.credentials.iter(host): for scheme in AUTH_SCHEME_ORDER: if challenges.has_key(scheme): yield AUTH_SCHEME_CLASSES[scheme](cred, host, request_uri, headers, response, content, self) def add_credentials(self, name, password, domain=""): """Add a name and password that will be used any time a request requires authentication.""" self.credentials.add(name, password, domain) def add_certificate(self, key, cert, domain): """Add a key and cert that will be used any time a request requires authentication.""" self.certificates.add(key, cert, domain) def clear_credentials(self): """Remove all the names and passwords that are used for authentication""" self.credentials.clear() self.authorizations = [] def _conn_request(self, conn, request_uri, method, body, headers): for i in range(2): try: if conn.sock is None: conn.connect() conn.request(method, request_uri, body, headers) except socket.timeout: raise except socket.gaierror: conn.close() raise ServerNotFoundError("Unable to find the server at %s" % conn.host) except ssl_SSLError: conn.close() raise except socket.error, e: err = 0 if hasattr(e, 'args'): err = getattr(e, 'args')[0] else: err = e.errno if err == errno.ECONNREFUSED: # Connection refused raise except httplib.HTTPException: # Just because the server closed the connection doesn't apparently mean # that the server didn't send a response. if conn.sock is None: if i == 0: conn.close() conn.connect() continue else: conn.close() raise if i == 0: conn.close() conn.connect() continue try: response = conn.getresponse() except (socket.error, httplib.HTTPException): if i == 0: conn.close() conn.connect() continue else: raise else: content = "" if method == "HEAD": response.close() else: content = response.read() response = Response(response) if method != "HEAD": content = _decompressContent(response, content) break return (response, content) def _request(self, conn, host, absolute_uri, request_uri, method, body, headers, redirections, cachekey): """Do the actual request using the connection object and also follow one level of redirects if necessary""" auths = [(auth.depth(request_uri), auth) for auth in self.authorizations if auth.inscope(host, request_uri)] auth = auths and sorted(auths)[0][1] or None if auth: auth.request(method, request_uri, headers, body) (response, content) = self._conn_request(conn, request_uri, method, body, headers) if auth: if auth.response(response, body): auth.request(method, request_uri, headers, body) (response, content) = self._conn_request(conn, request_uri, method, body, headers ) response._stale_digest = 1 if response.status == 401: for authorization in self._auth_from_challenge(host, request_uri, headers, response, content): authorization.request(method, request_uri, headers, body) (response, content) = self._conn_request(conn, request_uri, method, body, headers, ) if response.status != 401: self.authorizations.append(authorization) authorization.response(response, body) break if (self.follow_all_redirects or (method in ["GET", "HEAD"]) or response.status == 303): if self.follow_redirects and response.status in [300, 301, 302, 303, 307]: # Pick out the location header and basically start from the beginning # remembering first to strip the ETag header and decrement our 'depth' if redirections: if not response.has_key('location') and response.status != 300: raise RedirectMissingLocation( _("Redirected but the response is missing a Location: header."), response, content) # Fix-up relative redirects (which violate an RFC 2616 MUST) if response.has_key('location'): location = response['location'] (scheme, authority, path, query, fragment) = parse_uri(location) if authority == None: response['location'] = urlparse.urljoin(absolute_uri, location) if response.status == 301 and method in ["GET", "HEAD"]: response['-x-permanent-redirect-url'] = response['location'] if not response.has_key('content-location'): response['content-location'] = absolute_uri _updateCache(headers, response, content, self.cache, cachekey) if headers.has_key('if-none-match'): del headers['if-none-match'] if headers.has_key('if-modified-since'): del headers['if-modified-since'] if response.has_key('location'): location = response['location'] old_response = copy.deepcopy(response) if not old_response.has_key('content-location'): old_response['content-location'] = absolute_uri redirect_method = method if response.status in [302, 303]: redirect_method = "GET" body = None (response, content) = self.request(location, redirect_method, body=body, headers = headers, redirections = redirections - 1) response.previous = old_response else: raise RedirectLimit("Redirected more times than rediection_limit allows.", response, content) elif response.status in [200, 203] and method in ["GET", "HEAD"]: # Don't cache 206's since we aren't going to handle byte range requests if not response.has_key('content-location'): response['content-location'] = absolute_uri _updateCache(headers, response, content, self.cache, cachekey) return (response, content) def _normalize_headers(self, headers): return _normalize_headers(headers) # Need to catch and rebrand some exceptions # Then need to optionally turn all exceptions into status codes # including all socket.* and httplib.* exceptions. def request(self, uri, method="GET", body=None, headers=None, redirections=DEFAULT_MAX_REDIRECTS, connection_type=None): """ Performs a single HTTP request. The 'uri' is the URI of the HTTP resource and can begin with either 'http' or 'https'. The value of 'uri' must be an absolute URI. The 'method' is the HTTP method to perform, such as GET, POST, DELETE, etc. There is no restriction on the methods allowed. The 'body' is the entity body to be sent with the request. It is a string object. Any extra headers that are to be sent with the request should be provided in the 'headers' dictionary. The maximum number of redirect to follow before raising an exception is 'redirections. The default is 5. The return value is a tuple of (response, content), the first being and instance of the 'Response' class, the second being a string that contains the response entity body. """ try: if headers is None: headers = {} else: headers = self._normalize_headers(headers) if not headers.has_key('user-agent'): headers['user-agent'] = "Python-httplib2/%s (gzip)" % __version__ uri = iri2uri(uri) (scheme, authority, request_uri, defrag_uri) = urlnorm(uri) domain_port = authority.split(":")[0:2] if len(domain_port) == 2 and domain_port[1] == '443' and scheme == 'http': scheme = 'https' authority = domain_port[0] conn_key = scheme+":"+authority if conn_key in self.connections: conn = self.connections[conn_key] else: if not connection_type: connection_type = SCHEME_TO_CONNECTION[scheme] certs = list(self.certificates.iter(authority)) if issubclass(connection_type, HTTPSConnectionWithTimeout): if certs: conn = self.connections[conn_key] = connection_type( authority, key_file=certs[0][0], cert_file=certs[0][1], timeout=self.timeout, proxy_info=self.proxy_info, ca_certs=self.ca_certs, disable_ssl_certificate_validation= self.disable_ssl_certificate_validation) else: conn = self.connections[conn_key] = connection_type( authority, timeout=self.timeout, proxy_info=self.proxy_info, ca_certs=self.ca_certs, disable_ssl_certificate_validation= self.disable_ssl_certificate_validation) else: conn = self.connections[conn_key] = connection_type( authority, timeout=self.timeout, proxy_info=self.proxy_info) conn.set_debuglevel(debuglevel) if 'range' not in headers and 'accept-encoding' not in headers: headers['accept-encoding'] = 'gzip, deflate' info = email.Message.Message() cached_value = None if self.cache: cachekey = defrag_uri cached_value = self.cache.get(cachekey) if cached_value: # info = email.message_from_string(cached_value) # # Need to replace the line above with the kludge below # to fix the non-existent bug not fixed in this # bug report: http://mail.python.org/pipermail/python-bugs-list/2005-September/030289.html try: info, content = cached_value.split('\r\n\r\n', 1) feedparser = email.FeedParser.FeedParser() feedparser.feed(info) info = feedparser.close() feedparser._parse = None except IndexError: self.cache.delete(cachekey) cachekey = None cached_value = None else: cachekey = None if method in self.optimistic_concurrency_methods and self.cache and info.has_key('etag') and not self.ignore_etag and 'if-match' not in headers: # http://www.w3.org/1999/04/Editing/ headers['if-match'] = info['etag'] if method not in ["GET", "HEAD"] and self.cache and cachekey: # RFC 2616 Section 13.10 self.cache.delete(cachekey) # Check the vary header in the cache to see if this request # matches what varies in the cache. if method in ['GET', 'HEAD'] and 'vary' in info: vary = info['vary'] vary_headers = vary.lower().replace(' ', '').split(',') for header in vary_headers: key = '-varied-%s' % header value = info[key] if headers.get(header, None) != value: cached_value = None break if cached_value and method in ["GET", "HEAD"] and self.cache and 'range' not in headers: if info.has_key('-x-permanent-redirect-url'): # Should cached permanent redirects be counted in our redirection count? For now, yes. if redirections <= 0: raise RedirectLimit("Redirected more times than rediection_limit allows.", {}, "") (response, new_content) = self.request(info['-x-permanent-redirect-url'], "GET", headers = headers, redirections = redirections - 1) response.previous = Response(info) response.previous.fromcache = True else: # Determine our course of action: # Is the cached entry fresh or stale? # Has the client requested a non-cached response? # # There seems to be three possible answers: # 1. [FRESH] Return the cache entry w/o doing a GET # 2. [STALE] Do the GET (but add in cache validators if available) # 3. [TRANSPARENT] Do a GET w/o any cache validators (Cache-Control: no-cache) on the request entry_disposition = _entry_disposition(info, headers) if entry_disposition == "FRESH": if not cached_value: info['status'] = '504' content = "" response = Response(info) if cached_value: response.fromcache = True return (response, content) if entry_disposition == "STALE": if info.has_key('etag') and not self.ignore_etag and not 'if-none-match' in headers: headers['if-none-match'] = info['etag'] if info.has_key('last-modified') and not 'last-modified' in headers: headers['if-modified-since'] = info['last-modified'] elif entry_disposition == "TRANSPARENT": pass (response, new_content) = self._request(conn, authority, uri, request_uri, method, body, headers, redirections, cachekey) if response.status == 304 and method == "GET": # Rewrite the cache entry with the new end-to-end headers # Take all headers that are in response # and overwrite their values in info. # unless they are hop-by-hop, or are listed in the connection header. for key in _get_end2end_headers(response): info[key] = response[key] merged_response = Response(info) if hasattr(response, "_stale_digest"): merged_response._stale_digest = response._stale_digest _updateCache(headers, merged_response, content, self.cache, cachekey) response = merged_response response.status = 200 response.fromcache = True elif response.status == 200: content = new_content else: self.cache.delete(cachekey) content = new_content else: cc = _parse_cache_control(headers) if cc.has_key('only-if-cached'): info['status'] = '504' response = Response(info) content = "" else: (response, content) = self._request(conn, authority, uri, request_uri, method, body, headers, redirections, cachekey) except Exception, e: if self.force_exception_to_status_code: if isinstance(e, HttpLib2ErrorWithResponse): response = e.response content = e.content response.status = 500 response.reason = str(e) elif isinstance(e, socket.timeout): content = "Request Timeout" response = Response( { "content-type": "text/plain", "status": "408", "content-length": len(content) }) response.reason = "Request Timeout" else: content = str(e) response = Response( { "content-type": "text/plain", "status": "400", "content-length": len(content) }) response.reason = "Bad Request" else: raise return (response, content) class Response(dict): """An object more like email.Message than httplib.HTTPResponse.""" """Is this response from our local cache""" fromcache = False """HTTP protocol version used by server. 10 for HTTP/1.0, 11 for HTTP/1.1. """ version = 11 "Status code returned by server. " status = 200 """Reason phrase returned by server.""" reason = "Ok" previous = None def __init__(self, info): # info is either an email.Message or # an httplib.HTTPResponse object. if isinstance(info, httplib.HTTPResponse): for key, value in info.getheaders(): self[key.lower()] = value self.status = info.status self['status'] = str(self.status) self.reason = info.reason self.version = info.version elif isinstance(info, email.Message.Message): for key, value in info.items(): self[key] = value self.status = int(self['status']) else: for key, value in info.iteritems(): self[key] = value self.status = int(self.get('status', self.status)) def __getattr__(self, name): if name == 'dict': return self else: raise AttributeError, name
Python
"""SocksiPy - Python SOCKS module. Version 1.00 Copyright 2006 Dan-Haim. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of Dan Haim nor the names of his contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY DAN HAIM "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL DAN HAIM OR HIS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMANGE. This module provides a standard socket-like interface for Python for tunneling connections through SOCKS proxies. """ """ Minor modifications made by Christopher Gilbert (http://motomastyle.com/) for use in PyLoris (http://pyloris.sourceforge.net/) Minor modifications made by Mario Vilas (http://breakingcode.wordpress.com/) mainly to merge bug fixes found in Sourceforge """ import base64 import socket import struct import sys if getattr(socket, 'socket', None) is None: raise ImportError('socket.socket missing, proxy support unusable') PROXY_TYPE_SOCKS4 = 1 PROXY_TYPE_SOCKS5 = 2 PROXY_TYPE_HTTP = 3 PROXY_TYPE_HTTP_NO_TUNNEL = 4 _defaultproxy = None _orgsocket = socket.socket class ProxyError(Exception): pass class GeneralProxyError(ProxyError): pass class Socks5AuthError(ProxyError): pass class Socks5Error(ProxyError): pass class Socks4Error(ProxyError): pass class HTTPError(ProxyError): pass _generalerrors = ("success", "invalid data", "not connected", "not available", "bad proxy type", "bad input") _socks5errors = ("succeeded", "general SOCKS server failure", "connection not allowed by ruleset", "Network unreachable", "Host unreachable", "Connection refused", "TTL expired", "Command not supported", "Address type not supported", "Unknown error") _socks5autherrors = ("succeeded", "authentication is required", "all offered authentication methods were rejected", "unknown username or invalid password", "unknown error") _socks4errors = ("request granted", "request rejected or failed", "request rejected because SOCKS server cannot connect to identd on the client", "request rejected because the client program and identd report different user-ids", "unknown error") def setdefaultproxy(proxytype=None, addr=None, port=None, rdns=True, username=None, password=None): """setdefaultproxy(proxytype, addr[, port[, rdns[, username[, password]]]]) Sets a default proxy which all further socksocket objects will use, unless explicitly changed. """ global _defaultproxy _defaultproxy = (proxytype, addr, port, rdns, username, password) def wrapmodule(module): """wrapmodule(module) Attempts to replace a module's socket library with a SOCKS socket. Must set a default proxy using setdefaultproxy(...) first. This will only work on modules that import socket directly into the namespace; most of the Python Standard Library falls into this category. """ if _defaultproxy != None: module.socket.socket = socksocket else: raise GeneralProxyError((4, "no proxy specified")) class socksocket(socket.socket): """socksocket([family[, type[, proto]]]) -> socket object Open a SOCKS enabled socket. The parameters are the same as those of the standard socket init. In order for SOCKS to work, you must specify family=AF_INET, type=SOCK_STREAM and proto=0. """ def __init__(self, family=socket.AF_INET, type=socket.SOCK_STREAM, proto=0, _sock=None): _orgsocket.__init__(self, family, type, proto, _sock) if _defaultproxy != None: self.__proxy = _defaultproxy else: self.__proxy = (None, None, None, None, None, None) self.__proxysockname = None self.__proxypeername = None self.__httptunnel = True def __recvall(self, count): """__recvall(count) -> data Receive EXACTLY the number of bytes requested from the socket. Blocks until the required number of bytes have been received. """ data = self.recv(count) while len(data) < count: d = self.recv(count-len(data)) if not d: raise GeneralProxyError((0, "connection closed unexpectedly")) data = data + d return data def sendall(self, content, *args): """ override socket.socket.sendall method to rewrite the header for non-tunneling proxies if needed """ if not self.__httptunnel: content = self.__rewriteproxy(content) return super(socksocket, self).sendall(content, *args) def __rewriteproxy(self, header): """ rewrite HTTP request headers to support non-tunneling proxies (i.e. those which do not support the CONNECT method). This only works for HTTP (not HTTPS) since HTTPS requires tunneling. """ host, endpt = None, None hdrs = header.split("\r\n") for hdr in hdrs: if hdr.lower().startswith("host:"): host = hdr elif hdr.lower().startswith("get") or hdr.lower().startswith("post"): endpt = hdr if host and endpt: hdrs.remove(host) hdrs.remove(endpt) host = host.split(" ")[1] endpt = endpt.split(" ") if (self.__proxy[4] != None and self.__proxy[5] != None): hdrs.insert(0, self.__getauthheader()) hdrs.insert(0, "Host: %s" % host) hdrs.insert(0, "%s http://%s%s %s" % (endpt[0], host, endpt[1], endpt[2])) return "\r\n".join(hdrs) def __getauthheader(self): auth = self.__proxy[4] + ":" + self.__proxy[5] return "Proxy-Authorization: Basic " + base64.b64encode(auth) def setproxy(self, proxytype=None, addr=None, port=None, rdns=True, username=None, password=None): """setproxy(proxytype, addr[, port[, rdns[, username[, password]]]]) Sets the proxy to be used. proxytype - The type of the proxy to be used. Three types are supported: PROXY_TYPE_SOCKS4 (including socks4a), PROXY_TYPE_SOCKS5 and PROXY_TYPE_HTTP addr - The address of the server (IP or DNS). port - The port of the server. Defaults to 1080 for SOCKS servers and 8080 for HTTP proxy servers. rdns - Should DNS queries be preformed on the remote side (rather than the local side). The default is True. Note: This has no effect with SOCKS4 servers. username - Username to authenticate with to the server. The default is no authentication. password - Password to authenticate with to the server. Only relevant when username is also provided. """ self.__proxy = (proxytype, addr, port, rdns, username, password) def __negotiatesocks5(self, destaddr, destport): """__negotiatesocks5(self,destaddr,destport) Negotiates a connection through a SOCKS5 server. """ # First we'll send the authentication packages we support. if (self.__proxy[4]!=None) and (self.__proxy[5]!=None): # The username/password details were supplied to the # setproxy method so we support the USERNAME/PASSWORD # authentication (in addition to the standard none). self.sendall(struct.pack('BBBB', 0x05, 0x02, 0x00, 0x02)) else: # No username/password were entered, therefore we # only support connections with no authentication. self.sendall(struct.pack('BBB', 0x05, 0x01, 0x00)) # We'll receive the server's response to determine which # method was selected chosenauth = self.__recvall(2) if chosenauth[0:1] != chr(0x05).encode(): self.close() raise GeneralProxyError((1, _generalerrors[1])) # Check the chosen authentication method if chosenauth[1:2] == chr(0x00).encode(): # No authentication is required pass elif chosenauth[1:2] == chr(0x02).encode(): # Okay, we need to perform a basic username/password # authentication. self.sendall(chr(0x01).encode() + chr(len(self.__proxy[4])) + self.__proxy[4] + chr(len(self.__proxy[5])) + self.__proxy[5]) authstat = self.__recvall(2) if authstat[0:1] != chr(0x01).encode(): # Bad response self.close() raise GeneralProxyError((1, _generalerrors[1])) if authstat[1:2] != chr(0x00).encode(): # Authentication failed self.close() raise Socks5AuthError((3, _socks5autherrors[3])) # Authentication succeeded else: # Reaching here is always bad self.close() if chosenauth[1] == chr(0xFF).encode(): raise Socks5AuthError((2, _socks5autherrors[2])) else: raise GeneralProxyError((1, _generalerrors[1])) # Now we can request the actual connection req = struct.pack('BBB', 0x05, 0x01, 0x00) # If the given destination address is an IP address, we'll # use the IPv4 address request even if remote resolving was specified. try: ipaddr = socket.inet_aton(destaddr) req = req + chr(0x01).encode() + ipaddr except socket.error: # Well it's not an IP number, so it's probably a DNS name. if self.__proxy[3]: # Resolve remotely ipaddr = None req = req + chr(0x03).encode() + chr(len(destaddr)).encode() + destaddr else: # Resolve locally ipaddr = socket.inet_aton(socket.gethostbyname(destaddr)) req = req + chr(0x01).encode() + ipaddr req = req + struct.pack(">H", destport) self.sendall(req) # Get the response resp = self.__recvall(4) if resp[0:1] != chr(0x05).encode(): self.close() raise GeneralProxyError((1, _generalerrors[1])) elif resp[1:2] != chr(0x00).encode(): # Connection failed self.close() if ord(resp[1:2])<=8: raise Socks5Error((ord(resp[1:2]), _socks5errors[ord(resp[1:2])])) else: raise Socks5Error((9, _socks5errors[9])) # Get the bound address/port elif resp[3:4] == chr(0x01).encode(): boundaddr = self.__recvall(4) elif resp[3:4] == chr(0x03).encode(): resp = resp + self.recv(1) boundaddr = self.__recvall(ord(resp[4:5])) else: self.close() raise GeneralProxyError((1,_generalerrors[1])) boundport = struct.unpack(">H", self.__recvall(2))[0] self.__proxysockname = (boundaddr, boundport) if ipaddr != None: self.__proxypeername = (socket.inet_ntoa(ipaddr), destport) else: self.__proxypeername = (destaddr, destport) def getproxysockname(self): """getsockname() -> address info Returns the bound IP address and port number at the proxy. """ return self.__proxysockname def getproxypeername(self): """getproxypeername() -> address info Returns the IP and port number of the proxy. """ return _orgsocket.getpeername(self) def getpeername(self): """getpeername() -> address info Returns the IP address and port number of the destination machine (note: getproxypeername returns the proxy) """ return self.__proxypeername def __negotiatesocks4(self,destaddr,destport): """__negotiatesocks4(self,destaddr,destport) Negotiates a connection through a SOCKS4 server. """ # Check if the destination address provided is an IP address rmtrslv = False try: ipaddr = socket.inet_aton(destaddr) except socket.error: # It's a DNS name. Check where it should be resolved. if self.__proxy[3]: ipaddr = struct.pack("BBBB", 0x00, 0x00, 0x00, 0x01) rmtrslv = True else: ipaddr = socket.inet_aton(socket.gethostbyname(destaddr)) # Construct the request packet req = struct.pack(">BBH", 0x04, 0x01, destport) + ipaddr # The username parameter is considered userid for SOCKS4 if self.__proxy[4] != None: req = req + self.__proxy[4] req = req + chr(0x00).encode() # DNS name if remote resolving is required # NOTE: This is actually an extension to the SOCKS4 protocol # called SOCKS4A and may not be supported in all cases. if rmtrslv: req = req + destaddr + chr(0x00).encode() self.sendall(req) # Get the response from the server resp = self.__recvall(8) if resp[0:1] != chr(0x00).encode(): # Bad data self.close() raise GeneralProxyError((1,_generalerrors[1])) if resp[1:2] != chr(0x5A).encode(): # Server returned an error self.close() if ord(resp[1:2]) in (91, 92, 93): self.close() raise Socks4Error((ord(resp[1:2]), _socks4errors[ord(resp[1:2]) - 90])) else: raise Socks4Error((94, _socks4errors[4])) # Get the bound address/port self.__proxysockname = (socket.inet_ntoa(resp[4:]), struct.unpack(">H", resp[2:4])[0]) if rmtrslv != None: self.__proxypeername = (socket.inet_ntoa(ipaddr), destport) else: self.__proxypeername = (destaddr, destport) def __negotiatehttp(self, destaddr, destport): """__negotiatehttp(self,destaddr,destport) Negotiates a connection through an HTTP server. """ # If we need to resolve locally, we do this now if not self.__proxy[3]: addr = socket.gethostbyname(destaddr) else: addr = destaddr headers = ["CONNECT ", addr, ":", str(destport), " HTTP/1.1\r\n"] headers += ["Host: ", destaddr, "\r\n"] if (self.__proxy[4] != None and self.__proxy[5] != None): headers += [self.__getauthheader(), "\r\n"] headers.append("\r\n") self.sendall("".join(headers).encode()) # We read the response until we get the string "\r\n\r\n" resp = self.recv(1) while resp.find("\r\n\r\n".encode()) == -1: resp = resp + self.recv(1) # We just need the first line to check if the connection # was successful statusline = resp.splitlines()[0].split(" ".encode(), 2) if statusline[0] not in ("HTTP/1.0".encode(), "HTTP/1.1".encode()): self.close() raise GeneralProxyError((1, _generalerrors[1])) try: statuscode = int(statusline[1]) except ValueError: self.close() raise GeneralProxyError((1, _generalerrors[1])) if statuscode != 200: self.close() raise HTTPError((statuscode, statusline[2])) self.__proxysockname = ("0.0.0.0", 0) self.__proxypeername = (addr, destport) def connect(self, destpair): """connect(self, despair) Connects to the specified destination through a proxy. destpar - A tuple of the IP/DNS address and the port number. (identical to socket's connect). To select the proxy server use setproxy(). """ # Do a minimal input check first if (not type(destpair) in (list,tuple)) or (len(destpair) < 2) or (type(destpair[0]) != type('')) or (type(destpair[1]) != int): raise GeneralProxyError((5, _generalerrors[5])) if self.__proxy[0] == PROXY_TYPE_SOCKS5: if self.__proxy[2] != None: portnum = self.__proxy[2] else: portnum = 1080 _orgsocket.connect(self, (self.__proxy[1], portnum)) self.__negotiatesocks5(destpair[0], destpair[1]) elif self.__proxy[0] == PROXY_TYPE_SOCKS4: if self.__proxy[2] != None: portnum = self.__proxy[2] else: portnum = 1080 _orgsocket.connect(self,(self.__proxy[1], portnum)) self.__negotiatesocks4(destpair[0], destpair[1]) elif self.__proxy[0] == PROXY_TYPE_HTTP: if self.__proxy[2] != None: portnum = self.__proxy[2] else: portnum = 8080 _orgsocket.connect(self,(self.__proxy[1], portnum)) self.__negotiatehttp(destpair[0], destpair[1]) elif self.__proxy[0] == PROXY_TYPE_HTTP_NO_TUNNEL: if self.__proxy[2] != None: portnum = self.__proxy[2] else: portnum = 8080 _orgsocket.connect(self,(self.__proxy[1],portnum)) if destpair[1] == 443: self.__negotiatehttp(destpair[0],destpair[1]) else: self.__httptunnel = False elif self.__proxy[0] == None: _orgsocket.connect(self, (destpair[0], destpair[1])) else: raise GeneralProxyError((4, _generalerrors[4]))
Python
import Cookie import datetime import time import email.utils import calendar import base64 import hashlib import hmac import re import logging # Ripped from the Tornado Framework's web.py # http://github.com/facebook/tornado/commit/39ac6d169a36a54bb1f6b9bf1fdebb5c9da96e09 # # Tornado is licensed under the Apache Licence, Version 2.0 # (http://www.apache.org/licenses/LICENSE-2.0.html). # # Example: # from vendor.prayls.lilcookies import LilCookies # cookieutil = LilCookies(self, application_settings['cookie_secret']) # cookieutil.set_secure_cookie(name = 'mykey', value = 'myvalue', expires_days= 365*100) # cookieutil.get_secure_cookie(name = 'mykey') class LilCookies: @staticmethod def _utf8(s): if isinstance(s, unicode): return s.encode("utf-8") assert isinstance(s, str) return s @staticmethod def _time_independent_equals(a, b): if len(a) != len(b): return False result = 0 for x, y in zip(a, b): result |= ord(x) ^ ord(y) return result == 0 @staticmethod def _signature_from_secret(cookie_secret, *parts): """ Takes a secret salt value to create a signature for values in the `parts` param.""" hash = hmac.new(cookie_secret, digestmod=hashlib.sha1) for part in parts: hash.update(part) return hash.hexdigest() @staticmethod def _signed_cookie_value(cookie_secret, name, value): """ Returns a signed value for use in a cookie. This is helpful to have in its own method if you need to re-use this function for other needs. """ timestamp = str(int(time.time())) value = base64.b64encode(value) signature = LilCookies._signature_from_secret(cookie_secret, name, value, timestamp) return "|".join([value, timestamp, signature]) @staticmethod def _verified_cookie_value(cookie_secret, name, signed_value): """Returns the un-encrypted value given the signed value if it validates, or None.""" value = signed_value if not value: return None parts = value.split("|") if len(parts) != 3: return None signature = LilCookies._signature_from_secret(cookie_secret, name, parts[0], parts[1]) if not LilCookies._time_independent_equals(parts[2], signature): logging.warning("Invalid cookie signature %r", value) return None timestamp = int(parts[1]) if timestamp < time.time() - 31 * 86400: logging.warning("Expired cookie %r", value) return None try: return base64.b64decode(parts[0]) except: return None def __init__(self, handler, cookie_secret): """You must specify the cookie_secret to use any of the secure methods. It should be a long, random sequence of bytes to be used as the HMAC secret for the signature. """ if len(cookie_secret) < 45: raise ValueError("LilCookies cookie_secret should at least be 45 characters long, but got `%s`" % cookie_secret) self.handler = handler self.request = handler.request self.response = handler.response self.cookie_secret = cookie_secret def cookies(self): """A dictionary of Cookie.Morsel objects.""" if not hasattr(self, "_cookies"): self._cookies = Cookie.BaseCookie() if "Cookie" in self.request.headers: try: self._cookies.load(self.request.headers["Cookie"]) except: self.clear_all_cookies() return self._cookies def get_cookie(self, name, default=None): """Gets the value of the cookie with the given name, else default.""" if name in self.cookies(): return self._cookies[name].value return default def set_cookie(self, name, value, domain=None, expires=None, path="/", expires_days=None, **kwargs): """Sets the given cookie name/value with the given options. Additional keyword arguments are set on the Cookie.Morsel directly. See http://docs.python.org/library/cookie.html#morsel-objects for available attributes. """ name = LilCookies._utf8(name) value = LilCookies._utf8(value) if re.search(r"[\x00-\x20]", name + value): # Don't let us accidentally inject bad stuff raise ValueError("Invalid cookie %r: %r" % (name, value)) if not hasattr(self, "_new_cookies"): self._new_cookies = [] new_cookie = Cookie.BaseCookie() self._new_cookies.append(new_cookie) new_cookie[name] = value if domain: new_cookie[name]["domain"] = domain if expires_days is not None and not expires: expires = datetime.datetime.utcnow() + datetime.timedelta(days=expires_days) if expires: timestamp = calendar.timegm(expires.utctimetuple()) new_cookie[name]["expires"] = email.utils.formatdate( timestamp, localtime=False, usegmt=True) if path: new_cookie[name]["path"] = path for k, v in kwargs.iteritems(): new_cookie[name][k] = v # The 2 lines below were not in Tornado. Instead, they output all their cookies to the headers at once before a response flush. for vals in new_cookie.values(): self.response.headers._headers.append(('Set-Cookie', vals.OutputString(None))) def clear_cookie(self, name, path="/", domain=None): """Deletes the cookie with the given name.""" expires = datetime.datetime.utcnow() - datetime.timedelta(days=365) self.set_cookie(name, value="", path=path, expires=expires, domain=domain) def clear_all_cookies(self): """Deletes all the cookies the user sent with this request.""" for name in self.cookies().iterkeys(): self.clear_cookie(name) def set_secure_cookie(self, name, value, expires_days=30, **kwargs): """Signs and timestamps a cookie so it cannot be forged. To read a cookie set with this method, use get_secure_cookie(). """ value = LilCookies._signed_cookie_value(self.cookie_secret, name, value) self.set_cookie(name, value, expires_days=expires_days, **kwargs) def get_secure_cookie(self, name, value=None): """Returns the given signed cookie if it validates, or None.""" if value is None: value = self.get_cookie(name) return LilCookies._verified_cookie_value(self.cookie_secret, name, value) def _cookie_signature(self, *parts): return LilCookies._signature_from_secret(self.cookie_secret)
Python
# This is the version of this source code. manual_verstr = "1.5" auto_build_num = "211" verstr = manual_verstr + "." + auto_build_num try: from pyutil.version_class import Version as pyutil_Version __version__ = pyutil_Version(verstr) except (ImportError, ValueError): # Maybe there is no pyutil installed. from distutils.version import LooseVersion as distutils_Version __version__ = distutils_Version(verstr)
Python
""" The MIT License Copyright (c) 2007-2010 Leah Culver, Joe Stump, Mark Paschal, Vic Fryzel Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ import oauth2 import smtplib import base64 class SMTP(smtplib.SMTP): """SMTP wrapper for smtplib.SMTP that implements XOAUTH.""" def authenticate(self, url, consumer, token): if consumer is not None and not isinstance(consumer, oauth2.Consumer): raise ValueError("Invalid consumer.") if token is not None and not isinstance(token, oauth2.Token): raise ValueError("Invalid token.") self.docmd('AUTH', 'XOAUTH %s' % \ base64.b64encode(oauth2.build_xoauth_string(url, consumer, token)))
Python
""" The MIT License Copyright (c) 2007-2010 Leah Culver, Joe Stump, Mark Paschal, Vic Fryzel Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ import oauth2 import imaplib class IMAP4_SSL(imaplib.IMAP4_SSL): """IMAP wrapper for imaplib.IMAP4_SSL that implements XOAUTH.""" def authenticate(self, url, consumer, token): if consumer is not None and not isinstance(consumer, oauth2.Consumer): raise ValueError("Invalid consumer.") if token is not None and not isinstance(token, oauth2.Token): raise ValueError("Invalid token.") imaplib.IMAP4_SSL.authenticate(self, 'XOAUTH', lambda x: oauth2.build_xoauth_string(url, consumer, token))
Python
""" The MIT License Copyright (c) 2007-2010 Leah Culver, Joe Stump, Mark Paschal, Vic Fryzel Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ import base64 import urllib import time import random import urlparse import hmac import binascii import httplib2 try: from urlparse import parse_qs parse_qs # placate pyflakes except ImportError: # fall back for Python 2.5 from cgi import parse_qs try: from hashlib import sha1 sha = sha1 except ImportError: # hashlib was added in Python 2.5 import sha import _version __version__ = _version.__version__ OAUTH_VERSION = '1.0' # Hi Blaine! HTTP_METHOD = 'GET' SIGNATURE_METHOD = 'PLAINTEXT' class Error(RuntimeError): """Generic exception class.""" def __init__(self, message='OAuth error occurred.'): self._message = message @property def message(self): """A hack to get around the deprecation errors in 2.6.""" return self._message def __str__(self): return self._message class MissingSignature(Error): pass def build_authenticate_header(realm=''): """Optional WWW-Authenticate header (401 error)""" return {'WWW-Authenticate': 'OAuth realm="%s"' % realm} def build_xoauth_string(url, consumer, token=None): """Build an XOAUTH string for use in SMTP/IMPA authentication.""" request = Request.from_consumer_and_token(consumer, token, "GET", url) signing_method = SignatureMethod_HMAC_SHA1() request.sign_request(signing_method, consumer, token) params = [] for k, v in sorted(request.iteritems()): if v is not None: params.append('%s="%s"' % (k, escape(v))) return "%s %s %s" % ("GET", url, ','.join(params)) def to_unicode(s): """ Convert to unicode, raise exception with instructive error message if s is not unicode, ascii, or utf-8. """ if not isinstance(s, unicode): if not isinstance(s, str): raise TypeError('You are required to pass either unicode or string here, not: %r (%s)' % (type(s), s)) try: s = s.decode('utf-8') except UnicodeDecodeError, le: raise TypeError('You are required to pass either a unicode object or a utf-8 string here. You passed a Python string object which contained non-utf-8: %r. The UnicodeDecodeError that resulted from attempting to interpret it as utf-8 was: %s' % (s, le,)) return s def to_utf8(s): return to_unicode(s).encode('utf-8') def to_unicode_if_string(s): if isinstance(s, basestring): return to_unicode(s) else: return s def to_utf8_if_string(s): if isinstance(s, basestring): return to_utf8(s) else: return s def to_unicode_optional_iterator(x): """ Raise TypeError if x is a str containing non-utf8 bytes or if x is an iterable which contains such a str. """ if isinstance(x, basestring): return to_unicode(x) try: l = list(x) except TypeError, e: assert 'is not iterable' in str(e) return x else: return [ to_unicode(e) for e in l ] def to_utf8_optional_iterator(x): """ Raise TypeError if x is a str or if x is an iterable which contains a str. """ if isinstance(x, basestring): return to_utf8(x) try: l = list(x) except TypeError, e: assert 'is not iterable' in str(e) return x else: return [ to_utf8_if_string(e) for e in l ] def escape(s): """Escape a URL including any /.""" return urllib.quote(s.encode('utf-8'), safe='~') def generate_timestamp(): """Get seconds since epoch (UTC).""" return int(time.time()) def generate_nonce(length=8): """Generate pseudorandom number.""" return ''.join([str(random.randint(0, 9)) for i in range(length)]) def generate_verifier(length=8): """Generate pseudorandom number.""" return ''.join([str(random.randint(0, 9)) for i in range(length)]) class Consumer(object): """A consumer of OAuth-protected services. The OAuth consumer is a "third-party" service that wants to access protected resources from an OAuth service provider on behalf of an end user. It's kind of the OAuth client. Usually a consumer must be registered with the service provider by the developer of the consumer software. As part of that process, the service provider gives the consumer a *key* and a *secret* with which the consumer software can identify itself to the service. The consumer will include its key in each request to identify itself, but will use its secret only when signing requests, to prove that the request is from that particular registered consumer. Once registered, the consumer can then use its consumer credentials to ask the service provider for a request token, kicking off the OAuth authorization process. """ key = None secret = None def __init__(self, key, secret): self.key = key self.secret = secret if self.key is None or self.secret is None: raise ValueError("Key and secret must be set.") def __str__(self): data = {'oauth_consumer_key': self.key, 'oauth_consumer_secret': self.secret} return urllib.urlencode(data) class Token(object): """An OAuth credential used to request authorization or a protected resource. Tokens in OAuth comprise a *key* and a *secret*. The key is included in requests to identify the token being used, but the secret is used only in the signature, to prove that the requester is who the server gave the token to. When first negotiating the authorization, the consumer asks for a *request token* that the live user authorizes with the service provider. The consumer then exchanges the request token for an *access token* that can be used to access protected resources. """ key = None secret = None callback = None callback_confirmed = None verifier = None def __init__(self, key, secret): self.key = key self.secret = secret if self.key is None or self.secret is None: raise ValueError("Key and secret must be set.") def set_callback(self, callback): self.callback = callback self.callback_confirmed = 'true' def set_verifier(self, verifier=None): if verifier is not None: self.verifier = verifier else: self.verifier = generate_verifier() def get_callback_url(self): if self.callback and self.verifier: # Append the oauth_verifier. parts = urlparse.urlparse(self.callback) scheme, netloc, path, params, query, fragment = parts[:6] if query: query = '%s&oauth_verifier=%s' % (query, self.verifier) else: query = 'oauth_verifier=%s' % self.verifier return urlparse.urlunparse((scheme, netloc, path, params, query, fragment)) return self.callback def to_string(self): """Returns this token as a plain string, suitable for storage. The resulting string includes the token's secret, so you should never send or store this string where a third party can read it. """ data = { 'oauth_token': self.key, 'oauth_token_secret': self.secret, } if self.callback_confirmed is not None: data['oauth_callback_confirmed'] = self.callback_confirmed return urllib.urlencode(data) @staticmethod def from_string(s): """Deserializes a token from a string like one returned by `to_string()`.""" if not len(s): raise ValueError("Invalid parameter string.") params = parse_qs(s, keep_blank_values=False) if not len(params): raise ValueError("Invalid parameter string.") try: key = params['oauth_token'][0] except Exception: raise ValueError("'oauth_token' not found in OAuth request.") try: secret = params['oauth_token_secret'][0] except Exception: raise ValueError("'oauth_token_secret' not found in " "OAuth request.") token = Token(key, secret) try: token.callback_confirmed = params['oauth_callback_confirmed'][0] except KeyError: pass # 1.0, no callback confirmed. return token def __str__(self): return self.to_string() def setter(attr): name = attr.__name__ def getter(self): try: return self.__dict__[name] except KeyError: raise AttributeError(name) def deleter(self): del self.__dict__[name] return property(getter, attr, deleter) class Request(dict): """The parameters and information for an HTTP request, suitable for authorizing with OAuth credentials. When a consumer wants to access a service's protected resources, it does so using a signed HTTP request identifying itself (the consumer) with its key, and providing an access token authorized by the end user to access those resources. """ version = OAUTH_VERSION def __init__(self, method=HTTP_METHOD, url=None, parameters=None, body='', is_form_encoded=False): if url is not None: self.url = to_unicode(url) self.method = method if parameters is not None: for k, v in parameters.iteritems(): k = to_unicode(k) v = to_unicode_optional_iterator(v) self[k] = v self.body = body self.is_form_encoded = is_form_encoded @setter def url(self, value): self.__dict__['url'] = value if value is not None: scheme, netloc, path, params, query, fragment = urlparse.urlparse(value) # Exclude default port numbers. if scheme == 'http' and netloc[-3:] == ':80': netloc = netloc[:-3] elif scheme == 'https' and netloc[-4:] == ':443': netloc = netloc[:-4] if scheme not in ('http', 'https'): raise ValueError("Unsupported URL %s (%s)." % (value, scheme)) # Normalized URL excludes params, query, and fragment. self.normalized_url = urlparse.urlunparse((scheme, netloc, path, None, None, None)) else: self.normalized_url = None self.__dict__['url'] = None @setter def method(self, value): self.__dict__['method'] = value.upper() def _get_timestamp_nonce(self): return self['oauth_timestamp'], self['oauth_nonce'] def get_nonoauth_parameters(self): """Get any non-OAuth parameters.""" return dict([(k, v) for k, v in self.iteritems() if not k.startswith('oauth_')]) def to_header(self, realm=''): """Serialize as a header for an HTTPAuth request.""" oauth_params = ((k, v) for k, v in self.items() if k.startswith('oauth_')) stringy_params = ((k, escape(str(v))) for k, v in oauth_params) header_params = ('%s="%s"' % (k, v) for k, v in stringy_params) params_header = ', '.join(header_params) auth_header = 'OAuth realm="%s"' % realm if params_header: auth_header = "%s, %s" % (auth_header, params_header) return {'Authorization': auth_header} def to_postdata(self): """Serialize as post data for a POST request.""" d = {} for k, v in self.iteritems(): d[k.encode('utf-8')] = to_utf8_optional_iterator(v) # tell urlencode to deal with sequence values and map them correctly # to resulting querystring. for example self["k"] = ["v1", "v2"] will # result in 'k=v1&k=v2' and not k=%5B%27v1%27%2C+%27v2%27%5D return urllib.urlencode(d, True).replace('+', '%20') def to_url(self): """Serialize as a URL for a GET request.""" base_url = urlparse.urlparse(self.url) try: query = base_url.query except AttributeError: # must be python <2.5 query = base_url[4] query = parse_qs(query) for k, v in self.items(): query.setdefault(k, []).append(v) try: scheme = base_url.scheme netloc = base_url.netloc path = base_url.path params = base_url.params fragment = base_url.fragment except AttributeError: # must be python <2.5 scheme = base_url[0] netloc = base_url[1] path = base_url[2] params = base_url[3] fragment = base_url[5] url = (scheme, netloc, path, params, urllib.urlencode(query, True), fragment) return urlparse.urlunparse(url) def get_parameter(self, parameter): ret = self.get(parameter) if ret is None: raise Error('Parameter not found: %s' % parameter) return ret def get_normalized_parameters(self): """Return a string that contains the parameters that must be signed.""" items = [] for key, value in self.iteritems(): if key == 'oauth_signature': continue # 1.0a/9.1.1 states that kvp must be sorted by key, then by value, # so we unpack sequence values into multiple items for sorting. if isinstance(value, basestring): items.append((to_utf8_if_string(key), to_utf8(value))) else: try: value = list(value) except TypeError, e: assert 'is not iterable' in str(e) items.append((to_utf8_if_string(key), to_utf8_if_string(value))) else: items.extend((to_utf8_if_string(key), to_utf8_if_string(item)) for item in value) # Include any query string parameters from the provided URL query = urlparse.urlparse(self.url)[4] url_items = self._split_url_string(query).items() url_items = [(to_utf8(k), to_utf8(v)) for k, v in url_items if k != 'oauth_signature' ] items.extend(url_items) items.sort() encoded_str = urllib.urlencode(items) # Encode signature parameters per Oauth Core 1.0 protocol # spec draft 7, section 3.6 # (http://tools.ietf.org/html/draft-hammer-oauth-07#section-3.6) # Spaces must be encoded with "%20" instead of "+" return encoded_str.replace('+', '%20').replace('%7E', '~') def sign_request(self, signature_method, consumer, token): """Set the signature parameter to the result of sign.""" if not self.is_form_encoded: # according to # http://oauth.googlecode.com/svn/spec/ext/body_hash/1.0/oauth-bodyhash.html # section 4.1.1 "OAuth Consumers MUST NOT include an # oauth_body_hash parameter on requests with form-encoded # request bodies." self['oauth_body_hash'] = base64.b64encode(sha(self.body).digest()) if 'oauth_consumer_key' not in self: self['oauth_consumer_key'] = consumer.key if token and 'oauth_token' not in self: self['oauth_token'] = token.key self['oauth_signature_method'] = signature_method.name self['oauth_signature'] = signature_method.sign(self, consumer, token) @classmethod def make_timestamp(cls): """Get seconds since epoch (UTC).""" return str(int(time.time())) @classmethod def make_nonce(cls): """Generate pseudorandom number.""" return str(random.randint(0, 100000000)) @classmethod def from_request(cls, http_method, http_url, headers=None, parameters=None, query_string=None): """Combines multiple parameter sources.""" if parameters is None: parameters = {} # Headers if headers and 'Authorization' in headers: auth_header = headers['Authorization'] # Check that the authorization header is OAuth. if auth_header[:6] == 'OAuth ': auth_header = auth_header[6:] try: # Get the parameters from the header. header_params = cls._split_header(auth_header) parameters.update(header_params) except: raise Error('Unable to parse OAuth parameters from ' 'Authorization header.') # GET or POST query string. if query_string: query_params = cls._split_url_string(query_string) parameters.update(query_params) # URL parameters. param_str = urlparse.urlparse(http_url)[4] # query url_params = cls._split_url_string(param_str) parameters.update(url_params) if parameters: return cls(http_method, http_url, parameters) return None @classmethod def from_consumer_and_token(cls, consumer, token=None, http_method=HTTP_METHOD, http_url=None, parameters=None, body='', is_form_encoded=False): if not parameters: parameters = {} defaults = { 'oauth_consumer_key': consumer.key, 'oauth_timestamp': cls.make_timestamp(), 'oauth_nonce': cls.make_nonce(), 'oauth_version': cls.version, } defaults.update(parameters) parameters = defaults if token: parameters['oauth_token'] = token.key if token.verifier: parameters['oauth_verifier'] = token.verifier return Request(http_method, http_url, parameters, body=body, is_form_encoded=is_form_encoded) @classmethod def from_token_and_callback(cls, token, callback=None, http_method=HTTP_METHOD, http_url=None, parameters=None): if not parameters: parameters = {} parameters['oauth_token'] = token.key if callback: parameters['oauth_callback'] = callback return cls(http_method, http_url, parameters) @staticmethod def _split_header(header): """Turn Authorization: header into parameters.""" params = {} parts = header.split(',') for param in parts: # Ignore realm parameter. if param.find('realm') > -1: continue # Remove whitespace. param = param.strip() # Split key-value. param_parts = param.split('=', 1) # Remove quotes and unescape the value. params[param_parts[0]] = urllib.unquote(param_parts[1].strip('\"')) return params @staticmethod def _split_url_string(param_str): """Turn URL string into parameters.""" parameters = parse_qs(param_str.encode('utf-8'), keep_blank_values=True) for k, v in parameters.iteritems(): parameters[k] = urllib.unquote(v[0]) return parameters class Client(httplib2.Http): """OAuthClient is a worker to attempt to execute a request.""" def __init__(self, consumer, token=None, cache=None, timeout=None, proxy_info=None): if consumer is not None and not isinstance(consumer, Consumer): raise ValueError("Invalid consumer.") if token is not None and not isinstance(token, Token): raise ValueError("Invalid token.") self.consumer = consumer self.token = token self.method = SignatureMethod_HMAC_SHA1() httplib2.Http.__init__(self, cache=cache, timeout=timeout, proxy_info=proxy_info) def set_signature_method(self, method): if not isinstance(method, SignatureMethod): raise ValueError("Invalid signature method.") self.method = method def request(self, uri, method="GET", body='', headers=None, redirections=httplib2.DEFAULT_MAX_REDIRECTS, connection_type=None): DEFAULT_POST_CONTENT_TYPE = 'application/x-www-form-urlencoded' if not isinstance(headers, dict): headers = {} if method == "POST": headers['Content-Type'] = headers.get('Content-Type', DEFAULT_POST_CONTENT_TYPE) is_form_encoded = \ headers.get('Content-Type') == 'application/x-www-form-urlencoded' if is_form_encoded and body: parameters = parse_qs(body) else: parameters = None req = Request.from_consumer_and_token(self.consumer, token=self.token, http_method=method, http_url=uri, parameters=parameters, body=body, is_form_encoded=is_form_encoded) req.sign_request(self.method, self.consumer, self.token) schema, rest = urllib.splittype(uri) if rest.startswith('//'): hierpart = '//' else: hierpart = '' host, rest = urllib.splithost(rest) realm = schema + ':' + hierpart + host if is_form_encoded: body = req.to_postdata() elif method == "GET": uri = req.to_url() else: headers.update(req.to_header(realm=realm)) return httplib2.Http.request(self, uri, method=method, body=body, headers=headers, redirections=redirections, connection_type=connection_type) class Server(object): """A skeletal implementation of a service provider, providing protected resources to requests from authorized consumers. This class implements the logic to check requests for authorization. You can use it with your web server or web framework to protect certain resources with OAuth. """ timestamp_threshold = 300 # In seconds, five minutes. version = OAUTH_VERSION signature_methods = None def __init__(self, signature_methods=None): self.signature_methods = signature_methods or {} def add_signature_method(self, signature_method): self.signature_methods[signature_method.name] = signature_method return self.signature_methods def verify_request(self, request, consumer, token): """Verifies an api call and checks all the parameters.""" self._check_version(request) self._check_signature(request, consumer, token) parameters = request.get_nonoauth_parameters() return parameters def build_authenticate_header(self, realm=''): """Optional support for the authenticate header.""" return {'WWW-Authenticate': 'OAuth realm="%s"' % realm} def _check_version(self, request): """Verify the correct version of the request for this server.""" version = self._get_version(request) if version and version != self.version: raise Error('OAuth version %s not supported.' % str(version)) def _get_version(self, request): """Return the version of the request for this server.""" try: version = request.get_parameter('oauth_version') except: version = OAUTH_VERSION return version def _get_signature_method(self, request): """Figure out the signature with some defaults.""" try: signature_method = request.get_parameter('oauth_signature_method') except: signature_method = SIGNATURE_METHOD try: # Get the signature method object. signature_method = self.signature_methods[signature_method] except: signature_method_names = ', '.join(self.signature_methods.keys()) raise Error('Signature method %s not supported try one of the following: %s' % (signature_method, signature_method_names)) return signature_method def _get_verifier(self, request): return request.get_parameter('oauth_verifier') def _check_signature(self, request, consumer, token): timestamp, nonce = request._get_timestamp_nonce() self._check_timestamp(timestamp) signature_method = self._get_signature_method(request) try: signature = request.get_parameter('oauth_signature') except: raise MissingSignature('Missing oauth_signature.') # Validate the signature. valid = signature_method.check(request, consumer, token, signature) if not valid: key, base = signature_method.signing_base(request, consumer, token) raise Error('Invalid signature. Expected signature base ' 'string: %s' % base) def _check_timestamp(self, timestamp): """Verify that timestamp is recentish.""" timestamp = int(timestamp) now = int(time.time()) lapsed = now - timestamp if lapsed > self.timestamp_threshold: raise Error('Expired timestamp: given %d and now %s has a ' 'greater difference than threshold %d' % (timestamp, now, self.timestamp_threshold)) class SignatureMethod(object): """A way of signing requests. The OAuth protocol lets consumers and service providers pick a way to sign requests. This interface shows the methods expected by the other `oauth` modules for signing requests. Subclass it and implement its methods to provide a new way to sign requests. """ def signing_base(self, request, consumer, token): """Calculates the string that needs to be signed. This method returns a 2-tuple containing the starting key for the signing and the message to be signed. The latter may be used in error messages to help clients debug their software. """ raise NotImplementedError def sign(self, request, consumer, token): """Returns the signature for the given request, based on the consumer and token also provided. You should use your implementation of `signing_base()` to build the message to sign. Otherwise it may be less useful for debugging. """ raise NotImplementedError def check(self, request, consumer, token, signature): """Returns whether the given signature is the correct signature for the given consumer and token signing the given request.""" built = self.sign(request, consumer, token) return built == signature class SignatureMethod_HMAC_SHA1(SignatureMethod): name = 'HMAC-SHA1' def signing_base(self, request, consumer, token): if not hasattr(request, 'normalized_url') or request.normalized_url is None: raise ValueError("Base URL for request is not set.") sig = ( escape(request.method), escape(request.normalized_url), escape(request.get_normalized_parameters()), ) key = '%s&' % escape(consumer.secret) if token: key += escape(token.secret) raw = '&'.join(sig) return key, raw def sign(self, request, consumer, token): """Builds the base signature string.""" key, raw = self.signing_base(request, consumer, token) hashed = hmac.new(key, raw, sha) # Calculate the digest base 64. return binascii.b2a_base64(hashed.digest())[:-1] class SignatureMethod_PLAINTEXT(SignatureMethod): name = 'PLAINTEXT' def signing_base(self, request, consumer, token): """Concatenates the consumer key and secret with the token's secret.""" sig = '%s&' % escape(consumer.secret) if token: sig = sig + escape(token.secret) return sig, sig def sign(self, request, consumer, token): key, raw = self.signing_base(request, consumer, token) return raw
Python
# Early, and incomplete implementation of -04. # import re import urllib RESERVED = ":/?#[]@!$&'()*+,;=" OPERATOR = "+./;?|!@" EXPLODE = "*+" MODIFIER = ":^" TEMPLATE = re.compile(r"{(?P<operator>[\+\./;\?|!@])?(?P<varlist>[^}]+)}", re.UNICODE) VAR = re.compile(r"^(?P<varname>[^=\+\*:\^]+)((?P<explode>[\+\*])|(?P<partial>[:\^]-?[0-9]+))?(=(?P<default>.*))?$", re.UNICODE) def _tostring(varname, value, explode, operator, safe=""): if type(value) == type([]): if explode == "+": return ",".join([varname + "." + urllib.quote(x, safe) for x in value]) else: return ",".join([urllib.quote(x, safe) for x in value]) if type(value) == type({}): keys = value.keys() keys.sort() if explode == "+": return ",".join([varname + "." + urllib.quote(key, safe) + "," + urllib.quote(value[key], safe) for key in keys]) else: return ",".join([urllib.quote(key, safe) + "," + urllib.quote(value[key], safe) for key in keys]) else: return urllib.quote(value, safe) def _tostring_path(varname, value, explode, operator, safe=""): joiner = operator if type(value) == type([]): if explode == "+": return joiner.join([varname + "." + urllib.quote(x, safe) for x in value]) elif explode == "*": return joiner.join([urllib.quote(x, safe) for x in value]) else: return ",".join([urllib.quote(x, safe) for x in value]) elif type(value) == type({}): keys = value.keys() keys.sort() if explode == "+": return joiner.join([varname + "." + urllib.quote(key, safe) + joiner + urllib.quote(value[key], safe) for key in keys]) elif explode == "*": return joiner.join([urllib.quote(key, safe) + joiner + urllib.quote(value[key], safe) for key in keys]) else: return ",".join([urllib.quote(key, safe) + "," + urllib.quote(value[key], safe) for key in keys]) else: if value: return urllib.quote(value, safe) else: return "" def _tostring_query(varname, value, explode, operator, safe=""): joiner = operator varprefix = "" if operator == "?": joiner = "&" varprefix = varname + "=" if type(value) == type([]): if 0 == len(value): return "" if explode == "+": return joiner.join([varname + "=" + urllib.quote(x, safe) for x in value]) elif explode == "*": return joiner.join([urllib.quote(x, safe) for x in value]) else: return varprefix + ",".join([urllib.quote(x, safe) for x in value]) elif type(value) == type({}): if 0 == len(value): return "" keys = value.keys() keys.sort() if explode == "+": return joiner.join([varname + "." + urllib.quote(key, safe) + "=" + urllib.quote(value[key], safe) for key in keys]) elif explode == "*": return joiner.join([urllib.quote(key, safe) + "=" + urllib.quote(value[key], safe) for key in keys]) else: return varprefix + ",".join([urllib.quote(key, safe) + "," + urllib.quote(value[key], safe) for key in keys]) else: if value: return varname + "=" + urllib.quote(value, safe) else: return varname TOSTRING = { "" : _tostring, "+": _tostring, ";": _tostring_query, "?": _tostring_query, "/": _tostring_path, ".": _tostring_path, } def expand(template, vars): def _sub(match): groupdict = match.groupdict() operator = groupdict.get('operator') if operator is None: operator = '' varlist = groupdict.get('varlist') safe = "@" if operator == '+': safe = RESERVED varspecs = varlist.split(",") varnames = [] defaults = {} for varspec in varspecs: m = VAR.search(varspec) groupdict = m.groupdict() varname = groupdict.get('varname') explode = groupdict.get('explode') partial = groupdict.get('partial') default = groupdict.get('default') if default: defaults[varname] = default varnames.append((varname, explode, partial)) retval = [] joiner = operator prefix = operator if operator == "+": prefix = "" joiner = "," if operator == "?": joiner = "&" if operator == "": joiner = "," for varname, explode, partial in varnames: if varname in vars: value = vars[varname] #if not value and (type(value) == type({}) or type(value) == type([])) and varname in defaults: if not value and value != "" and varname in defaults: value = defaults[varname] elif varname in defaults: value = defaults[varname] else: continue retval.append(TOSTRING[operator](varname, value, explode, operator, safe=safe)) if "".join(retval): return prefix + joiner.join(retval) else: return "" return TEMPLATE.sub(_sub, template)
Python
import channle def test(ptr, msg): print(ptr, msg) print("in python...", channle.send(111, 'echo "ok===="')) return 101 print('load end ok .......')
Python
from distutils.core import setup, Extension module1 = Extension('spam', sources = ['spam.c']) setup (name = 'PackageName', version = '1.0', description = 'This is a demo package', ext_modules = [module1])
Python
import pylib.ffqt as ffqt if __name__=='__main__': ffqt.run_loop()
Python
from distutils.core import setup import py2exe #setup(windows=[{"script" : "main.py"}], options={"py2exe" : {"includes" : ["sip", "PyQt4._qt"]}}) from distutils.core import setup import py2exe # Now you need to pass arguments to setup # windows is a list of scripts that have their own UI and # thus don't need to run in a console. setup(windows=['main.py'], options={ # And now, configure py2exe by passing more options; 'py2exe': { # This is magic: if you don't add these, your .exe may # or may not work on older/newer versions of windows. "dll_excludes": [ "MSVCP90.dll", "MSWSOCK.dll", "mswsock.dll", "powrprof.dll", "python27" ], # Py2exe will not figure out that you need these on its own. # You may need one, the other, or both. 'includes': [ 'sip', 'PyQt4.QtNetwork', 'PyQt4._qt', ], # Optional: make one big exe with everything in it, or # a folder with many things in it. Your choice # 'bundle_files': 1, } }, # Qt's dynamically loaded plugins and py2exe really don't # get along. data_files = [ ('phonon_backend', [ 'C:\Python27\Lib\site-packages\PyQt4\plugins\phonon_backend\phonon_ds94.dll' ]), ('imageplugins', [ 'c:\Python27\lib\site-packages\PyQt4\plugins\imageformats\qgif4.dll', 'c:\Python27\lib\site-packages\PyQt4\plugins\imageformats\qjpeg4.dll', 'c:\Python27\lib\site-packages\PyQt4\plugins\imageformats\qsvg4.dll', ]), ], # If you choose the bundle above, you may want to use this, too. # zipfile=None, )
Python
#!/usr/bin/env python import sys from PyQt4.QtCore import * from PyQt4.QtGui import * from PyQt4.QtWebKit import * app = QApplication(sys.argv) web = QWebView() web.load(QUrl("http://www.cnblogs.com/zhiranok")) web.show() sys.exit(app.exec_())
Python
from PyQt4.QtCore import * from PyQt4.QtGui import * from PyQt4.QtWebKit import * from PyQt4.QtNetwork import * import os import urllib import random import traceback class BrowserScreen(QWebView): def __init__(self): QWebView.__init__(self) #self.setHtml(html_content) self.load(QUrl.fromLocalFile(os.getcwd() + "/index.html")) self.createTrayIcon() self.trayIcon.show() self.resize(800, 600) self.setWindowIcon(QIcon("images/own.ico")) self.setWindowTitle("FFOWN") self.show() def createTrayIcon(self): self.trayIcon = QSystemTrayIcon(self) self.trayIcon.setIcon(QIcon("images/xm.ico")) def showMessage(self, msg): self.trayIcon.showMessage("This is Python", msg, QSystemTrayIcon.MessageIcon(0), 15 * 1000) class PythonJS(QObject): url = [] __pyqtSignals__ = ("contentChanged(const QString &)") @pyqtSignature("", result="QString") def get_image_url(self): if len(self.url) == 0: search_url = 'http://ffown.sinaapp.com/get_image_url.php' search_ret = eval(urllib.urlopen(search_url).read()) self.url = search_ret dest = self.url[random.randint(0, 100) % len(self.url)] return dest @pyqtSignature("QString", result="QString") def readfile(self, path): ret = "" try: f = open(path, "r") ret = f.read() f.close() except: ret = "file not exist!" + path traceback.print_exc() return ret @pyqtSignature("QString", result="QString") def select_file(self, ext = "*"): ret = QFileDialog.getOpenFileName(None, "", ext, "FileDialog") return ret def run_loop(): import sys import os os.chdir("./html") app = QApplication(sys.argv) browser = BrowserScreen() pjs = PythonJS() browser.page().mainFrame().addToJavaScriptWindowObject("python", pjs) QObject.connect(pjs, SIGNAL("contentChanged(const QString &)"), browser.showMessage) sys.exit(app.exec_())
Python
import json import urllib def download_image(start = 0, num = 8): search_url = 'https://ajax.googleapis.com/ajax/services/search/images?v=1.0&start=' + str(start) + '&rsz=' + str(num) + '&q=beautifulgirl' print(search_url) search_ret = json.loads(urllib.urlopen(search_url).read()) index = 0 for k in search_ret["responseData"]["results"]: filename = k["titleNoFormatting"] url = k["url"] image_fd = urllib.urlopen(url) image = image_fd.read() dest = open("./html/download/" + str(start + index) + ".jpeg", "wb") dest.write(image) dest.close() index = index + 1 def download_image_from_sae(start = 0, num = 8): search_url = 'http://ffown.sinaapp.com/get_image_url.php' search_ret = json.loads(urllib.urlopen(search_url).read()) index = start for url in search_ret: if index > num: break print(index, url) try: f = open("./download/" + str(index) + ".jpeg", "r") f.close() index = index + 1 continue except: pass try: image_fd = urllib.urlopen(url) image = image_fd.read() dest = open("./html/download/" + str(index) + ".jpeg", "wb") dest.write(image) dest.close() except: pass index = index + 1 #download_image_from_sae()
Python
#!/usr/bin/env python import sys from PyQt4.QtCore import * from PyQt4.QtGui import * from PyQt4.QtWebKit import * app = QApplication(sys.argv) web = QWebView() web.load(QUrl("http://www.cnblogs.com/zhiranok")) web.show() sys.exit(app.exec_())
Python
import wx class MyForm(wx.Frame): def __init__(self): wx.Frame.__init__(self, None, wx.ID_ANY, 'My Form') #, size=(300,350)) # Add a panel so it looks the correct on all platforms self.panel = wx.Panel(self, wx.ID_ANY) bmp = wx.ArtProvider.GetBitmap(wx.ART_INFORMATION, wx.ART_OTHER, (16, 16)) titleIco = wx.StaticBitmap(self.panel, wx.ID_ANY, bmp) title = wx.StaticText(self.panel, wx.ID_ANY, 'My Title') bmp = wx.ArtProvider.GetBitmap(wx.ART_TIP, wx.ART_OTHER, (16, 16)) inputOneIco = wx.StaticBitmap(self.panel, wx.ID_ANY, bmp) labelOne = wx.StaticText(self.panel, wx.ID_ANY, 'Input 1') inputTxtOne = wx.TextCtrl(self.panel, wx.ID_ANY, '') inputTwoIco = wx.StaticBitmap(self.panel, wx.ID_ANY, bmp) labelTwo = wx.StaticText(self.panel, wx.ID_ANY, 'Input 2') inputTxtTwo = wx.TextCtrl(self.panel, wx.ID_ANY, '') inputThreeIco = wx.StaticBitmap(self.panel, wx.ID_ANY, bmp) labelThree = wx.StaticText(self.panel, wx.ID_ANY, 'Input 3') inputTxtThree = wx.TextCtrl(self.panel, wx.ID_ANY, '') inputFourIco = wx.StaticBitmap(self.panel, wx.ID_ANY, bmp) labelFour = wx.StaticText(self.panel, wx.ID_ANY, 'Input 4') inputTxtFour = wx.TextCtrl(self.panel, wx.ID_ANY, '') okBtn = wx.Button(self.panel, wx.ID_ANY, 'OK') cancelBtn = wx.Button(self.panel, wx.ID_ANY, 'Cancel') self.Bind(wx.EVT_BUTTON, self.onOK, okBtn) self.Bind(wx.EVT_BUTTON, self.onCancel, cancelBtn) topSizer = wx.BoxSizer(wx.VERTICAL) titleSizer = wx.BoxSizer(wx.HORIZONTAL) inputOneSizer = wx.BoxSizer(wx.HORIZONTAL) inputTwoSizer = wx.BoxSizer(wx.HORIZONTAL) inputThreeSizer = wx.BoxSizer(wx.HORIZONTAL) inputFourSizer = wx.BoxSizer(wx.HORIZONTAL) btnSizer = wx.BoxSizer(wx.HORIZONTAL) titleSizer.Add(titleIco, 0, wx.ALL, 5) titleSizer.Add(title, 0, wx.ALL, 5) inputOneSizer.Add(inputOneIco, 0, wx.ALL, 5) inputOneSizer.Add(labelOne, 0, wx.ALL, 5) inputOneSizer.Add(inputTxtOne, 1, wx.ALL|wx.EXPAND, 5) inputTwoSizer.Add(inputTwoIco, 0, wx.ALL, 5) inputTwoSizer.Add(labelTwo, 0, wx.ALL, 5) inputTwoSizer.Add(inputTxtTwo, 1, wx.ALL|wx.EXPAND, 5) inputThreeSizer.Add(inputThreeIco, 0, wx.ALL, 5) inputThreeSizer.Add(labelThree, 0, wx.ALL, 5) inputThreeSizer.Add(inputTxtThree, 1, wx.ALL|wx.EXPAND, 5) inputFourSizer.Add(inputFourIco, 0, wx.ALL, 5) inputFourSizer.Add(labelFour, 0, wx.ALL, 5) inputFourSizer.Add(inputTxtFour, 1, wx.ALL|wx.EXPAND, 5) btnSizer.Add(okBtn, 0, wx.ALL, 5) btnSizer.Add(cancelBtn, 0, wx.ALL, 5) topSizer.Add(titleSizer, 0, wx.CENTER) topSizer.Add(wx.StaticLine(self.panel,), 0, wx.ALL|wx.EXPAND, 5) topSizer.Add(inputOneSizer, 0, wx.ALL|wx.EXPAND, 5) topSizer.Add(inputTwoSizer, 0, wx.ALL|wx.EXPAND, 5) topSizer.Add(inputThreeSizer, 0, wx.ALL|wx.EXPAND, 5) topSizer.Add(inputFourSizer, 0, wx.ALL|wx.EXPAND, 5) topSizer.Add(wx.StaticLine(self.panel), 0, wx.ALL|wx.EXPAND, 5) topSizer.Add(btnSizer, 0, wx.ALL|wx.CENTER, 5) self.panel.SetSizer(topSizer) topSizer.Fit(self) def onOK(self, event): # Do something print 'onOK handler' def onCancel(self, event): self.closeProgram() def closeProgram(self): self.Close() # Run the program if __name__ == '__main__': app = wx.PySimpleApp() frame = MyForm().Show() app.MainLoop()
Python
# Experiment with wxPython's HtmlWindow # tested with Python24 and wxPython26 vegaseat 17may2006 #!/usr/bin/python import wx import wx.html import os g_panel = None g_frame = None g_html_win = None class ff_app(wx.PySimpleApp): def __init__(self): wx.PySimpleApp.__init__(self) os.chdir("./html") class ff_html_win(wx.html.HtmlWindow): this = None def __init__(self, parent, pos = (0, 1), size = (600,400)): wx.html.HtmlWindow.__init__(self, parent, -1, pos, size) if "gtk2" in wx.PlatformInfo: self.SetStandardFonts() def even_handler(self, event): print ("even_handler:", event) class ff_html_panel(wx.Panel): this = None """ class ff_html_panel inherits wx.Panel and auto load files from html/index.html """ def __init__(self, parent, id): # default pos is (0, 0) and size is (-1, -1) which fills the frame wx.Panel.__init__(self, parent, id) self.SetBackgroundColour("write") self.html_content = "<h2>404 Page Not found ./index.htm</h2>" self.html_win = ff_html_win(self, pos=(0,1), size=(800,600)) global g_html_win g_html_win = self.html_win self.html_win.SetRelatedFrame(parent, parent.GetTitle() + " -- %s") self.html_win.SetRelatedStatusBar(0) def show(self): try: a = file("./index.html") self.html_content = a.read() except: pass self.html_win.SetPage(str(self.html_content)) def even_handler(self, event): print ("even_handler:", event) class ff_html_frame(wx.Frame): this = None def __init__(self, parent, title): wx.Frame.__init__(self, parent, -1, title, size=(800,600)) self.CreateStatusBar() def run(self): global g_panel g_panel = ff_html_panel(self,-1) g_panel.show() def even_handler(self, event): print ("even_handler:", event) class BlueTagHandler(wx.html.HtmlWinTagHandler): this = None def __init__(self): wx.html.HtmlWinTagHandler.__init__(self) def GetSupportedTags(self): return "BUTTON,INPUT,TEXTAREA" def HandleTag(self, tag): tag_name = tag.GetName() if tag_name == "INPUT": return self.HandleInput(tag) elif tag_name == "TEXTAREA": return self.HandleTextarea(tag) def HandleInput(self, tag): global g_html_win type_name = "text" if tag.GetParam("type") : type_name = tag.GetParam("type").lower() list = [] if type_name == "text": inputTxtOne = wx.TextCtrl(g_html_win, wx.ID_ANY, tag.GetParam("value")) list.append(inputTxtOne) elif type_name == "button" or type_name == "submit": button = wx.Button(g_html_win, wx.ID_ANY, tag.GetParam("value")) #g_html_win.bind(wx.EVT_BUTTON, g_html_win.even_handler, button) list.append(button) for k in list: k.Show(True) self.GetParser().GetContainer().InsertCell(wx.html.HtmlWidgetCell(k, 0)) self.ParseInner(tag) return True def HandleTextarea(self, tag): global g_html_win w = long(tag.GetParam("cols")) * 5 h = long(tag.GetParam("rows")) * 20 a = (w, h) print(a) tc = wx.TextCtrl(g_html_win, style=wx.TE_MULTILINE|wx.TE_READONLY, size=(w, h)) self.GetParser().GetContainer().InsertCell(wx.html.HtmlWidgetCell(tc, 0)) self.ParseInner(tag) return True wx.html.HtmlWinParser_AddTagHandler(BlueTagHandler) app = ff_app() # create a window/frame, no parent, -1 is default ID, title, size global g_frame g_frame = ff_html_frame(None, "FFOWN HTML Browser") g_frame.run() # call the derived class, -1 is default ID # show the frame g_frame.Show(True) # start the event loop app.MainLoop()
Python
import wx import wx.html page = """<html><body> This silly example shows how custom tags can be defined and used in a wx.HtmlWindow. We've defined a new tag, <blue> that will change the <blue>foreground color</blue> of the portions of the document that it encloses to some shade of blue. The tag handler can also use parameters specifed in the tag, for example: <ul> <li> <blue shade='sky'>Sky Blue</blue> <li> <blue shade='midnight'>Midnight Blue</blue> <li> <blue shade='dark'>Dark Blue</blue> <li> <blue shade='navy'>Navy Blue</blue> </ul> </body></html> """ class BlueTagHandler(wx.html.HtmlWinTagHandler): def __init__(self): wx.html.HtmlWinTagHandler.__init__(self) def GetSupportedTags(self): return "BLUE" def HandleTag(self, tag): old = self.GetParser().GetActualColor() clr = "#0000FF" if tag.HasParam("SHADE"): shade = tag.GetParam("SHADE") if shade.upper() == "SKY": clr = "#3299CC" if shade.upper() == "MIDNIGHT": clr = "#2F2F4F" elif shade.upper() == "DARK": clr = "#00008B" elif shade.upper == "NAVY": clr = "#23238E" self.GetParser().SetActualColor(clr) self.GetParser().GetContainer().InsertCell(wx.html.HtmlColourCell(clr)) self.ParseInner(tag) self.GetParser().SetActualColor(old) self.GetParser().GetContainer().InsertCell(wx.html.HtmlColourCell(old)) return True wx.html.HtmlWinParser_AddTagHandler(BlueTagHandler) class MyHtmlFrame(wx.Frame): def __init__(self, parent, title): wx.Frame.__init__(self, parent, -1, title) html = wx.html.HtmlWindow(self) if "gtk2" in wx.PlatformInfo: html.SetStandardFonts() html.SetPage(page) app = wx.PySimpleApp() frm = MyHtmlFrame(None, "Custom HTML Tag Handler") frm.Show() app.MainLoop()
Python
import wx class Form(wx.Panel): ''' The Form class is a wx.Panel that creates a bunch of controls and handlers for callbacks. Doing the layout of the controls is the responsibility of subclasses (by means of the doLayout() method). ''' def __init__(self, *args, **kwargs): super(Form, self).__init__(*args, **kwargs) self.referrers = ['friends', 'advertising', 'websearch', 'yellowpages'] self.colors = ['blue', 'red', 'yellow', 'orange', 'green', 'purple', 'navy blue', 'black', 'gray'] self.createControls() self.bindEvents() self.doLayout() def createControls(self): self.logger = wx.TextCtrl(self, style=wx.TE_MULTILINE|wx.TE_READONLY) self.saveButton = wx.Button(self, label="Save") self.nameLabel = wx.StaticText(self, label="Your name:") self.nameTextCtrl = wx.TextCtrl(self, value="Enter here your name") self.referrerLabel = wx.StaticText(self, label="How did you hear from us?") self.referrerComboBox = wx.ComboBox(self, choices=self.referrers, style=wx.CB_DROPDOWN) self.insuranceCheckBox = wx.CheckBox(self, label="Do you want Insured Shipment?") self.colorRadioBox = wx.RadioBox(self, label="What color would you like?", choices=self.colors, majorDimension=3, style=wx.RA_SPECIFY_COLS) def bindEvents(self): for control, event, handler in \ [(self.saveButton, wx.EVT_BUTTON, self.onSave), (self.nameTextCtrl, wx.EVT_TEXT, self.onNameEntered), (self.nameTextCtrl, wx.EVT_CHAR, self.onNameChanged), (self.referrerComboBox, wx.EVT_COMBOBOX, self.onReferrerEntered), (self.referrerComboBox, wx.EVT_TEXT, self.onReferrerEntered), (self.insuranceCheckBox, wx.EVT_CHECKBOX, self.onInsuranceChanged), (self.colorRadioBox, wx.EVT_RADIOBOX, self.onColorchanged)]: control.Bind(event, handler) def doLayout(self): ''' Layout the controls that were created by createControls(). Form.doLayout() will raise a NotImplementedError because it is the responsibility of subclasses to layout the controls. ''' raise NotImplementedError # Callback methods: def onColorchanged(self, event): self.__log('User wants color: %s'%self.colors[event.GetInt()]) def onReferrerEntered(self, event): self.__log('User entered referrer: %s'%event.GetString()) def onSave(self,event): self.__log('User clicked on button with id %d'%event.GetId()) def onNameEntered(self, event): self.__log('User entered name: %s'%event.GetString()) def onNameChanged(self, event): self.__log('User typed character: %d'%event.GetKeyCode()) event.Skip() def onInsuranceChanged(self, event): self.__log('User wants insurance: %s'%bool(event.Checked())) # Helper method(s): def __log(self, message): ''' Private method to append a string to the logger text control. ''' self.logger.AppendText('%s\n'%message) class FormWithAbsolutePositioning(Form): def doLayout(self): ''' Layout the controls by means of absolute positioning. ''' for control, x, y, width, height in \ [(self.logger, 300, 20, 200, 300), (self.nameLabel, 20, 60, -1, -1), (self.nameTextCtrl, 150, 60, 150, -1), (self.referrerLabel, 20, 90, -1, -1), (self.referrerComboBox, 150, 90, 95, -1), (self.insuranceCheckBox, 20, 180, -1, -1), (self.colorRadioBox, 20, 210, -1, -1), (self.saveButton, 200, 300, -1, -1)]: control.SetDimensions(x=x, y=y, width=width, height=height) class FormWithSizer(Form): def doLayout(self): ''' Layout the controls by means of sizers. ''' # A horizontal BoxSizer will contain the GridSizer (on the left) # and the logger text control (on the right): boxSizer = wx.BoxSizer(orient=wx.HORIZONTAL) # A GridSizer will contain the other controls: gridSizer = wx.FlexGridSizer(rows=5, cols=2, vgap=10, hgap=10) # Prepare some reusable arguments for calling sizer.Add(): expandOption = dict(flag=wx.EXPAND) noOptions = dict() emptySpace = ((0, 0), noOptions) # Add the controls to the sizers: for control, options in \ [(self.nameLabel, noOptions), (self.nameTextCtrl, expandOption), (self.referrerLabel, noOptions), (self.referrerComboBox, expandOption), emptySpace, (self.insuranceCheckBox, noOptions), emptySpace, (self.colorRadioBox, noOptions), emptySpace, (self.saveButton, dict(flag=wx.ALIGN_CENTER))]: gridSizer.Add(control, **options) for control, options in \ [(gridSizer, dict(border=5, flag=wx.ALL)), (self.logger, dict(border=5, flag=wx.ALL|wx.EXPAND, proportion=1))]: boxSizer.Add(control, **options) self.SetSizerAndFit(boxSizer) class FrameWithForms(wx.Frame): def __init__(self, *args, **kwargs): super(FrameWithForms, self).__init__(*args, **kwargs) notebook = wx.Notebook(self) form1 = FormWithAbsolutePositioning(notebook) form2 = FormWithSizer(notebook) notebook.AddPage(form1, 'Absolute Positioning') notebook.AddPage(form2, 'Sizers') # We just set the frame to the right size manually. This is feasible # for the frame since the frame contains just one component. If the # frame had contained more than one component, we would use sizers # of course, as demonstrated in the FormWithSizer class above. self.SetClientSize(notebook.GetBestSize()) if __name__ == '__main__': app = wx.App(0) frame = FrameWithForms(None, title='Demo with Notebook') frame.Show() app.MainLoop()
Python
import sys from pylib.inc import * from pylib.src_parser import src_parser_t from pylib.code_generator import code_generator_t if __name__ =='__main__': if len(sys.argv) < 3: print('Usage: %s idl_filename dest_file_name' % (sys.argv[0])) exit(0) idl_filename = sys.argv[1] dest_file_name = sys.argv[2] p = src_parser_t(idl_filename) p.exe() mgr = p.get_struct_def_mgr() mgr.dump() cg = code_generator_t(mgr, dest_file_name) cg.exe()
Python
from pylib.inc import * def convert_to_check_op(t): if t == 'int8' or t == 'int16' or t == 'int32': return 'IsInt' elif t == 'uint8' or t == 'uint16' or t == 'uint32': return 'IsUint' elif t == 'int64': return 'IsInt64' elif t == 'UInt64': return 'IsUint64' elif t == 'float': return 'IsDouble' elif t == 'string': return 'IsString' elif t == 'array': return 'IsArray' elif t == 'dictionary': return 'IsObject' else: return 'IsObject' def convert_to_fetch_op(t, var_name = 'tmp_val', j_var = 'val'): if t == 'int8' or t == 'int16' or t == 'int32': return '%s = %s.GetInt()' % (var_name, j_var) elif t == 'uint8' or t == 'uint16' or t == 'uint32': return '%s = %s.GetUint()' % (var_name, j_var) elif t == 'int64': return '%s = %s.GetInt64()' % (var_name, j_var) elif t == 'uint64': return '%s = %s.GetUint64()' % (var_name, j_var) elif t == 'float': return '%s = %s.GetDouble();' % (var_name, j_var) elif t == 'string': return '%s = %s.GetString()' % (var_name, j_var) else: return '%s.parse(%s)' % (var_name, j_var) inc_str = ''' #ifndef _IDL_DEF_I_ #define _IDL_DEF_I_ #include <stdint.h> #include <string> #include <vector> #include <map> #include <stdexcept> #include <iostream> using namespace std; #include "rapidjson/document.h" // rapidjson's DOM-style API #include "rapidjson/prettywriter.h" // for stringify JSON #include "rapidjson/filestream.h" // wrapper of C stream for prettywriter as output #include "json_instream.h" #include "json_outstream.h" #include "rapidjson/stringbuffer.h" #include "smart_ptr/shared_ptr.h" //! using namespace rapidjson; using namespace ff; typedef runtime_error msg_exception_t; typedef rapidjson::Document json_dom_t; typedef rapidjson::Value json_value_t; typedef int8_t int8; typedef uint8_t uint8; typedef int16_t int16; typedef uint16_t uint16; typedef int32_t int32; typedef uint32_t uint32; typedef int64_t int64; typedef uint64_t uint64; struct msg_t { virtual ~msg_t(){} virtual string encode_json() const = 0; }; typedef shared_ptr_t<msg_t> msg_ptr_t; ''' class code_generator_t: def __init__(self, struct_def_mgr, dest_filename): self.struct_def_mgr = struct_def_mgr self.dest_filename = dest_filename def gen_class_def_code(self, f): tmp_s = ''' template<typename T, typename R> class msg_dispather_t { typedef R socket_ptr_t; typedef int (msg_dispather_t<T, R>::*reg_func_t)(const json_value_t&, socket_ptr_t); public: msg_dispather_t(T& msg_handler_): m_msg_handler(msg_handler_) { ''' for struct in self.struct_def_mgr.get_all_struct(): if -1 != struct.find('ret_t'): continue tmp_s += ''' m_reg_func["%s"] = &msg_dispather_t<T, R>::%s_dispacher; ''' % (struct, struct) tmp_s += '\n }\n' tmp_s += ''' int dispath(const string& json_, socket_ptr_t sock_) { json_dom_t document; // Default template parameter uses UTF8 and MemoryPoolAllocator. if (document.Parse<0>(json_.c_str()).HasParseError()) { throw msg_exception_t("json format not right"); } if (false == document.IsObject() && false == document.Empty()) { throw msg_exception_t("json must has one field"); } const json_value_t& val = document.MemberBegin()->name; const char* func_name = val.GetString(); typename map<string, reg_func_t>::const_iterator it = m_reg_func.find(func_name); if (it == m_reg_func.end()) { char buff[512]; snprintf(buff, sizeof(buff), "msg not supported<%s>", func_name); throw msg_exception_t(buff); return -1; } reg_func_t func = it->second; (this->*func)(document.MemberBegin()->value, sock_); return 0; } ''' for struct in self.struct_def_mgr.get_all_struct(): if -1 != struct.find('ret_t'): continue tmp_s += ''' int %s_dispacher(const json_value_t& jval_, socket_ptr_t sock_) { shared_ptr_t<%s> ret_val(new %s()); ret_val->parse(jval_); m_msg_handler.handle(ret_val, sock_); return 0; } ''' % (struct, struct, struct) tmp_s += ''' private: T& m_msg_handler; map<string, reg_func_t> m_reg_func; }; ''' f.write(tmp_s) def format_field_declare_code(self, field_def, prefix = ''): type_str = field_def.get_type() field_name = field_def.get_name() key_type = field_def.get_key_type() val_type = field_def.get_val_type() ret = prefix if val_type != '': ret = ret + 'map<%s, %s> %s;' %(key_type, val_type, field_name) elif key_type != '': ret = ret + 'vector<%s> %s;' %(key_type, field_name) else: ret = ret + '%s %s;' %(type_str, field_name) return ret def format_struct_declare_code(self, struct_def, prefix = ''): struct_name = struct_def.get_name() all_sub_struct = struct_def.get_all_struct() all_fields = struct_def.get_all_field() ret = '' + prefix ret += 'struct %s : public msg_t {\n' %(struct_name) for sub_struct in all_sub_struct: ret = ret + self.format_struct_declare_code(sub_struct, prefix + ' ') + '\n' for field_name in all_fields: ret = ret + self.format_field_declare_code(all_fields[field_name], prefix + ' ') + '\n' ret = ret + prefix + ' int parse(const json_value_t& jval_) {\n' ret += ''' json_instream_t in("%s"); in''' % (struct_name) for field_name in all_fields: ret += '.decode("%s", jval_["%s"], %s)' % (field_name, field_name, field_name) ret += ';\n' ret += prefix + ' return 0;\n' + prefix + ' }\n' ret += ''' string encode_json() const { rapidjson::Document::AllocatorType allocator; rapidjson::StringBuffer str_buff; json_value_t ibj_json(rapidjson::kObjectType); json_value_t ret_json(rapidjson::kObjectType); this->encode_json_val(ibj_json, allocator); ret_json.AddMember("%s", ibj_json, allocator); rapidjson::Writer<rapidjson::StringBuffer> writer(str_buff, &allocator); ret_json.Accept(writer); string output(str_buff.GetString(), str_buff.GetSize()); return output; } \n''' % (struct_name) ret += prefix + ' int encode_json_val(json_value_t& dest, rapidjson::Document::AllocatorType& allocator) const{\n' ret += ''' json_outstream_t out(allocator); out''' for field_name in all_fields: ret += '.encode("%s", dest, %s)' % (field_name, field_name) ret += ';\n' ret += prefix + ' return 0;\n' + prefix + ' }\n' ret = ret + '\n' + prefix + '};\n' return ret def gen_declare_code(self, f): f.write(inc_str) all_struct = self.struct_def_mgr.get_all_struct() for struct_name in all_struct: cur_struct = all_struct[struct_name] all_sub_struct = cur_struct.get_all_struct() ret_str = self.format_struct_declare_code(cur_struct) #print(ret_str) f.write(ret_str) def exe(self): f = open(self.dest_filename, "w") self.gen_declare_code(f) self.gen_class_def_code(f) f.write('\n#endif\n')
Python
from pylib.inc import * class src_parser_t: def __init__(self, file): self.file = file self.struct_def_mgr = struct_def_mgr_t() self.file_content = '' self.all_words = [] f = open(file) self.file_content = f.read() f.close() def get_struct_def_mgr(self): return self.struct_def_mgr def parse_to_words(self): all_line = self.file_content.split('\n') for line in all_line: words = line.split(' ') for w in words: w = w.strip() if w != '': self.all_words.append(w) def build_struct_relation(self): struct_stack = [] index = 0 while index < len(self.all_words): if len(struct_stack) < 1: struct_stack.append(self.struct_def_mgr) parent_struct = struct_stack[len(struct_stack) - 1] cur_word = self.all_words[index] if cur_word == 'struct': struct_def = struct_def_t(self.all_words[index + 1]) parent_struct.add_struct(struct_def) struct_stack.append(struct_def) index = index + 1 elif cur_word == '}' or cur_word == '};': struct_stack.pop() elif cur_word == 'int8' or cur_word == 'int16' or cur_word == 'int32' or \ cur_word == 'float' or cur_word == 'string': field_name = self.all_words[index + 1].split(';')[0] field = field_def_t(field_name, cur_word, '', '') parent_struct.add_field(field) index = index + 1 else: if -1 == cur_word.find('dictionary') and -1 == cur_word.find('{') and -1 == cur_word.find('array') : field_name = self.all_words[index + 1].split(';')[0] field = field_def_t(field_name, cur_word, '', '') parent_struct.add_field(field) index = index + 1 else: field_type = '' field_name = '' key_type = '' val_type = '' if -1 != cur_word.find('array'): field_name = self.all_words[index + 1].split(';')[0] word_split = cur_word.split('<') field_type = word_split[0] key_type = word_split[1].split('>')[0] field = field_def_t(field_name, field_type, key_type, '') parent_struct.add_field(field) index = index + 1 elif -1 != cur_word.find('dictionary'): field_name = self.all_words[index + 1].split(';')[0] word_split = cur_word.split('<') field_type = word_split[0] key_val_type = word_split[1].split('>') key_type = key_val_type[0].split(',')[0] val_type = key_val_type[0].split(',')[1] field = field_def_t(field_name, field_type, key_type, val_type) parent_struct.add_field(field) index = index + 1 index = index + 1 def exe(self): self.parse_to_words() self.build_struct_relation()
Python
class field_def_t: def __init__(self, name, type, key_type, val_type_): self.name = name self.parent = None self.type = type self.key_type = key_type self.val_type = val_type_ def get_name(self): return self.name def get_parent(self): return self.parent def set_parent(self, p): self.parent = p def get_type(self): return self.type def get_key_type(self): return self.key_type def get_val_type(self): return self.val_type def dump(self, prefix = ''): print(prefix, self.name, self.type, self.key_type, self.val_type) class struct_def_t: def __init__(self, name, parent = None): self.name = name self.parent = parent self.all_fields = {} self.sub_struct = [] def get_name(self): return self.name def get_parent(self): return self.parent def set_parent(self, parent): self.parent = parent def add_field(self, field_def_): self.all_fields[field_def_.get_name()] = field_def_ field_def_.set_parent(self) def add_struct(self, struct_def_): self.sub_struct.append(struct_def_) struct_def_.set_parent(self) def get_all_struct(self): return self.sub_struct def get_all_field(self): return self.all_fields def get_parent(self): return self.parent def has_field(self, name): if None == self.all_fields.get(name): return False return True def dump(self, prefix = ''): print(prefix, self.name, 'include struct:') for struct in self.sub_struct: struct.dump(prefix + " ") print(prefix, self.name, "include fields:") for field in self.all_fields: self.all_fields[field].dump(prefix + " ") class struct_def_mgr_t: def __init__(self): self.all_struct = {} def get_name(self): return '' def add_struct(self, struct_def_): self.all_struct[struct_def_.get_name()] = struct_def_ struct_def_.set_parent(None) def get_all_struct(self): return self.all_struct def get_struct(self, name): return self.all_struct[name] def get_parent(self): return '' def dump(self): for name in self.all_struct: self.all_struct[name].dump()
Python
import channel def handle_msg(channel_, msg_): print(channel_, msg_) channel.send(channel_, msg_) def handle_broken(channel_): print(channel_) print("load end ok ....")
Python
import socket import struct import time import thread import threading import sys import traceback class client_t: uid = 0 def __init__(self, host_, port_, handler_): self.host = host_ self.port = port_ self.handler = handler_ self.mutex = threading.Lock() self.status = "broken" def handle_broken(self): self.close() self.status = "broken" self.handler.handle_broken(self) #print "handle_broken::handle_broken" def connect(self): try: self.socket = socket.socket() self.socket.connect((self.host, self.port)) self.status = "ok" except: self.handle_broken() def dump(self): print "host:port", self.host, self.port def send_msg(self, cmd_, content_): self.mutex.acquire() try: #head = struct.pack('IHH', len(content_), cmd_, 0) dest = str(len(content_)) + '\r\n' + content_ self.socket.sendall(dest.encode()) #self.socket.sendall((head.decode() + content_).encode()) except: print("send msg error", sys.exc_info()) self.handle_broken() self.mutex.release() def read_some(self): try: buff = self.socket.recv(1024*8) dest = buff.split('\r\n') if len(dest) == 2: self.handler.handle_msg(self, dest[0], dest[1]) except: print("read_some error", sys.exc_info()) self.handle_broken() def close(self): self.socket.close() def loop(self, xx): loop = 10 while loop > 0 and self.status != "broken": loop = loop - 1 self.read_some() def run(self): thread.start_new_thread(self.loop, (self,)) class msg_handler_t: def handle_broken(self, client_): print "msg_handler_t:handle_broken xXX" def handle_msg(self, client_, cmd_, content_): print(content_) try: result = eval(content_) register_dict = { "user_login_ret_t" : self.handle_login, "echo_result" : self.handle_echo } for key in result: if register_dict.get(key) != None: register_dict[key](client_, result[key]) except: print "handle_msgXXX....cmd:", cmd_, "not supported!", "body:", content_ return def handle_login(self, client_, result_): print "handle_login...uid:", result_['uid'] pass def handle_echo(self, client_, result_): print "handle_echo...content:<", result_['content'], ">" pass def handle_broadcast(): pass def test(): host = "127.0.0.1" port = 10241 h = msg_handler_t() c = client_t(host, port, h) cmd = 0 c.connect() c.send_msg(cmd, '{"login_req_t":{"uid":123}}') c.dump() c.read_some() c.run() get_cmd(c) def get_cmd(c): cmd = 1 while cmd: cmd = input("input cmd 1 chat to other:") if 1 == cmd: c.send_msg(cmd, '{"chat_to_some_req_t":{"dest_uids":[321],"content":"oh nice"}}') else: print(cmd, "not support") def exe(cmd): shell_cmd = cmd + ' > /tmp/tmp_result' os.system(shell_cmd) f = open('/tmp/tmp_result') result = f.read() return result if __name__ == "__main__": test()
Python
#!/usr/bin/env python # # Copyright 2006, 2007 Google Inc. All Rights Reserved. # Author: danderson@google.com (David Anderson) # # Script for uploading files to a Google Code project. # # This is intended to be both a useful script for people who want to # streamline project uploads and a reference implementation for # uploading files to Google Code projects. # # To upload a file to Google Code, you need to provide a path to the # file on your local machine, a small summary of what the file is, a # project name, and a valid account that is a member or owner of that # project. You can optionally provide a list of labels that apply to # the file. The file will be uploaded under the same name that it has # in your local filesystem (that is, the "basename" or last path # component). Run the script with '--help' to get the exact syntax # and available options. # # Note that the upload script requests that you enter your # googlecode.com password. This is NOT your Gmail account password! # This is the password you use on googlecode.com for committing to # Subversion and uploading files. You can find your password by going # to http://code.google.com/hosting/settings when logged in with your # Gmail account. If you have already committed to your project's # Subversion repository, the script will automatically retrieve your # credentials from there (unless disabled, see the output of '--help' # for details). # # If you are looking at this script as a reference for implementing # your own Google Code file uploader, then you should take a look at # the upload() function, which is the meat of the uploader. You # basically need to build a multipart/form-data POST request with the # right fields and send it to https://PROJECT.googlecode.com/files . # Authenticate the request using HTTP Basic authentication, as is # shown below. # # Licensed under the terms of the Apache Software License 2.0: # http://www.apache.org/licenses/LICENSE-2.0 # # Questions, comments, feature requests and patches are most welcome. # Please direct all of these to the Google Code users group: # http://groups.google.com/group/google-code-hosting """Google Code file uploader script. """ __author__ = 'danderson@google.com (David Anderson)' import httplib import os.path import optparse import getpass import base64 import sys def upload(file, project_name, user_name, password, summary, labels=None): """Upload a file to a Google Code project's file server. Args: file: The local path to the file. project_name: The name of your project on Google Code. user_name: Your Google account name. password: The googlecode.com password for your account. Note that this is NOT your global Google Account password! summary: A small description for the file. labels: an optional list of label strings with which to tag the file. Returns: a tuple: http_status: 201 if the upload succeeded, something else if an error occured. http_reason: The human-readable string associated with http_status file_url: If the upload succeeded, the URL of the file on Google Code, None otherwise. """ # The login is the user part of user@gmail.com. If the login provided # is in the full user@domain form, strip it down. if user_name.endswith('@gmail.com'): user_name = user_name[:user_name.index('@gmail.com')] form_fields = [('summary', summary)] if labels is not None: form_fields.extend([('label', l.strip()) for l in labels]) content_type, body = encode_upload_request(form_fields, file) upload_host = '%s.googlecode.com' % project_name upload_uri = '/files' auth_token = base64.b64encode('%s:%s'% (user_name, password)) headers = { 'Authorization': 'Basic %s' % auth_token, 'User-Agent': 'Googlecode.com uploader v0.9.4', 'Content-Type': content_type, } server = httplib.HTTPSConnection(upload_host) server.request('POST', upload_uri, body, headers) resp = server.getresponse() server.close() if resp.status == 201: location = resp.getheader('Location', None) else: location = None return resp.status, resp.reason, location def encode_upload_request(fields, file_path): """Encode the given fields and file into a multipart form body. fields is a sequence of (name, value) pairs. file is the path of the file to upload. The file will be uploaded to Google Code with the same file name. Returns: (content_type, body) ready for httplib.HTTP instance """ BOUNDARY = '----------Googlecode_boundary_reindeer_flotilla' CRLF = '\r\n' body = [] # Add the metadata about the upload first for key, value in fields: body.extend( ['--' + BOUNDARY, 'Content-Disposition: form-data; name="%s"' % key, '', value, ]) # Now add the file itself file_name = os.path.basename(file_path) f = open(file_path, 'rb') file_content = f.read() f.close() body.extend( ['--' + BOUNDARY, 'Content-Disposition: form-data; name="filename"; filename="%s"' % file_name, # The upload server determines the mime-type, no need to set it. 'Content-Type: application/octet-stream', '', file_content, ]) # Finalize the form body body.extend(['--' + BOUNDARY + '--', '']) return 'multipart/form-data; boundary=%s' % BOUNDARY, CRLF.join(body) def upload_find_auth(file_path, project_name, summary, labels=None, user_name=None, password=None, tries=3): """Find credentials and upload a file to a Google Code project's file server. file_path, project_name, summary, and labels are passed as-is to upload. Args: file_path: The local path to the file. project_name: The name of your project on Google Code. summary: A small description for the file. labels: an optional list of label strings with which to tag the file. config_dir: Path to Subversion configuration directory, 'none', or None. user_name: Your Google account name. tries: How many attempts to make. """ while tries > 0: if user_name is None: # Read username if not specified or loaded from svn config, or on # subsequent tries. sys.stdout.write('Please enter your googlecode.com username: ') sys.stdout.flush() user_name = sys.stdin.readline().rstrip() if password is None: # Read password if not loaded from svn config, or on subsequent tries. print 'Please enter your googlecode.com password.' print '** Note that this is NOT your Gmail account password! **' print 'It is the password you use to access Subversion repositories,' print 'and can be found here: http://code.google.com/hosting/settings' password = getpass.getpass() status, reason, url = upload(file_path, project_name, user_name, password, summary, labels) # Returns 403 Forbidden instead of 401 Unauthorized for bad # credentials as of 2007-07-17. if status in [httplib.FORBIDDEN, httplib.UNAUTHORIZED]: # Rest for another try. user_name = password = None tries = tries - 1 else: # We're done. break return status, reason, url def main(): parser = optparse.OptionParser(usage='googlecode-upload.py -s SUMMARY ' '-p PROJECT [options] FILE') parser.add_option('-s', '--summary', dest='summary', help='Short description of the file') parser.add_option('-p', '--project', dest='project', help='Google Code project name') parser.add_option('-u', '--user', dest='user', help='Your Google Code username') parser.add_option('-w', '--password', dest='password', help='Your Google Code password') parser.add_option('-l', '--labels', dest='labels', help='An optional list of labels to attach to the file') options, args = parser.parse_args() if not options.summary: parser.error('File summary is missing.') elif not options.project: parser.error('Project name is missing.') elif len(args) < 1: parser.error('File to upload not provided.') elif len(args) > 1: parser.error('Only one file may be specified.') file_path = args[0] if options.labels: labels = options.labels.split(',') else: labels = None status, reason, url = upload_find_auth(file_path, options.project, options.summary, labels, options.user, options.password) if url: print 'The file was uploaded successfully.' print 'URL: %s' % url return 0 else: print 'An error occurred. Your file was not uploaded.' print 'Google Code upload server said: %s (%s)' % (reason, status) return 1 if __name__ == '__main__': sys.exit(main())
Python
#!/usr/bin/env python # # Copyright 2006, 2007 Google Inc. All Rights Reserved. # Author: danderson@google.com (David Anderson) # # Script for uploading files to a Google Code project. # # This is intended to be both a useful script for people who want to # streamline project uploads and a reference implementation for # uploading files to Google Code projects. # # To upload a file to Google Code, you need to provide a path to the # file on your local machine, a small summary of what the file is, a # project name, and a valid account that is a member or owner of that # project. You can optionally provide a list of labels that apply to # the file. The file will be uploaded under the same name that it has # in your local filesystem (that is, the "basename" or last path # component). Run the script with '--help' to get the exact syntax # and available options. # # Note that the upload script requests that you enter your # googlecode.com password. This is NOT your Gmail account password! # This is the password you use on googlecode.com for committing to # Subversion and uploading files. You can find your password by going # to http://code.google.com/hosting/settings when logged in with your # Gmail account. If you have already committed to your project's # Subversion repository, the script will automatically retrieve your # credentials from there (unless disabled, see the output of '--help' # for details). # # If you are looking at this script as a reference for implementing # your own Google Code file uploader, then you should take a look at # the upload() function, which is the meat of the uploader. You # basically need to build a multipart/form-data POST request with the # right fields and send it to https://PROJECT.googlecode.com/files . # Authenticate the request using HTTP Basic authentication, as is # shown below. # # Licensed under the terms of the Apache Software License 2.0: # http://www.apache.org/licenses/LICENSE-2.0 # # Questions, comments, feature requests and patches are most welcome. # Please direct all of these to the Google Code users group: # http://groups.google.com/group/google-code-hosting """Google Code file uploader script. """ __author__ = 'danderson@google.com (David Anderson)' import httplib import os.path import optparse import getpass import base64 import sys def upload(file, project_name, user_name, password, summary, labels=None): """Upload a file to a Google Code project's file server. Args: file: The local path to the file. project_name: The name of your project on Google Code. user_name: Your Google account name. password: The googlecode.com password for your account. Note that this is NOT your global Google Account password! summary: A small description for the file. labels: an optional list of label strings with which to tag the file. Returns: a tuple: http_status: 201 if the upload succeeded, something else if an error occured. http_reason: The human-readable string associated with http_status file_url: If the upload succeeded, the URL of the file on Google Code, None otherwise. """ # The login is the user part of user@gmail.com. If the login provided # is in the full user@domain form, strip it down. if user_name.endswith('@gmail.com'): user_name = user_name[:user_name.index('@gmail.com')] form_fields = [('summary', summary)] if labels is not None: form_fields.extend([('label', l.strip()) for l in labels]) content_type, body = encode_upload_request(form_fields, file) upload_host = '%s.googlecode.com' % project_name upload_uri = '/files' auth_token = base64.b64encode('%s:%s'% (user_name, password)) headers = { 'Authorization': 'Basic %s' % auth_token, 'User-Agent': 'Googlecode.com uploader v0.9.4', 'Content-Type': content_type, } server = httplib.HTTPSConnection(upload_host) server.request('POST', upload_uri, body, headers) resp = server.getresponse() server.close() if resp.status == 201: location = resp.getheader('Location', None) else: location = None return resp.status, resp.reason, location def encode_upload_request(fields, file_path): """Encode the given fields and file into a multipart form body. fields is a sequence of (name, value) pairs. file is the path of the file to upload. The file will be uploaded to Google Code with the same file name. Returns: (content_type, body) ready for httplib.HTTP instance """ BOUNDARY = '----------Googlecode_boundary_reindeer_flotilla' CRLF = '\r\n' body = [] # Add the metadata about the upload first for key, value in fields: body.extend( ['--' + BOUNDARY, 'Content-Disposition: form-data; name="%s"' % key, '', value, ]) # Now add the file itself file_name = os.path.basename(file_path) f = open(file_path, 'rb') file_content = f.read() f.close() body.extend( ['--' + BOUNDARY, 'Content-Disposition: form-data; name="filename"; filename="%s"' % file_name, # The upload server determines the mime-type, no need to set it. 'Content-Type: application/octet-stream', '', file_content, ]) # Finalize the form body body.extend(['--' + BOUNDARY + '--', '']) return 'multipart/form-data; boundary=%s' % BOUNDARY, CRLF.join(body) def upload_find_auth(file_path, project_name, summary, labels=None, user_name=None, password=None, tries=3): """Find credentials and upload a file to a Google Code project's file server. file_path, project_name, summary, and labels are passed as-is to upload. Args: file_path: The local path to the file. project_name: The name of your project on Google Code. summary: A small description for the file. labels: an optional list of label strings with which to tag the file. config_dir: Path to Subversion configuration directory, 'none', or None. user_name: Your Google account name. tries: How many attempts to make. """ while tries > 0: if user_name is None: # Read username if not specified or loaded from svn config, or on # subsequent tries. sys.stdout.write('Please enter your googlecode.com username: ') sys.stdout.flush() user_name = sys.stdin.readline().rstrip() if password is None: # Read password if not loaded from svn config, or on subsequent tries. print 'Please enter your googlecode.com password.' print '** Note that this is NOT your Gmail account password! **' print 'It is the password you use to access Subversion repositories,' print 'and can be found here: http://code.google.com/hosting/settings' password = getpass.getpass() status, reason, url = upload(file_path, project_name, user_name, password, summary, labels) # Returns 403 Forbidden instead of 401 Unauthorized for bad # credentials as of 2007-07-17. if status in [httplib.FORBIDDEN, httplib.UNAUTHORIZED]: # Rest for another try. user_name = password = None tries = tries - 1 else: # We're done. break return status, reason, url def main(): parser = optparse.OptionParser(usage='googlecode-upload.py -s SUMMARY ' '-p PROJECT [options] FILE') parser.add_option('-s', '--summary', dest='summary', help='Short description of the file') parser.add_option('-p', '--project', dest='project', help='Google Code project name') parser.add_option('-u', '--user', dest='user', help='Your Google Code username') parser.add_option('-w', '--password', dest='password', help='Your Google Code password') parser.add_option('-l', '--labels', dest='labels', help='An optional list of labels to attach to the file') options, args = parser.parse_args() if not options.summary: parser.error('File summary is missing.') elif not options.project: parser.error('Project name is missing.') elif len(args) < 1: parser.error('File to upload not provided.') elif len(args) > 1: parser.error('Only one file may be specified.') file_path = args[0] if options.labels: labels = options.labels.split(',') else: labels = None status, reason, url = upload_find_auth(file_path, options.project, options.summary, labels, options.user, options.password) if url: print 'The file was uploaded successfully.' print 'URL: %s' % url return 0 else: print 'An error occurred. Your file was not uploaded.' print 'Google Code upload server said: %s (%s)' % (reason, status) return 1 if __name__ == '__main__': sys.exit(main())
Python
#!/usr/bin/env python # # Copyright 2006, 2007 Google Inc. All Rights Reserved. # Author: danderson@google.com (David Anderson) # # Script for uploading files to a Google Code project. # # This is intended to be both a useful script for people who want to # streamline project uploads and a reference implementation for # uploading files to Google Code projects. # # To upload a file to Google Code, you need to provide a path to the # file on your local machine, a small summary of what the file is, a # project name, and a valid account that is a member or owner of that # project. You can optionally provide a list of labels that apply to # the file. The file will be uploaded under the same name that it has # in your local filesystem (that is, the "basename" or last path # component). Run the script with '--help' to get the exact syntax # and available options. # # Note that the upload script requests that you enter your # googlecode.com password. This is NOT your Gmail account password! # This is the password you use on googlecode.com for committing to # Subversion and uploading files. You can find your password by going # to http://code.google.com/hosting/settings when logged in with your # Gmail account. If you have already committed to your project's # Subversion repository, the script will automatically retrieve your # credentials from there (unless disabled, see the output of '--help' # for details). # # If you are looking at this script as a reference for implementing # your own Google Code file uploader, then you should take a look at # the upload() function, which is the meat of the uploader. You # basically need to build a multipart/form-data POST request with the # right fields and send it to https://PROJECT.googlecode.com/files . # Authenticate the request using HTTP Basic authentication, as is # shown below. # # Licensed under the terms of the Apache Software License 2.0: # http://www.apache.org/licenses/LICENSE-2.0 # # Questions, comments, feature requests and patches are most welcome. # Please direct all of these to the Google Code users group: # http://groups.google.com/group/google-code-hosting """Google Code file uploader script. """ __author__ = 'danderson@google.com (David Anderson)' import httplib import os.path import optparse import getpass import base64 import sys def upload(file, project_name, user_name, password, summary, labels=None): """Upload a file to a Google Code project's file server. Args: file: The local path to the file. project_name: The name of your project on Google Code. user_name: Your Google account name. password: The googlecode.com password for your account. Note that this is NOT your global Google Account password! summary: A small description for the file. labels: an optional list of label strings with which to tag the file. Returns: a tuple: http_status: 201 if the upload succeeded, something else if an error occured. http_reason: The human-readable string associated with http_status file_url: If the upload succeeded, the URL of the file on Google Code, None otherwise. """ # The login is the user part of user@gmail.com. If the login provided # is in the full user@domain form, strip it down. if user_name.endswith('@gmail.com'): user_name = user_name[:user_name.index('@gmail.com')] form_fields = [('summary', summary)] if labels is not None: form_fields.extend([('label', l.strip()) for l in labels]) content_type, body = encode_upload_request(form_fields, file) upload_host = '%s.googlecode.com' % project_name upload_uri = '/files' auth_token = base64.b64encode('%s:%s'% (user_name, password)) headers = { 'Authorization': 'Basic %s' % auth_token, 'User-Agent': 'Googlecode.com uploader v0.9.4', 'Content-Type': content_type, } server = httplib.HTTPSConnection(upload_host) server.request('POST', upload_uri, body, headers) resp = server.getresponse() server.close() if resp.status == 201: location = resp.getheader('Location', None) else: location = None return resp.status, resp.reason, location def encode_upload_request(fields, file_path): """Encode the given fields and file into a multipart form body. fields is a sequence of (name, value) pairs. file is the path of the file to upload. The file will be uploaded to Google Code with the same file name. Returns: (content_type, body) ready for httplib.HTTP instance """ BOUNDARY = '----------Googlecode_boundary_reindeer_flotilla' CRLF = '\r\n' body = [] # Add the metadata about the upload first for key, value in fields: body.extend( ['--' + BOUNDARY, 'Content-Disposition: form-data; name="%s"' % key, '', value, ]) # Now add the file itself file_name = os.path.basename(file_path) f = open(file_path, 'rb') file_content = f.read() f.close() body.extend( ['--' + BOUNDARY, 'Content-Disposition: form-data; name="filename"; filename="%s"' % file_name, # The upload server determines the mime-type, no need to set it. 'Content-Type: application/octet-stream', '', file_content, ]) # Finalize the form body body.extend(['--' + BOUNDARY + '--', '']) return 'multipart/form-data; boundary=%s' % BOUNDARY, CRLF.join(body) def upload_find_auth(file_path, project_name, summary, labels=None, user_name=None, password=None, tries=3): """Find credentials and upload a file to a Google Code project's file server. file_path, project_name, summary, and labels are passed as-is to upload. Args: file_path: The local path to the file. project_name: The name of your project on Google Code. summary: A small description for the file. labels: an optional list of label strings with which to tag the file. config_dir: Path to Subversion configuration directory, 'none', or None. user_name: Your Google account name. tries: How many attempts to make. """ while tries > 0: if user_name is None: # Read username if not specified or loaded from svn config, or on # subsequent tries. sys.stdout.write('Please enter your googlecode.com username: ') sys.stdout.flush() user_name = sys.stdin.readline().rstrip() if password is None: # Read password if not loaded from svn config, or on subsequent tries. print 'Please enter your googlecode.com password.' print '** Note that this is NOT your Gmail account password! **' print 'It is the password you use to access Subversion repositories,' print 'and can be found here: http://code.google.com/hosting/settings' password = getpass.getpass() status, reason, url = upload(file_path, project_name, user_name, password, summary, labels) # Returns 403 Forbidden instead of 401 Unauthorized for bad # credentials as of 2007-07-17. if status in [httplib.FORBIDDEN, httplib.UNAUTHORIZED]: # Rest for another try. user_name = password = None tries = tries - 1 else: # We're done. break return status, reason, url def main(): parser = optparse.OptionParser(usage='googlecode-upload.py -s SUMMARY ' '-p PROJECT [options] FILE') parser.add_option('-s', '--summary', dest='summary', help='Short description of the file') parser.add_option('-p', '--project', dest='project', help='Google Code project name') parser.add_option('-u', '--user', dest='user', help='Your Google Code username') parser.add_option('-w', '--password', dest='password', help='Your Google Code password') parser.add_option('-l', '--labels', dest='labels', help='An optional list of labels to attach to the file') options, args = parser.parse_args() if not options.summary: parser.error('File summary is missing.') elif not options.project: parser.error('Project name is missing.') elif len(args) < 1: parser.error('File to upload not provided.') elif len(args) > 1: parser.error('Only one file may be specified.') file_path = args[0] if options.labels: labels = options.labels.split(',') else: labels = None status, reason, url = upload_find_auth(file_path, options.project, options.summary, labels, options.user, options.password) if url: print 'The file was uploaded successfully.' print 'URL: %s' % url return 0 else: print 'An error occurred. Your file was not uploaded.' print 'Google Code upload server said: %s (%s)' % (reason, status) return 1 if __name__ == '__main__': sys.exit(main())
Python
#!/usr/bin/env python # # Copyright 2006, 2007 Google Inc. All Rights Reserved. # Author: danderson@google.com (David Anderson) # # Script for uploading files to a Google Code project. # # This is intended to be both a useful script for people who want to # streamline project uploads and a reference implementation for # uploading files to Google Code projects. # # To upload a file to Google Code, you need to provide a path to the # file on your local machine, a small summary of what the file is, a # project name, and a valid account that is a member or owner of that # project. You can optionally provide a list of labels that apply to # the file. The file will be uploaded under the same name that it has # in your local filesystem (that is, the "basename" or last path # component). Run the script with '--help' to get the exact syntax # and available options. # # Note that the upload script requests that you enter your # googlecode.com password. This is NOT your Gmail account password! # This is the password you use on googlecode.com for committing to # Subversion and uploading files. You can find your password by going # to http://code.google.com/hosting/settings when logged in with your # Gmail account. If you have already committed to your project's # Subversion repository, the script will automatically retrieve your # credentials from there (unless disabled, see the output of '--help' # for details). # # If you are looking at this script as a reference for implementing # your own Google Code file uploader, then you should take a look at # the upload() function, which is the meat of the uploader. You # basically need to build a multipart/form-data POST request with the # right fields and send it to https://PROJECT.googlecode.com/files . # Authenticate the request using HTTP Basic authentication, as is # shown below. # # Licensed under the terms of the Apache Software License 2.0: # http://www.apache.org/licenses/LICENSE-2.0 # # Questions, comments, feature requests and patches are most welcome. # Please direct all of these to the Google Code users group: # http://groups.google.com/group/google-code-hosting """Google Code file uploader script. """ __author__ = 'danderson@google.com (David Anderson)' import httplib import os.path import optparse import getpass import base64 import sys def upload(file, project_name, user_name, password, summary, labels=None): """Upload a file to a Google Code project's file server. Args: file: The local path to the file. project_name: The name of your project on Google Code. user_name: Your Google account name. password: The googlecode.com password for your account. Note that this is NOT your global Google Account password! summary: A small description for the file. labels: an optional list of label strings with which to tag the file. Returns: a tuple: http_status: 201 if the upload succeeded, something else if an error occured. http_reason: The human-readable string associated with http_status file_url: If the upload succeeded, the URL of the file on Google Code, None otherwise. """ # The login is the user part of user@gmail.com. If the login provided # is in the full user@domain form, strip it down. if user_name.endswith('@gmail.com'): user_name = user_name[:user_name.index('@gmail.com')] form_fields = [('summary', summary)] if labels is not None: form_fields.extend([('label', l.strip()) for l in labels]) content_type, body = encode_upload_request(form_fields, file) upload_host = '%s.googlecode.com' % project_name upload_uri = '/files' auth_token = base64.b64encode('%s:%s'% (user_name, password)) headers = { 'Authorization': 'Basic %s' % auth_token, 'User-Agent': 'Googlecode.com uploader v0.9.4', 'Content-Type': content_type, } server = httplib.HTTPSConnection(upload_host) server.request('POST', upload_uri, body, headers) resp = server.getresponse() server.close() if resp.status == 201: location = resp.getheader('Location', None) else: location = None return resp.status, resp.reason, location def encode_upload_request(fields, file_path): """Encode the given fields and file into a multipart form body. fields is a sequence of (name, value) pairs. file is the path of the file to upload. The file will be uploaded to Google Code with the same file name. Returns: (content_type, body) ready for httplib.HTTP instance """ BOUNDARY = '----------Googlecode_boundary_reindeer_flotilla' CRLF = '\r\n' body = [] # Add the metadata about the upload first for key, value in fields: body.extend( ['--' + BOUNDARY, 'Content-Disposition: form-data; name="%s"' % key, '', value, ]) # Now add the file itself file_name = os.path.basename(file_path) f = open(file_path, 'rb') file_content = f.read() f.close() body.extend( ['--' + BOUNDARY, 'Content-Disposition: form-data; name="filename"; filename="%s"' % file_name, # The upload server determines the mime-type, no need to set it. 'Content-Type: application/octet-stream', '', file_content, ]) # Finalize the form body body.extend(['--' + BOUNDARY + '--', '']) return 'multipart/form-data; boundary=%s' % BOUNDARY, CRLF.join(body) def upload_find_auth(file_path, project_name, summary, labels=None, user_name=None, password=None, tries=3): """Find credentials and upload a file to a Google Code project's file server. file_path, project_name, summary, and labels are passed as-is to upload. Args: file_path: The local path to the file. project_name: The name of your project on Google Code. summary: A small description for the file. labels: an optional list of label strings with which to tag the file. config_dir: Path to Subversion configuration directory, 'none', or None. user_name: Your Google account name. tries: How many attempts to make. """ while tries > 0: if user_name is None: # Read username if not specified or loaded from svn config, or on # subsequent tries. sys.stdout.write('Please enter your googlecode.com username: ') sys.stdout.flush() user_name = sys.stdin.readline().rstrip() if password is None: # Read password if not loaded from svn config, or on subsequent tries. print 'Please enter your googlecode.com password.' print '** Note that this is NOT your Gmail account password! **' print 'It is the password you use to access Subversion repositories,' print 'and can be found here: http://code.google.com/hosting/settings' password = getpass.getpass() status, reason, url = upload(file_path, project_name, user_name, password, summary, labels) # Returns 403 Forbidden instead of 401 Unauthorized for bad # credentials as of 2007-07-17. if status in [httplib.FORBIDDEN, httplib.UNAUTHORIZED]: # Rest for another try. user_name = password = None tries = tries - 1 else: # We're done. break return status, reason, url def main(): parser = optparse.OptionParser(usage='googlecode-upload.py -s SUMMARY ' '-p PROJECT [options] FILE') parser.add_option('-s', '--summary', dest='summary', help='Short description of the file') parser.add_option('-p', '--project', dest='project', help='Google Code project name') parser.add_option('-u', '--user', dest='user', help='Your Google Code username') parser.add_option('-w', '--password', dest='password', help='Your Google Code password') parser.add_option('-l', '--labels', dest='labels', help='An optional list of labels to attach to the file') options, args = parser.parse_args() if not options.summary: parser.error('File summary is missing.') elif not options.project: parser.error('Project name is missing.') elif len(args) < 1: parser.error('File to upload not provided.') elif len(args) > 1: parser.error('Only one file may be specified.') file_path = args[0] if options.labels: labels = options.labels.split(',') else: labels = None status, reason, url = upload_find_auth(file_path, options.project, options.summary, labels, options.user, options.password) if url: print 'The file was uploaded successfully.' print 'URL: %s' % url return 0 else: print 'An error occurred. Your file was not uploaded.' print 'Google Code upload server said: %s (%s)' % (reason, status) return 1 if __name__ == '__main__': sys.exit(main())
Python
#!/usr/bin/env python # # Copyright 2006, 2007 Google Inc. All Rights Reserved. # Author: danderson@google.com (David Anderson) # # Script for uploading files to a Google Code project. # # This is intended to be both a useful script for people who want to # streamline project uploads and a reference implementation for # uploading files to Google Code projects. # # To upload a file to Google Code, you need to provide a path to the # file on your local machine, a small summary of what the file is, a # project name, and a valid account that is a member or owner of that # project. You can optionally provide a list of labels that apply to # the file. The file will be uploaded under the same name that it has # in your local filesystem (that is, the "basename" or last path # component). Run the script with '--help' to get the exact syntax # and available options. # # Note that the upload script requests that you enter your # googlecode.com password. This is NOT your Gmail account password! # This is the password you use on googlecode.com for committing to # Subversion and uploading files. You can find your password by going # to http://code.google.com/hosting/settings when logged in with your # Gmail account. If you have already committed to your project's # Subversion repository, the script will automatically retrieve your # credentials from there (unless disabled, see the output of '--help' # for details). # # If you are looking at this script as a reference for implementing # your own Google Code file uploader, then you should take a look at # the upload() function, which is the meat of the uploader. You # basically need to build a multipart/form-data POST request with the # right fields and send it to https://PROJECT.googlecode.com/files . # Authenticate the request using HTTP Basic authentication, as is # shown below. # # Licensed under the terms of the Apache Software License 2.0: # http://www.apache.org/licenses/LICENSE-2.0 # # Questions, comments, feature requests and patches are most welcome. # Please direct all of these to the Google Code users group: # http://groups.google.com/group/google-code-hosting """Google Code file uploader script. """ __author__ = 'danderson@google.com (David Anderson)' import httplib import os.path import optparse import getpass import base64 import sys def upload(file, project_name, user_name, password, summary, labels=None): """Upload a file to a Google Code project's file server. Args: file: The local path to the file. project_name: The name of your project on Google Code. user_name: Your Google account name. password: The googlecode.com password for your account. Note that this is NOT your global Google Account password! summary: A small description for the file. labels: an optional list of label strings with which to tag the file. Returns: a tuple: http_status: 201 if the upload succeeded, something else if an error occured. http_reason: The human-readable string associated with http_status file_url: If the upload succeeded, the URL of the file on Google Code, None otherwise. """ # The login is the user part of user@gmail.com. If the login provided # is in the full user@domain form, strip it down. if user_name.endswith('@gmail.com'): user_name = user_name[:user_name.index('@gmail.com')] form_fields = [('summary', summary)] if labels is not None: form_fields.extend([('label', l.strip()) for l in labels]) content_type, body = encode_upload_request(form_fields, file) upload_host = '%s.googlecode.com' % project_name upload_uri = '/files' auth_token = base64.b64encode('%s:%s'% (user_name, password)) headers = { 'Authorization': 'Basic %s' % auth_token, 'User-Agent': 'Googlecode.com uploader v0.9.4', 'Content-Type': content_type, } server = httplib.HTTPSConnection(upload_host) server.request('POST', upload_uri, body, headers) resp = server.getresponse() server.close() if resp.status == 201: location = resp.getheader('Location', None) else: location = None return resp.status, resp.reason, location def encode_upload_request(fields, file_path): """Encode the given fields and file into a multipart form body. fields is a sequence of (name, value) pairs. file is the path of the file to upload. The file will be uploaded to Google Code with the same file name. Returns: (content_type, body) ready for httplib.HTTP instance """ BOUNDARY = '----------Googlecode_boundary_reindeer_flotilla' CRLF = '\r\n' body = [] # Add the metadata about the upload first for key, value in fields: body.extend( ['--' + BOUNDARY, 'Content-Disposition: form-data; name="%s"' % key, '', value, ]) # Now add the file itself file_name = os.path.basename(file_path) f = open(file_path, 'rb') file_content = f.read() f.close() body.extend( ['--' + BOUNDARY, 'Content-Disposition: form-data; name="filename"; filename="%s"' % file_name, # The upload server determines the mime-type, no need to set it. 'Content-Type: application/octet-stream', '', file_content, ]) # Finalize the form body body.extend(['--' + BOUNDARY + '--', '']) return 'multipart/form-data; boundary=%s' % BOUNDARY, CRLF.join(body) def upload_find_auth(file_path, project_name, summary, labels=None, user_name=None, password=None, tries=3): """Find credentials and upload a file to a Google Code project's file server. file_path, project_name, summary, and labels are passed as-is to upload. Args: file_path: The local path to the file. project_name: The name of your project on Google Code. summary: A small description for the file. labels: an optional list of label strings with which to tag the file. config_dir: Path to Subversion configuration directory, 'none', or None. user_name: Your Google account name. tries: How many attempts to make. """ while tries > 0: if user_name is None: # Read username if not specified or loaded from svn config, or on # subsequent tries. sys.stdout.write('Please enter your googlecode.com username: ') sys.stdout.flush() user_name = sys.stdin.readline().rstrip() if password is None: # Read password if not loaded from svn config, or on subsequent tries. print 'Please enter your googlecode.com password.' print '** Note that this is NOT your Gmail account password! **' print 'It is the password you use to access Subversion repositories,' print 'and can be found here: http://code.google.com/hosting/settings' password = getpass.getpass() status, reason, url = upload(file_path, project_name, user_name, password, summary, labels) # Returns 403 Forbidden instead of 401 Unauthorized for bad # credentials as of 2007-07-17. if status in [httplib.FORBIDDEN, httplib.UNAUTHORIZED]: # Rest for another try. user_name = password = None tries = tries - 1 else: # We're done. break return status, reason, url def main(): parser = optparse.OptionParser(usage='googlecode-upload.py -s SUMMARY ' '-p PROJECT [options] FILE') parser.add_option('-s', '--summary', dest='summary', help='Short description of the file') parser.add_option('-p', '--project', dest='project', help='Google Code project name') parser.add_option('-u', '--user', dest='user', help='Your Google Code username') parser.add_option('-w', '--password', dest='password', help='Your Google Code password') parser.add_option('-l', '--labels', dest='labels', help='An optional list of labels to attach to the file') options, args = parser.parse_args() if not options.summary: parser.error('File summary is missing.') elif not options.project: parser.error('Project name is missing.') elif len(args) < 1: parser.error('File to upload not provided.') elif len(args) > 1: parser.error('Only one file may be specified.') file_path = args[0] if options.labels: labels = options.labels.split(',') else: labels = None status, reason, url = upload_find_auth(file_path, options.project, options.summary, labels, options.user, options.password) if url: print 'The file was uploaded successfully.' print 'URL: %s' % url return 0 else: print 'An error occurred. Your file was not uploaded.' print 'Google Code upload server said: %s (%s)' % (reason, status) return 1 if __name__ == '__main__': sys.exit(main())
Python
#!/usr/bin/env python # # Copyright 2006, 2007 Google Inc. All Rights Reserved. # Author: danderson@google.com (David Anderson) # # Script for uploading files to a Google Code project. # # This is intended to be both a useful script for people who want to # streamline project uploads and a reference implementation for # uploading files to Google Code projects. # # To upload a file to Google Code, you need to provide a path to the # file on your local machine, a small summary of what the file is, a # project name, and a valid account that is a member or owner of that # project. You can optionally provide a list of labels that apply to # the file. The file will be uploaded under the same name that it has # in your local filesystem (that is, the "basename" or last path # component). Run the script with '--help' to get the exact syntax # and available options. # # Note that the upload script requests that you enter your # googlecode.com password. This is NOT your Gmail account password! # This is the password you use on googlecode.com for committing to # Subversion and uploading files. You can find your password by going # to http://code.google.com/hosting/settings when logged in with your # Gmail account. If you have already committed to your project's # Subversion repository, the script will automatically retrieve your # credentials from there (unless disabled, see the output of '--help' # for details). # # If you are looking at this script as a reference for implementing # your own Google Code file uploader, then you should take a look at # the upload() function, which is the meat of the uploader. You # basically need to build a multipart/form-data POST request with the # right fields and send it to https://PROJECT.googlecode.com/files . # Authenticate the request using HTTP Basic authentication, as is # shown below. # # Licensed under the terms of the Apache Software License 2.0: # http://www.apache.org/licenses/LICENSE-2.0 # # Questions, comments, feature requests and patches are most welcome. # Please direct all of these to the Google Code users group: # http://groups.google.com/group/google-code-hosting """Google Code file uploader script. """ __author__ = 'danderson@google.com (David Anderson)' import httplib import os.path import optparse import getpass import base64 import sys def upload(file, project_name, user_name, password, summary, labels=None): """Upload a file to a Google Code project's file server. Args: file: The local path to the file. project_name: The name of your project on Google Code. user_name: Your Google account name. password: The googlecode.com password for your account. Note that this is NOT your global Google Account password! summary: A small description for the file. labels: an optional list of label strings with which to tag the file. Returns: a tuple: http_status: 201 if the upload succeeded, something else if an error occured. http_reason: The human-readable string associated with http_status file_url: If the upload succeeded, the URL of the file on Google Code, None otherwise. """ # The login is the user part of user@gmail.com. If the login provided # is in the full user@domain form, strip it down. if user_name.endswith('@gmail.com'): user_name = user_name[:user_name.index('@gmail.com')] form_fields = [('summary', summary)] if labels is not None: form_fields.extend([('label', l.strip()) for l in labels]) content_type, body = encode_upload_request(form_fields, file) upload_host = '%s.googlecode.com' % project_name upload_uri = '/files' auth_token = base64.b64encode('%s:%s'% (user_name, password)) headers = { 'Authorization': 'Basic %s' % auth_token, 'User-Agent': 'Googlecode.com uploader v0.9.4', 'Content-Type': content_type, } server = httplib.HTTPSConnection(upload_host) server.request('POST', upload_uri, body, headers) resp = server.getresponse() server.close() if resp.status == 201: location = resp.getheader('Location', None) else: location = None return resp.status, resp.reason, location def encode_upload_request(fields, file_path): """Encode the given fields and file into a multipart form body. fields is a sequence of (name, value) pairs. file is the path of the file to upload. The file will be uploaded to Google Code with the same file name. Returns: (content_type, body) ready for httplib.HTTP instance """ BOUNDARY = '----------Googlecode_boundary_reindeer_flotilla' CRLF = '\r\n' body = [] # Add the metadata about the upload first for key, value in fields: body.extend( ['--' + BOUNDARY, 'Content-Disposition: form-data; name="%s"' % key, '', value, ]) # Now add the file itself file_name = os.path.basename(file_path) f = open(file_path, 'rb') file_content = f.read() f.close() body.extend( ['--' + BOUNDARY, 'Content-Disposition: form-data; name="filename"; filename="%s"' % file_name, # The upload server determines the mime-type, no need to set it. 'Content-Type: application/octet-stream', '', file_content, ]) # Finalize the form body body.extend(['--' + BOUNDARY + '--', '']) return 'multipart/form-data; boundary=%s' % BOUNDARY, CRLF.join(body) def upload_find_auth(file_path, project_name, summary, labels=None, user_name=None, password=None, tries=3): """Find credentials and upload a file to a Google Code project's file server. file_path, project_name, summary, and labels are passed as-is to upload. Args: file_path: The local path to the file. project_name: The name of your project on Google Code. summary: A small description for the file. labels: an optional list of label strings with which to tag the file. config_dir: Path to Subversion configuration directory, 'none', or None. user_name: Your Google account name. tries: How many attempts to make. """ while tries > 0: if user_name is None: # Read username if not specified or loaded from svn config, or on # subsequent tries. sys.stdout.write('Please enter your googlecode.com username: ') sys.stdout.flush() user_name = sys.stdin.readline().rstrip() if password is None: # Read password if not loaded from svn config, or on subsequent tries. print 'Please enter your googlecode.com password.' print '** Note that this is NOT your Gmail account password! **' print 'It is the password you use to access Subversion repositories,' print 'and can be found here: http://code.google.com/hosting/settings' password = getpass.getpass() status, reason, url = upload(file_path, project_name, user_name, password, summary, labels) # Returns 403 Forbidden instead of 401 Unauthorized for bad # credentials as of 2007-07-17. if status in [httplib.FORBIDDEN, httplib.UNAUTHORIZED]: # Rest for another try. user_name = password = None tries = tries - 1 else: # We're done. break return status, reason, url def main(): parser = optparse.OptionParser(usage='googlecode-upload.py -s SUMMARY ' '-p PROJECT [options] FILE') parser.add_option('-s', '--summary', dest='summary', help='Short description of the file') parser.add_option('-p', '--project', dest='project', help='Google Code project name') parser.add_option('-u', '--user', dest='user', help='Your Google Code username') parser.add_option('-w', '--password', dest='password', help='Your Google Code password') parser.add_option('-l', '--labels', dest='labels', help='An optional list of labels to attach to the file') options, args = parser.parse_args() if not options.summary: parser.error('File summary is missing.') elif not options.project: parser.error('Project name is missing.') elif len(args) < 1: parser.error('File to upload not provided.') elif len(args) > 1: parser.error('Only one file may be specified.') file_path = args[0] if options.labels: labels = options.labels.split(',') else: labels = None status, reason, url = upload_find_auth(file_path, options.project, options.summary, labels, options.user, options.password) if url: print 'The file was uploaded successfully.' print 'URL: %s' % url return 0 else: print 'An error occurred. Your file was not uploaded.' print 'Google Code upload server said: %s (%s)' % (reason, status) return 1 if __name__ == '__main__': sys.exit(main())
Python