id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
16,600
openid/python-openid
examples/djopenid/server/views.py
processTrustResult
def processTrustResult(request): """ Handle the result of a trust decision and respond to the RP accordingly. """ # Get the request from the session so we can construct the # appropriate response. openid_request = getRequest(request) # The identifier that this server can vouch for response_identity = getViewURL(request, idPage) # If the decision was to allow the verification, respond # accordingly. allowed = 'allow' in request.POST # Generate a response with the appropriate answer. openid_response = openid_request.answer(allowed, identity=response_identity) # Send Simple Registration data in the response, if appropriate. if allowed: sreg_data = { 'fullname': 'Example User', 'nickname': 'example', 'dob': '1970-01-01', 'email': 'invalid@example.com', 'gender': 'F', 'postcode': '12345', 'country': 'ES', 'language': 'eu', 'timezone': 'America/New_York', } sreg_req = sreg.SRegRequest.fromOpenIDRequest(openid_request) sreg_resp = sreg.SRegResponse.extractResponse(sreg_req, sreg_data) openid_response.addExtension(sreg_resp) pape_response = pape.Response() pape_response.setAuthLevel(pape.LEVELS_NIST, 0) openid_response.addExtension(pape_response) return displayResponse(request, openid_response)
python
def processTrustResult(request): """ Handle the result of a trust decision and respond to the RP accordingly. """ # Get the request from the session so we can construct the # appropriate response. openid_request = getRequest(request) # The identifier that this server can vouch for response_identity = getViewURL(request, idPage) # If the decision was to allow the verification, respond # accordingly. allowed = 'allow' in request.POST # Generate a response with the appropriate answer. openid_response = openid_request.answer(allowed, identity=response_identity) # Send Simple Registration data in the response, if appropriate. if allowed: sreg_data = { 'fullname': 'Example User', 'nickname': 'example', 'dob': '1970-01-01', 'email': 'invalid@example.com', 'gender': 'F', 'postcode': '12345', 'country': 'ES', 'language': 'eu', 'timezone': 'America/New_York', } sreg_req = sreg.SRegRequest.fromOpenIDRequest(openid_request) sreg_resp = sreg.SRegResponse.extractResponse(sreg_req, sreg_data) openid_response.addExtension(sreg_resp) pape_response = pape.Response() pape_response.setAuthLevel(pape.LEVELS_NIST, 0) openid_response.addExtension(pape_response) return displayResponse(request, openid_response)
[ "def", "processTrustResult", "(", "request", ")", ":", "# Get the request from the session so we can construct the", "# appropriate response.", "openid_request", "=", "getRequest", "(", "request", ")", "# The identifier that this server can vouch for", "response_identity", "=", "getViewURL", "(", "request", ",", "idPage", ")", "# If the decision was to allow the verification, respond", "# accordingly.", "allowed", "=", "'allow'", "in", "request", ".", "POST", "# Generate a response with the appropriate answer.", "openid_response", "=", "openid_request", ".", "answer", "(", "allowed", ",", "identity", "=", "response_identity", ")", "# Send Simple Registration data in the response, if appropriate.", "if", "allowed", ":", "sreg_data", "=", "{", "'fullname'", ":", "'Example User'", ",", "'nickname'", ":", "'example'", ",", "'dob'", ":", "'1970-01-01'", ",", "'email'", ":", "'invalid@example.com'", ",", "'gender'", ":", "'F'", ",", "'postcode'", ":", "'12345'", ",", "'country'", ":", "'ES'", ",", "'language'", ":", "'eu'", ",", "'timezone'", ":", "'America/New_York'", ",", "}", "sreg_req", "=", "sreg", ".", "SRegRequest", ".", "fromOpenIDRequest", "(", "openid_request", ")", "sreg_resp", "=", "sreg", ".", "SRegResponse", ".", "extractResponse", "(", "sreg_req", ",", "sreg_data", ")", "openid_response", ".", "addExtension", "(", "sreg_resp", ")", "pape_response", "=", "pape", ".", "Response", "(", ")", "pape_response", ".", "setAuthLevel", "(", "pape", ".", "LEVELS_NIST", ",", "0", ")", "openid_response", ".", "addExtension", "(", "pape_response", ")", "return", "displayResponse", "(", "request", ",", "openid_response", ")" ]
Handle the result of a trust decision and respond to the RP accordingly.
[ "Handle", "the", "result", "of", "a", "trust", "decision", "and", "respond", "to", "the", "RP", "accordingly", "." ]
f7e13536f0d1828d3cef5ae7a7b55cabadff37fc
https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/examples/djopenid/server/views.py#L208-L250
16,601
openid/python-openid
admin/builddiscover.py
buildDiscover
def buildDiscover(base_url, out_dir): """Convert all files in a directory to apache mod_asis files in another directory.""" test_data = discoverdata.readTests(discoverdata.default_test_file) def writeTestFile(test_name): template = test_data[test_name] data = discoverdata.fillTemplate( test_name, template, base_url, discoverdata.example_xrds) out_file_name = os.path.join(out_dir, test_name) out_file = file(out_file_name, 'w') out_file.write(data) manifest = [manifest_header] for success, input_name, id_name, result_name in discoverdata.testlist: if not success: continue writeTestFile(input_name) input_url = urlparse.urljoin(base_url, input_name) id_url = urlparse.urljoin(base_url, id_name) result_url = urlparse.urljoin(base_url, result_name) manifest.append('\t'.join((input_url, id_url, result_url))) manifest.append('\n') manifest_file_name = os.path.join(out_dir, 'manifest.txt') manifest_file = file(manifest_file_name, 'w') for chunk in manifest: manifest_file.write(chunk) manifest_file.close()
python
def buildDiscover(base_url, out_dir): """Convert all files in a directory to apache mod_asis files in another directory.""" test_data = discoverdata.readTests(discoverdata.default_test_file) def writeTestFile(test_name): template = test_data[test_name] data = discoverdata.fillTemplate( test_name, template, base_url, discoverdata.example_xrds) out_file_name = os.path.join(out_dir, test_name) out_file = file(out_file_name, 'w') out_file.write(data) manifest = [manifest_header] for success, input_name, id_name, result_name in discoverdata.testlist: if not success: continue writeTestFile(input_name) input_url = urlparse.urljoin(base_url, input_name) id_url = urlparse.urljoin(base_url, id_name) result_url = urlparse.urljoin(base_url, result_name) manifest.append('\t'.join((input_url, id_url, result_url))) manifest.append('\n') manifest_file_name = os.path.join(out_dir, 'manifest.txt') manifest_file = file(manifest_file_name, 'w') for chunk in manifest: manifest_file.write(chunk) manifest_file.close()
[ "def", "buildDiscover", "(", "base_url", ",", "out_dir", ")", ":", "test_data", "=", "discoverdata", ".", "readTests", "(", "discoverdata", ".", "default_test_file", ")", "def", "writeTestFile", "(", "test_name", ")", ":", "template", "=", "test_data", "[", "test_name", "]", "data", "=", "discoverdata", ".", "fillTemplate", "(", "test_name", ",", "template", ",", "base_url", ",", "discoverdata", ".", "example_xrds", ")", "out_file_name", "=", "os", ".", "path", ".", "join", "(", "out_dir", ",", "test_name", ")", "out_file", "=", "file", "(", "out_file_name", ",", "'w'", ")", "out_file", ".", "write", "(", "data", ")", "manifest", "=", "[", "manifest_header", "]", "for", "success", ",", "input_name", ",", "id_name", ",", "result_name", "in", "discoverdata", ".", "testlist", ":", "if", "not", "success", ":", "continue", "writeTestFile", "(", "input_name", ")", "input_url", "=", "urlparse", ".", "urljoin", "(", "base_url", ",", "input_name", ")", "id_url", "=", "urlparse", ".", "urljoin", "(", "base_url", ",", "id_name", ")", "result_url", "=", "urlparse", ".", "urljoin", "(", "base_url", ",", "result_name", ")", "manifest", ".", "append", "(", "'\\t'", ".", "join", "(", "(", "input_url", ",", "id_url", ",", "result_url", ")", ")", ")", "manifest", ".", "append", "(", "'\\n'", ")", "manifest_file_name", "=", "os", ".", "path", ".", "join", "(", "out_dir", ",", "'manifest.txt'", ")", "manifest_file", "=", "file", "(", "manifest_file_name", ",", "'w'", ")", "for", "chunk", "in", "manifest", ":", "manifest_file", ".", "write", "(", "chunk", ")", "manifest_file", ".", "close", "(", ")" ]
Convert all files in a directory to apache mod_asis files in another directory.
[ "Convert", "all", "files", "in", "a", "directory", "to", "apache", "mod_asis", "files", "in", "another", "directory", "." ]
f7e13536f0d1828d3cef5ae7a7b55cabadff37fc
https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/admin/builddiscover.py#L31-L63
16,602
openid/python-openid
openid/store/memstore.py
ServerAssocs.best
def best(self): """Returns association with the oldest issued date. or None if there are no associations. """ best = None for assoc in self.assocs.values(): if best is None or best.issued < assoc.issued: best = assoc return best
python
def best(self): """Returns association with the oldest issued date. or None if there are no associations. """ best = None for assoc in self.assocs.values(): if best is None or best.issued < assoc.issued: best = assoc return best
[ "def", "best", "(", "self", ")", ":", "best", "=", "None", "for", "assoc", "in", "self", ".", "assocs", ".", "values", "(", ")", ":", "if", "best", "is", "None", "or", "best", ".", "issued", "<", "assoc", ".", "issued", ":", "best", "=", "assoc", "return", "best" ]
Returns association with the oldest issued date. or None if there are no associations.
[ "Returns", "association", "with", "the", "oldest", "issued", "date", "." ]
f7e13536f0d1828d3cef5ae7a7b55cabadff37fc
https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/store/memstore.py#L26-L35
16,603
openid/python-openid
openid/store/nonce.py
split
def split(nonce_string): """Extract a timestamp from the given nonce string @param nonce_string: the nonce from which to extract the timestamp @type nonce_string: str @returns: A pair of a Unix timestamp and the salt characters @returntype: (int, str) @raises ValueError: if the nonce does not start with a correctly formatted time string """ timestamp_str = nonce_string[:time_str_len] try: timestamp = timegm(strptime(timestamp_str, time_fmt)) except AssertionError: # Python 2.2 timestamp = -1 if timestamp < 0: raise ValueError('time out of range') return timestamp, nonce_string[time_str_len:]
python
def split(nonce_string): """Extract a timestamp from the given nonce string @param nonce_string: the nonce from which to extract the timestamp @type nonce_string: str @returns: A pair of a Unix timestamp and the salt characters @returntype: (int, str) @raises ValueError: if the nonce does not start with a correctly formatted time string """ timestamp_str = nonce_string[:time_str_len] try: timestamp = timegm(strptime(timestamp_str, time_fmt)) except AssertionError: # Python 2.2 timestamp = -1 if timestamp < 0: raise ValueError('time out of range') return timestamp, nonce_string[time_str_len:]
[ "def", "split", "(", "nonce_string", ")", ":", "timestamp_str", "=", "nonce_string", "[", ":", "time_str_len", "]", "try", ":", "timestamp", "=", "timegm", "(", "strptime", "(", "timestamp_str", ",", "time_fmt", ")", ")", "except", "AssertionError", ":", "# Python 2.2", "timestamp", "=", "-", "1", "if", "timestamp", "<", "0", ":", "raise", "ValueError", "(", "'time out of range'", ")", "return", "timestamp", ",", "nonce_string", "[", "time_str_len", ":", "]" ]
Extract a timestamp from the given nonce string @param nonce_string: the nonce from which to extract the timestamp @type nonce_string: str @returns: A pair of a Unix timestamp and the salt characters @returntype: (int, str) @raises ValueError: if the nonce does not start with a correctly formatted time string
[ "Extract", "a", "timestamp", "from", "the", "given", "nonce", "string" ]
f7e13536f0d1828d3cef5ae7a7b55cabadff37fc
https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/store/nonce.py#L22-L41
16,604
openid/python-openid
openid/store/nonce.py
checkTimestamp
def checkTimestamp(nonce_string, allowed_skew=SKEW, now=None): """Is the timestamp that is part of the specified nonce string within the allowed clock-skew of the current time? @param nonce_string: The nonce that is being checked @type nonce_string: str @param allowed_skew: How many seconds should be allowed for completing the request, allowing for clock skew. @type allowed_skew: int @param now: The current time, as a Unix timestamp @type now: int @returntype: bool @returns: Whether the timestamp is correctly formatted and within the allowed skew of the current time. """ try: stamp, _ = split(nonce_string) except ValueError: return False else: if now is None: now = time() # Time after which we should not use the nonce past = now - allowed_skew # Time that is too far in the future for us to allow future = now + allowed_skew # the stamp is not too far in the future and is not too far in # the past return past <= stamp <= future
python
def checkTimestamp(nonce_string, allowed_skew=SKEW, now=None): """Is the timestamp that is part of the specified nonce string within the allowed clock-skew of the current time? @param nonce_string: The nonce that is being checked @type nonce_string: str @param allowed_skew: How many seconds should be allowed for completing the request, allowing for clock skew. @type allowed_skew: int @param now: The current time, as a Unix timestamp @type now: int @returntype: bool @returns: Whether the timestamp is correctly formatted and within the allowed skew of the current time. """ try: stamp, _ = split(nonce_string) except ValueError: return False else: if now is None: now = time() # Time after which we should not use the nonce past = now - allowed_skew # Time that is too far in the future for us to allow future = now + allowed_skew # the stamp is not too far in the future and is not too far in # the past return past <= stamp <= future
[ "def", "checkTimestamp", "(", "nonce_string", ",", "allowed_skew", "=", "SKEW", ",", "now", "=", "None", ")", ":", "try", ":", "stamp", ",", "_", "=", "split", "(", "nonce_string", ")", "except", "ValueError", ":", "return", "False", "else", ":", "if", "now", "is", "None", ":", "now", "=", "time", "(", ")", "# Time after which we should not use the nonce", "past", "=", "now", "-", "allowed_skew", "# Time that is too far in the future for us to allow", "future", "=", "now", "+", "allowed_skew", "# the stamp is not too far in the future and is not too far in", "# the past", "return", "past", "<=", "stamp", "<=", "future" ]
Is the timestamp that is part of the specified nonce string within the allowed clock-skew of the current time? @param nonce_string: The nonce that is being checked @type nonce_string: str @param allowed_skew: How many seconds should be allowed for completing the request, allowing for clock skew. @type allowed_skew: int @param now: The current time, as a Unix timestamp @type now: int @returntype: bool @returns: Whether the timestamp is correctly formatted and within the allowed skew of the current time.
[ "Is", "the", "timestamp", "that", "is", "part", "of", "the", "specified", "nonce", "string", "within", "the", "allowed", "clock", "-", "skew", "of", "the", "current", "time?" ]
f7e13536f0d1828d3cef5ae7a7b55cabadff37fc
https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/store/nonce.py#L43-L77
16,605
openid/python-openid
openid/store/nonce.py
mkNonce
def mkNonce(when=None): """Generate a nonce with the current timestamp @param when: Unix timestamp representing the issue time of the nonce. Defaults to the current time. @type when: int @returntype: str @returns: A string that should be usable as a one-way nonce @see: time """ salt = cryptutil.randomString(6, NONCE_CHARS) if when is None: t = gmtime() else: t = gmtime(when) time_str = strftime(time_fmt, t) return time_str + salt
python
def mkNonce(when=None): """Generate a nonce with the current timestamp @param when: Unix timestamp representing the issue time of the nonce. Defaults to the current time. @type when: int @returntype: str @returns: A string that should be usable as a one-way nonce @see: time """ salt = cryptutil.randomString(6, NONCE_CHARS) if when is None: t = gmtime() else: t = gmtime(when) time_str = strftime(time_fmt, t) return time_str + salt
[ "def", "mkNonce", "(", "when", "=", "None", ")", ":", "salt", "=", "cryptutil", ".", "randomString", "(", "6", ",", "NONCE_CHARS", ")", "if", "when", "is", "None", ":", "t", "=", "gmtime", "(", ")", "else", ":", "t", "=", "gmtime", "(", "when", ")", "time_str", "=", "strftime", "(", "time_fmt", ",", "t", ")", "return", "time_str", "+", "salt" ]
Generate a nonce with the current timestamp @param when: Unix timestamp representing the issue time of the nonce. Defaults to the current time. @type when: int @returntype: str @returns: A string that should be usable as a one-way nonce @see: time
[ "Generate", "a", "nonce", "with", "the", "current", "timestamp" ]
f7e13536f0d1828d3cef5ae7a7b55cabadff37fc
https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/store/nonce.py#L79-L98
16,606
openid/python-openid
openid/fetchers.py
fetch
def fetch(url, body=None, headers=None): """Invoke the fetch method on the default fetcher. Most users should need only this method. @raises Exception: any exceptions that may be raised by the default fetcher """ fetcher = getDefaultFetcher() return fetcher.fetch(url, body, headers)
python
def fetch(url, body=None, headers=None): """Invoke the fetch method on the default fetcher. Most users should need only this method. @raises Exception: any exceptions that may be raised by the default fetcher """ fetcher = getDefaultFetcher() return fetcher.fetch(url, body, headers)
[ "def", "fetch", "(", "url", ",", "body", "=", "None", ",", "headers", "=", "None", ")", ":", "fetcher", "=", "getDefaultFetcher", "(", ")", "return", "fetcher", ".", "fetch", "(", "url", ",", "body", ",", "headers", ")" ]
Invoke the fetch method on the default fetcher. Most users should need only this method. @raises Exception: any exceptions that may be raised by the default fetcher
[ "Invoke", "the", "fetch", "method", "on", "the", "default", "fetcher", ".", "Most", "users", "should", "need", "only", "this", "method", "." ]
f7e13536f0d1828d3cef5ae7a7b55cabadff37fc
https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/fetchers.py#L35-L42
16,607
openid/python-openid
openid/fetchers.py
setDefaultFetcher
def setDefaultFetcher(fetcher, wrap_exceptions=True): """Set the default fetcher @param fetcher: The fetcher to use as the default HTTP fetcher @type fetcher: HTTPFetcher @param wrap_exceptions: Whether to wrap exceptions thrown by the fetcher wil HTTPFetchingError so that they may be caught easier. By default, exceptions will be wrapped. In general, unwrapped fetchers are useful for debugging of fetching errors or if your fetcher raises well-known exceptions that you would like to catch. @type wrap_exceptions: bool """ global _default_fetcher if fetcher is None or not wrap_exceptions: _default_fetcher = fetcher else: _default_fetcher = ExceptionWrappingFetcher(fetcher)
python
def setDefaultFetcher(fetcher, wrap_exceptions=True): """Set the default fetcher @param fetcher: The fetcher to use as the default HTTP fetcher @type fetcher: HTTPFetcher @param wrap_exceptions: Whether to wrap exceptions thrown by the fetcher wil HTTPFetchingError so that they may be caught easier. By default, exceptions will be wrapped. In general, unwrapped fetchers are useful for debugging of fetching errors or if your fetcher raises well-known exceptions that you would like to catch. @type wrap_exceptions: bool """ global _default_fetcher if fetcher is None or not wrap_exceptions: _default_fetcher = fetcher else: _default_fetcher = ExceptionWrappingFetcher(fetcher)
[ "def", "setDefaultFetcher", "(", "fetcher", ",", "wrap_exceptions", "=", "True", ")", ":", "global", "_default_fetcher", "if", "fetcher", "is", "None", "or", "not", "wrap_exceptions", ":", "_default_fetcher", "=", "fetcher", "else", ":", "_default_fetcher", "=", "ExceptionWrappingFetcher", "(", "fetcher", ")" ]
Set the default fetcher @param fetcher: The fetcher to use as the default HTTP fetcher @type fetcher: HTTPFetcher @param wrap_exceptions: Whether to wrap exceptions thrown by the fetcher wil HTTPFetchingError so that they may be caught easier. By default, exceptions will be wrapped. In general, unwrapped fetchers are useful for debugging of fetching errors or if your fetcher raises well-known exceptions that you would like to catch. @type wrap_exceptions: bool
[ "Set", "the", "default", "fetcher" ]
f7e13536f0d1828d3cef5ae7a7b55cabadff37fc
https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/fetchers.py#L74-L92
16,608
openid/python-openid
openid/fetchers.py
usingCurl
def usingCurl(): """Whether the currently set HTTP fetcher is a Curl HTTP fetcher.""" fetcher = getDefaultFetcher() if isinstance(fetcher, ExceptionWrappingFetcher): fetcher = fetcher.fetcher return isinstance(fetcher, CurlHTTPFetcher)
python
def usingCurl(): """Whether the currently set HTTP fetcher is a Curl HTTP fetcher.""" fetcher = getDefaultFetcher() if isinstance(fetcher, ExceptionWrappingFetcher): fetcher = fetcher.fetcher return isinstance(fetcher, CurlHTTPFetcher)
[ "def", "usingCurl", "(", ")", ":", "fetcher", "=", "getDefaultFetcher", "(", ")", "if", "isinstance", "(", "fetcher", ",", "ExceptionWrappingFetcher", ")", ":", "fetcher", "=", "fetcher", ".", "fetcher", "return", "isinstance", "(", "fetcher", ",", "CurlHTTPFetcher", ")" ]
Whether the currently set HTTP fetcher is a Curl HTTP fetcher.
[ "Whether", "the", "currently", "set", "HTTP", "fetcher", "is", "a", "Curl", "HTTP", "fetcher", "." ]
f7e13536f0d1828d3cef5ae7a7b55cabadff37fc
https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/fetchers.py#L94-L99
16,609
openid/python-openid
openid/fetchers.py
HTTPLib2Fetcher.fetch
def fetch(self, url, body=None, headers=None): """Perform an HTTP request @raises Exception: Any exception that can be raised by httplib2 @see: C{L{HTTPFetcher.fetch}} """ if body: method = 'POST' else: method = 'GET' if headers is None: headers = {} # httplib2 doesn't check to make sure that the URL's scheme is # 'http' so we do it here. if not (url.startswith('http://') or url.startswith('https://')): raise ValueError('URL is not a HTTP URL: %r' % (url,)) httplib2_response, content = self.httplib2.request( url, method, body=body, headers=headers) # Translate the httplib2 response to our HTTP response abstraction # When a 400 is returned, there is no "content-location" # header set. This seems like a bug to me. I can't think of a # case where we really care about the final URL when it is an # error response, but being careful about it can't hurt. try: final_url = httplib2_response['content-location'] except KeyError: # We're assuming that no redirects occurred assert not httplib2_response.previous # And this should never happen for a successful response assert httplib2_response.status != 200 final_url = url return HTTPResponse( body=content, final_url=final_url, headers=dict(httplib2_response.items()), status=httplib2_response.status, )
python
def fetch(self, url, body=None, headers=None): """Perform an HTTP request @raises Exception: Any exception that can be raised by httplib2 @see: C{L{HTTPFetcher.fetch}} """ if body: method = 'POST' else: method = 'GET' if headers is None: headers = {} # httplib2 doesn't check to make sure that the URL's scheme is # 'http' so we do it here. if not (url.startswith('http://') or url.startswith('https://')): raise ValueError('URL is not a HTTP URL: %r' % (url,)) httplib2_response, content = self.httplib2.request( url, method, body=body, headers=headers) # Translate the httplib2 response to our HTTP response abstraction # When a 400 is returned, there is no "content-location" # header set. This seems like a bug to me. I can't think of a # case where we really care about the final URL when it is an # error response, but being careful about it can't hurt. try: final_url = httplib2_response['content-location'] except KeyError: # We're assuming that no redirects occurred assert not httplib2_response.previous # And this should never happen for a successful response assert httplib2_response.status != 200 final_url = url return HTTPResponse( body=content, final_url=final_url, headers=dict(httplib2_response.items()), status=httplib2_response.status, )
[ "def", "fetch", "(", "self", ",", "url", ",", "body", "=", "None", ",", "headers", "=", "None", ")", ":", "if", "body", ":", "method", "=", "'POST'", "else", ":", "method", "=", "'GET'", "if", "headers", "is", "None", ":", "headers", "=", "{", "}", "# httplib2 doesn't check to make sure that the URL's scheme is", "# 'http' so we do it here.", "if", "not", "(", "url", ".", "startswith", "(", "'http://'", ")", "or", "url", ".", "startswith", "(", "'https://'", ")", ")", ":", "raise", "ValueError", "(", "'URL is not a HTTP URL: %r'", "%", "(", "url", ",", ")", ")", "httplib2_response", ",", "content", "=", "self", ".", "httplib2", ".", "request", "(", "url", ",", "method", ",", "body", "=", "body", ",", "headers", "=", "headers", ")", "# Translate the httplib2 response to our HTTP response abstraction", "# When a 400 is returned, there is no \"content-location\"", "# header set. This seems like a bug to me. I can't think of a", "# case where we really care about the final URL when it is an", "# error response, but being careful about it can't hurt.", "try", ":", "final_url", "=", "httplib2_response", "[", "'content-location'", "]", "except", "KeyError", ":", "# We're assuming that no redirects occurred", "assert", "not", "httplib2_response", ".", "previous", "# And this should never happen for a successful response", "assert", "httplib2_response", ".", "status", "!=", "200", "final_url", "=", "url", "return", "HTTPResponse", "(", "body", "=", "content", ",", "final_url", "=", "final_url", ",", "headers", "=", "dict", "(", "httplib2_response", ".", "items", "(", ")", ")", ",", "status", "=", "httplib2_response", ".", "status", ",", ")" ]
Perform an HTTP request @raises Exception: Any exception that can be raised by httplib2 @see: C{L{HTTPFetcher.fetch}}
[ "Perform", "an", "HTTP", "request" ]
f7e13536f0d1828d3cef5ae7a7b55cabadff37fc
https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/fetchers.py#L386-L430
16,610
openid/python-openid
openid/yadis/services.py
getServiceEndpoints
def getServiceEndpoints(input_url, flt=None): """Perform the Yadis protocol on the input URL and return an iterable of resulting endpoint objects. @param flt: A filter object or something that is convertable to a filter object (using mkFilter) that will be used to generate endpoint objects. This defaults to generating BasicEndpoint objects. @param input_url: The URL on which to perform the Yadis protocol @return: The normalized identity URL and an iterable of endpoint objects generated by the filter function. @rtype: (str, [endpoint]) @raises DiscoveryFailure: when Yadis fails to obtain an XRDS document. """ result = discover(input_url) try: endpoints = applyFilter(result.normalized_uri, result.response_text, flt) except XRDSError, err: raise DiscoveryFailure(str(err), None) return (result.normalized_uri, endpoints)
python
def getServiceEndpoints(input_url, flt=None): """Perform the Yadis protocol on the input URL and return an iterable of resulting endpoint objects. @param flt: A filter object or something that is convertable to a filter object (using mkFilter) that will be used to generate endpoint objects. This defaults to generating BasicEndpoint objects. @param input_url: The URL on which to perform the Yadis protocol @return: The normalized identity URL and an iterable of endpoint objects generated by the filter function. @rtype: (str, [endpoint]) @raises DiscoveryFailure: when Yadis fails to obtain an XRDS document. """ result = discover(input_url) try: endpoints = applyFilter(result.normalized_uri, result.response_text, flt) except XRDSError, err: raise DiscoveryFailure(str(err), None) return (result.normalized_uri, endpoints)
[ "def", "getServiceEndpoints", "(", "input_url", ",", "flt", "=", "None", ")", ":", "result", "=", "discover", "(", "input_url", ")", "try", ":", "endpoints", "=", "applyFilter", "(", "result", ".", "normalized_uri", ",", "result", ".", "response_text", ",", "flt", ")", "except", "XRDSError", ",", "err", ":", "raise", "DiscoveryFailure", "(", "str", "(", "err", ")", ",", "None", ")", "return", "(", "result", ".", "normalized_uri", ",", "endpoints", ")" ]
Perform the Yadis protocol on the input URL and return an iterable of resulting endpoint objects. @param flt: A filter object or something that is convertable to a filter object (using mkFilter) that will be used to generate endpoint objects. This defaults to generating BasicEndpoint objects. @param input_url: The URL on which to perform the Yadis protocol @return: The normalized identity URL and an iterable of endpoint objects generated by the filter function. @rtype: (str, [endpoint]) @raises DiscoveryFailure: when Yadis fails to obtain an XRDS document.
[ "Perform", "the", "Yadis", "protocol", "on", "the", "input", "URL", "and", "return", "an", "iterable", "of", "resulting", "endpoint", "objects", "." ]
f7e13536f0d1828d3cef5ae7a7b55cabadff37fc
https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/yadis/services.py#L7-L31
16,611
openid/python-openid
openid/yadis/services.py
applyFilter
def applyFilter(normalized_uri, xrd_data, flt=None): """Generate an iterable of endpoint objects given this input data, presumably from the result of performing the Yadis protocol. @param normalized_uri: The input URL, after following redirects, as in the Yadis protocol. @param xrd_data: The XML text the XRDS file fetched from the normalized URI. @type xrd_data: str """ flt = mkFilter(flt) et = parseXRDS(xrd_data) endpoints = [] for service_element in iterServices(et): endpoints.extend( flt.getServiceEndpoints(normalized_uri, service_element)) return endpoints
python
def applyFilter(normalized_uri, xrd_data, flt=None): """Generate an iterable of endpoint objects given this input data, presumably from the result of performing the Yadis protocol. @param normalized_uri: The input URL, after following redirects, as in the Yadis protocol. @param xrd_data: The XML text the XRDS file fetched from the normalized URI. @type xrd_data: str """ flt = mkFilter(flt) et = parseXRDS(xrd_data) endpoints = [] for service_element in iterServices(et): endpoints.extend( flt.getServiceEndpoints(normalized_uri, service_element)) return endpoints
[ "def", "applyFilter", "(", "normalized_uri", ",", "xrd_data", ",", "flt", "=", "None", ")", ":", "flt", "=", "mkFilter", "(", "flt", ")", "et", "=", "parseXRDS", "(", "xrd_data", ")", "endpoints", "=", "[", "]", "for", "service_element", "in", "iterServices", "(", "et", ")", ":", "endpoints", ".", "extend", "(", "flt", ".", "getServiceEndpoints", "(", "normalized_uri", ",", "service_element", ")", ")", "return", "endpoints" ]
Generate an iterable of endpoint objects given this input data, presumably from the result of performing the Yadis protocol. @param normalized_uri: The input URL, after following redirects, as in the Yadis protocol. @param xrd_data: The XML text the XRDS file fetched from the normalized URI. @type xrd_data: str
[ "Generate", "an", "iterable", "of", "endpoint", "objects", "given", "this", "input", "data", "presumably", "from", "the", "result", "of", "performing", "the", "Yadis", "protocol", "." ]
f7e13536f0d1828d3cef5ae7a7b55cabadff37fc
https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/yadis/services.py#L33-L54
16,612
openid/python-openid
openid/consumer/html_parse.py
parseLinkAttrs
def parseLinkAttrs(html): """Find all link tags in a string representing a HTML document and return a list of their attributes. @param html: the text to parse @type html: str or unicode @return: A list of dictionaries of attributes, one for each link tag @rtype: [[(type(html), type(html))]] """ stripped = removed_re.sub('', html) html_mo = html_find.search(stripped) if html_mo is None or html_mo.start('contents') == -1: return [] start, end = html_mo.span('contents') head_mo = head_find.search(stripped, start, end) if head_mo is None or head_mo.start('contents') == -1: return [] start, end = head_mo.span('contents') link_mos = link_find.finditer(stripped, head_mo.start(), head_mo.end()) matches = [] for link_mo in link_mos: start = link_mo.start() + 5 link_attrs = {} for attr_mo in attr_find.finditer(stripped, start): if attr_mo.lastgroup == 'end_link': break # Either q_val or unq_val must be present, but not both # unq_val is a True (non-empty) value if it is present attr_name, q_val, unq_val = attr_mo.group( 'attr_name', 'q_val', 'unq_val') attr_val = ent_replace.sub(replaceEnt, unq_val or q_val) link_attrs[attr_name] = attr_val matches.append(link_attrs) return matches
python
def parseLinkAttrs(html): """Find all link tags in a string representing a HTML document and return a list of their attributes. @param html: the text to parse @type html: str or unicode @return: A list of dictionaries of attributes, one for each link tag @rtype: [[(type(html), type(html))]] """ stripped = removed_re.sub('', html) html_mo = html_find.search(stripped) if html_mo is None or html_mo.start('contents') == -1: return [] start, end = html_mo.span('contents') head_mo = head_find.search(stripped, start, end) if head_mo is None or head_mo.start('contents') == -1: return [] start, end = head_mo.span('contents') link_mos = link_find.finditer(stripped, head_mo.start(), head_mo.end()) matches = [] for link_mo in link_mos: start = link_mo.start() + 5 link_attrs = {} for attr_mo in attr_find.finditer(stripped, start): if attr_mo.lastgroup == 'end_link': break # Either q_val or unq_val must be present, but not both # unq_val is a True (non-empty) value if it is present attr_name, q_val, unq_val = attr_mo.group( 'attr_name', 'q_val', 'unq_val') attr_val = ent_replace.sub(replaceEnt, unq_val or q_val) link_attrs[attr_name] = attr_val matches.append(link_attrs) return matches
[ "def", "parseLinkAttrs", "(", "html", ")", ":", "stripped", "=", "removed_re", ".", "sub", "(", "''", ",", "html", ")", "html_mo", "=", "html_find", ".", "search", "(", "stripped", ")", "if", "html_mo", "is", "None", "or", "html_mo", ".", "start", "(", "'contents'", ")", "==", "-", "1", ":", "return", "[", "]", "start", ",", "end", "=", "html_mo", ".", "span", "(", "'contents'", ")", "head_mo", "=", "head_find", ".", "search", "(", "stripped", ",", "start", ",", "end", ")", "if", "head_mo", "is", "None", "or", "head_mo", ".", "start", "(", "'contents'", ")", "==", "-", "1", ":", "return", "[", "]", "start", ",", "end", "=", "head_mo", ".", "span", "(", "'contents'", ")", "link_mos", "=", "link_find", ".", "finditer", "(", "stripped", ",", "head_mo", ".", "start", "(", ")", ",", "head_mo", ".", "end", "(", ")", ")", "matches", "=", "[", "]", "for", "link_mo", "in", "link_mos", ":", "start", "=", "link_mo", ".", "start", "(", ")", "+", "5", "link_attrs", "=", "{", "}", "for", "attr_mo", "in", "attr_find", ".", "finditer", "(", "stripped", ",", "start", ")", ":", "if", "attr_mo", ".", "lastgroup", "==", "'end_link'", ":", "break", "# Either q_val or unq_val must be present, but not both", "# unq_val is a True (non-empty) value if it is present", "attr_name", ",", "q_val", ",", "unq_val", "=", "attr_mo", ".", "group", "(", "'attr_name'", ",", "'q_val'", ",", "'unq_val'", ")", "attr_val", "=", "ent_replace", ".", "sub", "(", "replaceEnt", ",", "unq_val", "or", "q_val", ")", "link_attrs", "[", "attr_name", "]", "=", "attr_val", "matches", ".", "append", "(", "link_attrs", ")", "return", "matches" ]
Find all link tags in a string representing a HTML document and return a list of their attributes. @param html: the text to parse @type html: str or unicode @return: A list of dictionaries of attributes, one for each link tag @rtype: [[(type(html), type(html))]]
[ "Find", "all", "link", "tags", "in", "a", "string", "representing", "a", "HTML", "document", "and", "return", "a", "list", "of", "their", "attributes", "." ]
f7e13536f0d1828d3cef5ae7a7b55cabadff37fc
https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/consumer/html_parse.py#L174-L215
16,613
openid/python-openid
openid/consumer/html_parse.py
relMatches
def relMatches(rel_attr, target_rel): """Does this target_rel appear in the rel_str?""" # XXX: TESTME rels = rel_attr.strip().split() for rel in rels: rel = rel.lower() if rel == target_rel: return 1 return 0
python
def relMatches(rel_attr, target_rel): """Does this target_rel appear in the rel_str?""" # XXX: TESTME rels = rel_attr.strip().split() for rel in rels: rel = rel.lower() if rel == target_rel: return 1 return 0
[ "def", "relMatches", "(", "rel_attr", ",", "target_rel", ")", ":", "# XXX: TESTME", "rels", "=", "rel_attr", ".", "strip", "(", ")", ".", "split", "(", ")", "for", "rel", "in", "rels", ":", "rel", "=", "rel", ".", "lower", "(", ")", "if", "rel", "==", "target_rel", ":", "return", "1", "return", "0" ]
Does this target_rel appear in the rel_str?
[ "Does", "this", "target_rel", "appear", "in", "the", "rel_str?" ]
f7e13536f0d1828d3cef5ae7a7b55cabadff37fc
https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/consumer/html_parse.py#L217-L226
16,614
openid/python-openid
openid/consumer/html_parse.py
linkHasRel
def linkHasRel(link_attrs, target_rel): """Does this link have target_rel as a relationship?""" # XXX: TESTME rel_attr = link_attrs.get('rel') return rel_attr and relMatches(rel_attr, target_rel)
python
def linkHasRel(link_attrs, target_rel): """Does this link have target_rel as a relationship?""" # XXX: TESTME rel_attr = link_attrs.get('rel') return rel_attr and relMatches(rel_attr, target_rel)
[ "def", "linkHasRel", "(", "link_attrs", ",", "target_rel", ")", ":", "# XXX: TESTME", "rel_attr", "=", "link_attrs", ".", "get", "(", "'rel'", ")", "return", "rel_attr", "and", "relMatches", "(", "rel_attr", ",", "target_rel", ")" ]
Does this link have target_rel as a relationship?
[ "Does", "this", "link", "have", "target_rel", "as", "a", "relationship?" ]
f7e13536f0d1828d3cef5ae7a7b55cabadff37fc
https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/consumer/html_parse.py#L228-L232
16,615
openid/python-openid
openid/consumer/html_parse.py
findFirstHref
def findFirstHref(link_attrs_list, target_rel): """Return the value of the href attribute for the first link tag in the list that has target_rel as a relationship.""" # XXX: TESTME matches = findLinksRel(link_attrs_list, target_rel) if not matches: return None first = matches[0] return first.get('href')
python
def findFirstHref(link_attrs_list, target_rel): """Return the value of the href attribute for the first link tag in the list that has target_rel as a relationship.""" # XXX: TESTME matches = findLinksRel(link_attrs_list, target_rel) if not matches: return None first = matches[0] return first.get('href')
[ "def", "findFirstHref", "(", "link_attrs_list", ",", "target_rel", ")", ":", "# XXX: TESTME", "matches", "=", "findLinksRel", "(", "link_attrs_list", ",", "target_rel", ")", "if", "not", "matches", ":", "return", "None", "first", "=", "matches", "[", "0", "]", "return", "first", ".", "get", "(", "'href'", ")" ]
Return the value of the href attribute for the first link tag in the list that has target_rel as a relationship.
[ "Return", "the", "value", "of", "the", "href", "attribute", "for", "the", "first", "link", "tag", "in", "the", "list", "that", "has", "target_rel", "as", "a", "relationship", "." ]
f7e13536f0d1828d3cef5ae7a7b55cabadff37fc
https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/consumer/html_parse.py#L241-L249
16,616
openid/python-openid
openid/oidutil.py
importElementTree
def importElementTree(module_names=None): """Find a working ElementTree implementation, trying the standard places that such a thing might show up. >>> ElementTree = importElementTree() @param module_names: The names of modules to try to use as ElementTree. Defaults to C{L{elementtree_modules}} @returns: An ElementTree module """ if module_names is None: module_names = elementtree_modules for mod_name in module_names: try: ElementTree = __import__(mod_name, None, None, ['unused']) except ImportError: pass else: # Make sure it can actually parse XML try: ElementTree.XML('<unused/>') except (SystemExit, MemoryError, AssertionError): raise except: logging.exception('Not using ElementTree library %r because it failed to ' 'parse a trivial document: %s' % mod_name) else: return ElementTree else: raise ImportError('No ElementTree library found. ' 'You may need to install one. ' 'Tried importing %r' % (module_names,) )
python
def importElementTree(module_names=None): """Find a working ElementTree implementation, trying the standard places that such a thing might show up. >>> ElementTree = importElementTree() @param module_names: The names of modules to try to use as ElementTree. Defaults to C{L{elementtree_modules}} @returns: An ElementTree module """ if module_names is None: module_names = elementtree_modules for mod_name in module_names: try: ElementTree = __import__(mod_name, None, None, ['unused']) except ImportError: pass else: # Make sure it can actually parse XML try: ElementTree.XML('<unused/>') except (SystemExit, MemoryError, AssertionError): raise except: logging.exception('Not using ElementTree library %r because it failed to ' 'parse a trivial document: %s' % mod_name) else: return ElementTree else: raise ImportError('No ElementTree library found. ' 'You may need to install one. ' 'Tried importing %r' % (module_names,) )
[ "def", "importElementTree", "(", "module_names", "=", "None", ")", ":", "if", "module_names", "is", "None", ":", "module_names", "=", "elementtree_modules", "for", "mod_name", "in", "module_names", ":", "try", ":", "ElementTree", "=", "__import__", "(", "mod_name", ",", "None", ",", "None", ",", "[", "'unused'", "]", ")", "except", "ImportError", ":", "pass", "else", ":", "# Make sure it can actually parse XML", "try", ":", "ElementTree", ".", "XML", "(", "'<unused/>'", ")", "except", "(", "SystemExit", ",", "MemoryError", ",", "AssertionError", ")", ":", "raise", "except", ":", "logging", ".", "exception", "(", "'Not using ElementTree library %r because it failed to '", "'parse a trivial document: %s'", "%", "mod_name", ")", "else", ":", "return", "ElementTree", "else", ":", "raise", "ImportError", "(", "'No ElementTree library found. '", "'You may need to install one. '", "'Tried importing %r'", "%", "(", "module_names", ",", ")", ")" ]
Find a working ElementTree implementation, trying the standard places that such a thing might show up. >>> ElementTree = importElementTree() @param module_names: The names of modules to try to use as ElementTree. Defaults to C{L{elementtree_modules}} @returns: An ElementTree module
[ "Find", "a", "working", "ElementTree", "implementation", "trying", "the", "standard", "places", "that", "such", "a", "thing", "might", "show", "up", "." ]
f7e13536f0d1828d3cef5ae7a7b55cabadff37fc
https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/oidutil.py#L55-L89
16,617
openid/python-openid
openid/yadis/etxrd.py
getYadisXRD
def getYadisXRD(xrd_tree): """Return the XRD element that should contain the Yadis services""" xrd = None # for the side-effect of assigning the last one in the list to the # xrd variable for xrd in xrd_tree.findall(xrd_tag): pass # There were no elements found, or else xrd would be set to the # last one if xrd is None: raise XRDSError('No XRD present in tree') return xrd
python
def getYadisXRD(xrd_tree): """Return the XRD element that should contain the Yadis services""" xrd = None # for the side-effect of assigning the last one in the list to the # xrd variable for xrd in xrd_tree.findall(xrd_tag): pass # There were no elements found, or else xrd would be set to the # last one if xrd is None: raise XRDSError('No XRD present in tree') return xrd
[ "def", "getYadisXRD", "(", "xrd_tree", ")", ":", "xrd", "=", "None", "# for the side-effect of assigning the last one in the list to the", "# xrd variable", "for", "xrd", "in", "xrd_tree", ".", "findall", "(", "xrd_tag", ")", ":", "pass", "# There were no elements found, or else xrd would be set to the", "# last one", "if", "xrd", "is", "None", ":", "raise", "XRDSError", "(", "'No XRD present in tree'", ")", "return", "xrd" ]
Return the XRD element that should contain the Yadis services
[ "Return", "the", "XRD", "element", "that", "should", "contain", "the", "Yadis", "services" ]
f7e13536f0d1828d3cef5ae7a7b55cabadff37fc
https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/yadis/etxrd.py#L119-L133
16,618
openid/python-openid
openid/yadis/etxrd.py
getXRDExpiration
def getXRDExpiration(xrd_element, default=None): """Return the expiration date of this XRD element, or None if no expiration was specified. @type xrd_element: ElementTree node @param default: The value to use as the expiration if no expiration was specified in the XRD. @rtype: datetime.datetime @raises ValueError: If the xrd:Expires element is present, but its contents are not formatted according to the specification. """ expires_element = xrd_element.find(expires_tag) if expires_element is None: return default else: expires_string = expires_element.text # Will raise ValueError if the string is not the expected format expires_time = strptime(expires_string, "%Y-%m-%dT%H:%M:%SZ") return datetime(*expires_time[0:6])
python
def getXRDExpiration(xrd_element, default=None): """Return the expiration date of this XRD element, or None if no expiration was specified. @type xrd_element: ElementTree node @param default: The value to use as the expiration if no expiration was specified in the XRD. @rtype: datetime.datetime @raises ValueError: If the xrd:Expires element is present, but its contents are not formatted according to the specification. """ expires_element = xrd_element.find(expires_tag) if expires_element is None: return default else: expires_string = expires_element.text # Will raise ValueError if the string is not the expected format expires_time = strptime(expires_string, "%Y-%m-%dT%H:%M:%SZ") return datetime(*expires_time[0:6])
[ "def", "getXRDExpiration", "(", "xrd_element", ",", "default", "=", "None", ")", ":", "expires_element", "=", "xrd_element", ".", "find", "(", "expires_tag", ")", "if", "expires_element", "is", "None", ":", "return", "default", "else", ":", "expires_string", "=", "expires_element", ".", "text", "# Will raise ValueError if the string is not the expected format", "expires_time", "=", "strptime", "(", "expires_string", ",", "\"%Y-%m-%dT%H:%M:%SZ\"", ")", "return", "datetime", "(", "*", "expires_time", "[", "0", ":", "6", "]", ")" ]
Return the expiration date of this XRD element, or None if no expiration was specified. @type xrd_element: ElementTree node @param default: The value to use as the expiration if no expiration was specified in the XRD. @rtype: datetime.datetime @raises ValueError: If the xrd:Expires element is present, but its contents are not formatted according to the specification.
[ "Return", "the", "expiration", "date", "of", "this", "XRD", "element", "or", "None", "if", "no", "expiration", "was", "specified", "." ]
f7e13536f0d1828d3cef5ae7a7b55cabadff37fc
https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/yadis/etxrd.py#L135-L157
16,619
openid/python-openid
openid/yadis/etxrd.py
getCanonicalID
def getCanonicalID(iname, xrd_tree): """Return the CanonicalID from this XRDS document. @param iname: the XRI being resolved. @type iname: unicode @param xrd_tree: The XRDS output from the resolver. @type xrd_tree: ElementTree @returns: The XRI CanonicalID or None. @returntype: unicode or None """ xrd_list = xrd_tree.findall(xrd_tag) xrd_list.reverse() try: canonicalID = xri.XRI(xrd_list[0].findall(canonicalID_tag)[0].text) except IndexError: return None childID = canonicalID.lower() for xrd in xrd_list[1:]: # XXX: can't use rsplit until we require python >= 2.4. parent_sought = childID[:childID.rindex('!')] parent = xri.XRI(xrd.findtext(canonicalID_tag)) if parent_sought != parent.lower(): raise XRDSFraud("%r can not come from %s" % (childID, parent)) childID = parent_sought root = xri.rootAuthority(iname) if not xri.providerIsAuthoritative(root, childID): raise XRDSFraud("%r can not come from root %r" % (childID, root)) return canonicalID
python
def getCanonicalID(iname, xrd_tree): """Return the CanonicalID from this XRDS document. @param iname: the XRI being resolved. @type iname: unicode @param xrd_tree: The XRDS output from the resolver. @type xrd_tree: ElementTree @returns: The XRI CanonicalID or None. @returntype: unicode or None """ xrd_list = xrd_tree.findall(xrd_tag) xrd_list.reverse() try: canonicalID = xri.XRI(xrd_list[0].findall(canonicalID_tag)[0].text) except IndexError: return None childID = canonicalID.lower() for xrd in xrd_list[1:]: # XXX: can't use rsplit until we require python >= 2.4. parent_sought = childID[:childID.rindex('!')] parent = xri.XRI(xrd.findtext(canonicalID_tag)) if parent_sought != parent.lower(): raise XRDSFraud("%r can not come from %s" % (childID, parent)) childID = parent_sought root = xri.rootAuthority(iname) if not xri.providerIsAuthoritative(root, childID): raise XRDSFraud("%r can not come from root %r" % (childID, root)) return canonicalID
[ "def", "getCanonicalID", "(", "iname", ",", "xrd_tree", ")", ":", "xrd_list", "=", "xrd_tree", ".", "findall", "(", "xrd_tag", ")", "xrd_list", ".", "reverse", "(", ")", "try", ":", "canonicalID", "=", "xri", ".", "XRI", "(", "xrd_list", "[", "0", "]", ".", "findall", "(", "canonicalID_tag", ")", "[", "0", "]", ".", "text", ")", "except", "IndexError", ":", "return", "None", "childID", "=", "canonicalID", ".", "lower", "(", ")", "for", "xrd", "in", "xrd_list", "[", "1", ":", "]", ":", "# XXX: can't use rsplit until we require python >= 2.4.", "parent_sought", "=", "childID", "[", ":", "childID", ".", "rindex", "(", "'!'", ")", "]", "parent", "=", "xri", ".", "XRI", "(", "xrd", ".", "findtext", "(", "canonicalID_tag", ")", ")", "if", "parent_sought", "!=", "parent", ".", "lower", "(", ")", ":", "raise", "XRDSFraud", "(", "\"%r can not come from %s\"", "%", "(", "childID", ",", "parent", ")", ")", "childID", "=", "parent_sought", "root", "=", "xri", ".", "rootAuthority", "(", "iname", ")", "if", "not", "xri", ".", "providerIsAuthoritative", "(", "root", ",", "childID", ")", ":", "raise", "XRDSFraud", "(", "\"%r can not come from root %r\"", "%", "(", "childID", ",", "root", ")", ")", "return", "canonicalID" ]
Return the CanonicalID from this XRDS document. @param iname: the XRI being resolved. @type iname: unicode @param xrd_tree: The XRDS output from the resolver. @type xrd_tree: ElementTree @returns: The XRI CanonicalID or None. @returntype: unicode or None
[ "Return", "the", "CanonicalID", "from", "this", "XRDS", "document", "." ]
f7e13536f0d1828d3cef5ae7a7b55cabadff37fc
https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/yadis/etxrd.py#L159-L194
16,620
openid/python-openid
openid/yadis/etxrd.py
getPriorityStrict
def getPriorityStrict(element): """Get the priority of this element. Raises ValueError if the value of the priority is invalid. If no priority is specified, it returns a value that compares greater than any other value. """ prio_str = element.get('priority') if prio_str is not None: prio_val = int(prio_str) if prio_val >= 0: return prio_val else: raise ValueError('Priority values must be non-negative integers') # Any errors in parsing the priority fall through to here return Max
python
def getPriorityStrict(element): """Get the priority of this element. Raises ValueError if the value of the priority is invalid. If no priority is specified, it returns a value that compares greater than any other value. """ prio_str = element.get('priority') if prio_str is not None: prio_val = int(prio_str) if prio_val >= 0: return prio_val else: raise ValueError('Priority values must be non-negative integers') # Any errors in parsing the priority fall through to here return Max
[ "def", "getPriorityStrict", "(", "element", ")", ":", "prio_str", "=", "element", ".", "get", "(", "'priority'", ")", "if", "prio_str", "is", "not", "None", ":", "prio_val", "=", "int", "(", "prio_str", ")", "if", "prio_val", ">=", "0", ":", "return", "prio_val", "else", ":", "raise", "ValueError", "(", "'Priority values must be non-negative integers'", ")", "# Any errors in parsing the priority fall through to here", "return", "Max" ]
Get the priority of this element. Raises ValueError if the value of the priority is invalid. If no priority is specified, it returns a value that compares greater than any other value.
[ "Get", "the", "priority", "of", "this", "element", "." ]
f7e13536f0d1828d3cef5ae7a7b55cabadff37fc
https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/yadis/etxrd.py#L211-L227
16,621
openid/python-openid
openid/consumer/consumer.py
makeKVPost
def makeKVPost(request_message, server_url): """Make a Direct Request to an OpenID Provider and return the result as a Message object. @raises openid.fetchers.HTTPFetchingError: if an error is encountered in making the HTTP post. @rtype: L{openid.message.Message} """ # XXX: TESTME resp = fetchers.fetch(server_url, body=request_message.toURLEncoded()) # Process response in separate function that can be shared by async code. return _httpResponseToMessage(resp, server_url)
python
def makeKVPost(request_message, server_url): """Make a Direct Request to an OpenID Provider and return the result as a Message object. @raises openid.fetchers.HTTPFetchingError: if an error is encountered in making the HTTP post. @rtype: L{openid.message.Message} """ # XXX: TESTME resp = fetchers.fetch(server_url, body=request_message.toURLEncoded()) # Process response in separate function that can be shared by async code. return _httpResponseToMessage(resp, server_url)
[ "def", "makeKVPost", "(", "request_message", ",", "server_url", ")", ":", "# XXX: TESTME", "resp", "=", "fetchers", ".", "fetch", "(", "server_url", ",", "body", "=", "request_message", ".", "toURLEncoded", "(", ")", ")", "# Process response in separate function that can be shared by async code.", "return", "_httpResponseToMessage", "(", "resp", ",", "server_url", ")" ]
Make a Direct Request to an OpenID Provider and return the result as a Message object. @raises openid.fetchers.HTTPFetchingError: if an error is encountered in making the HTTP post. @rtype: L{openid.message.Message}
[ "Make", "a", "Direct", "Request", "to", "an", "OpenID", "Provider", "and", "return", "the", "result", "as", "a", "Message", "object", "." ]
f7e13536f0d1828d3cef5ae7a7b55cabadff37fc
https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/consumer/consumer.py#L217-L230
16,622
openid/python-openid
openid/consumer/consumer.py
_httpResponseToMessage
def _httpResponseToMessage(response, server_url): """Adapt a POST response to a Message. @type response: L{openid.fetchers.HTTPResponse} @param response: Result of a POST to an OpenID endpoint. @rtype: L{openid.message.Message} @raises openid.fetchers.HTTPFetchingError: if the server returned a status of other than 200 or 400. @raises ServerError: if the server returned an OpenID error. """ # Should this function be named Message.fromHTTPResponse instead? response_message = Message.fromKVForm(response.body) if response.status == 400: raise ServerError.fromMessage(response_message) elif response.status not in (200, 206): fmt = 'bad status code from server %s: %s' error_message = fmt % (server_url, response.status) raise fetchers.HTTPFetchingError(error_message) return response_message
python
def _httpResponseToMessage(response, server_url): """Adapt a POST response to a Message. @type response: L{openid.fetchers.HTTPResponse} @param response: Result of a POST to an OpenID endpoint. @rtype: L{openid.message.Message} @raises openid.fetchers.HTTPFetchingError: if the server returned a status of other than 200 or 400. @raises ServerError: if the server returned an OpenID error. """ # Should this function be named Message.fromHTTPResponse instead? response_message = Message.fromKVForm(response.body) if response.status == 400: raise ServerError.fromMessage(response_message) elif response.status not in (200, 206): fmt = 'bad status code from server %s: %s' error_message = fmt % (server_url, response.status) raise fetchers.HTTPFetchingError(error_message) return response_message
[ "def", "_httpResponseToMessage", "(", "response", ",", "server_url", ")", ":", "# Should this function be named Message.fromHTTPResponse instead?", "response_message", "=", "Message", ".", "fromKVForm", "(", "response", ".", "body", ")", "if", "response", ".", "status", "==", "400", ":", "raise", "ServerError", ".", "fromMessage", "(", "response_message", ")", "elif", "response", ".", "status", "not", "in", "(", "200", ",", "206", ")", ":", "fmt", "=", "'bad status code from server %s: %s'", "error_message", "=", "fmt", "%", "(", "server_url", ",", "response", ".", "status", ")", "raise", "fetchers", ".", "HTTPFetchingError", "(", "error_message", ")", "return", "response_message" ]
Adapt a POST response to a Message. @type response: L{openid.fetchers.HTTPResponse} @param response: Result of a POST to an OpenID endpoint. @rtype: L{openid.message.Message} @raises openid.fetchers.HTTPFetchingError: if the server returned a status of other than 200 or 400. @raises ServerError: if the server returned an OpenID error.
[ "Adapt", "a", "POST", "response", "to", "a", "Message", "." ]
f7e13536f0d1828d3cef5ae7a7b55cabadff37fc
https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/consumer/consumer.py#L233-L256
16,623
openid/python-openid
openid/consumer/consumer.py
Consumer.complete
def complete(self, query, current_url): """Called to interpret the server's response to an OpenID request. It is called in step 4 of the flow described in the consumer overview. @param query: A dictionary of the query parameters for this HTTP request. @param current_url: The URL used to invoke the application. Extract the URL from your application's web request framework and specify it here to have it checked against the openid.return_to value in the response. If the return_to URL check fails, the status of the completion will be FAILURE. @returns: a subclass of Response. The type of response is indicated by the status attribute, which will be one of SUCCESS, CANCEL, FAILURE, or SETUP_NEEDED. @see: L{SuccessResponse<openid.consumer.consumer.SuccessResponse>} @see: L{CancelResponse<openid.consumer.consumer.CancelResponse>} @see: L{SetupNeededResponse<openid.consumer.consumer.SetupNeededResponse>} @see: L{FailureResponse<openid.consumer.consumer.FailureResponse>} """ endpoint = self.session.get(self._token_key) message = Message.fromPostArgs(query) response = self.consumer.complete(message, endpoint, current_url) try: del self.session[self._token_key] except KeyError: pass if (response.status in ['success', 'cancel'] and response.identity_url is not None): disco = Discovery(self.session, response.identity_url, self.session_key_prefix) # This is OK to do even if we did not do discovery in # the first place. disco.cleanup(force=True) return response
python
def complete(self, query, current_url): """Called to interpret the server's response to an OpenID request. It is called in step 4 of the flow described in the consumer overview. @param query: A dictionary of the query parameters for this HTTP request. @param current_url: The URL used to invoke the application. Extract the URL from your application's web request framework and specify it here to have it checked against the openid.return_to value in the response. If the return_to URL check fails, the status of the completion will be FAILURE. @returns: a subclass of Response. The type of response is indicated by the status attribute, which will be one of SUCCESS, CANCEL, FAILURE, or SETUP_NEEDED. @see: L{SuccessResponse<openid.consumer.consumer.SuccessResponse>} @see: L{CancelResponse<openid.consumer.consumer.CancelResponse>} @see: L{SetupNeededResponse<openid.consumer.consumer.SetupNeededResponse>} @see: L{FailureResponse<openid.consumer.consumer.FailureResponse>} """ endpoint = self.session.get(self._token_key) message = Message.fromPostArgs(query) response = self.consumer.complete(message, endpoint, current_url) try: del self.session[self._token_key] except KeyError: pass if (response.status in ['success', 'cancel'] and response.identity_url is not None): disco = Discovery(self.session, response.identity_url, self.session_key_prefix) # This is OK to do even if we did not do discovery in # the first place. disco.cleanup(force=True) return response
[ "def", "complete", "(", "self", ",", "query", ",", "current_url", ")", ":", "endpoint", "=", "self", ".", "session", ".", "get", "(", "self", ".", "_token_key", ")", "message", "=", "Message", ".", "fromPostArgs", "(", "query", ")", "response", "=", "self", ".", "consumer", ".", "complete", "(", "message", ",", "endpoint", ",", "current_url", ")", "try", ":", "del", "self", ".", "session", "[", "self", ".", "_token_key", "]", "except", "KeyError", ":", "pass", "if", "(", "response", ".", "status", "in", "[", "'success'", ",", "'cancel'", "]", "and", "response", ".", "identity_url", "is", "not", "None", ")", ":", "disco", "=", "Discovery", "(", "self", ".", "session", ",", "response", ".", "identity_url", ",", "self", ".", "session_key_prefix", ")", "# This is OK to do even if we did not do discovery in", "# the first place.", "disco", ".", "cleanup", "(", "force", "=", "True", ")", "return", "response" ]
Called to interpret the server's response to an OpenID request. It is called in step 4 of the flow described in the consumer overview. @param query: A dictionary of the query parameters for this HTTP request. @param current_url: The URL used to invoke the application. Extract the URL from your application's web request framework and specify it here to have it checked against the openid.return_to value in the response. If the return_to URL check fails, the status of the completion will be FAILURE. @returns: a subclass of Response. The type of response is indicated by the status attribute, which will be one of SUCCESS, CANCEL, FAILURE, or SETUP_NEEDED. @see: L{SuccessResponse<openid.consumer.consumer.SuccessResponse>} @see: L{CancelResponse<openid.consumer.consumer.CancelResponse>} @see: L{SetupNeededResponse<openid.consumer.consumer.SetupNeededResponse>} @see: L{FailureResponse<openid.consumer.consumer.FailureResponse>}
[ "Called", "to", "interpret", "the", "server", "s", "response", "to", "an", "OpenID", "request", ".", "It", "is", "called", "in", "step", "4", "of", "the", "flow", "described", "in", "the", "consumer", "overview", "." ]
f7e13536f0d1828d3cef5ae7a7b55cabadff37fc
https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/consumer/consumer.py#L387-L432
16,624
openid/python-openid
openid/consumer/consumer.py
ServerError.fromMessage
def fromMessage(cls, message): """Generate a ServerError instance, extracting the error text and the error code from the message.""" error_text = message.getArg( OPENID_NS, 'error', '<no error message supplied>') error_code = message.getArg(OPENID_NS, 'error_code') return cls(error_text, error_code, message)
python
def fromMessage(cls, message): """Generate a ServerError instance, extracting the error text and the error code from the message.""" error_text = message.getArg( OPENID_NS, 'error', '<no error message supplied>') error_code = message.getArg(OPENID_NS, 'error_code') return cls(error_text, error_code, message)
[ "def", "fromMessage", "(", "cls", ",", "message", ")", ":", "error_text", "=", "message", ".", "getArg", "(", "OPENID_NS", ",", "'error'", ",", "'<no error message supplied>'", ")", "error_code", "=", "message", ".", "getArg", "(", "OPENID_NS", ",", "'error_code'", ")", "return", "cls", "(", "error_text", ",", "error_code", ",", "message", ")" ]
Generate a ServerError instance, extracting the error text and the error code from the message.
[ "Generate", "a", "ServerError", "instance", "extracting", "the", "error", "text", "and", "the", "error", "code", "from", "the", "message", "." ]
f7e13536f0d1828d3cef5ae7a7b55cabadff37fc
https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/consumer/consumer.py#L544-L550
16,625
openid/python-openid
openid/consumer/consumer.py
GenericConsumer.begin
def begin(self, service_endpoint): """Create an AuthRequest object for the specified service_endpoint. This method will create an association if necessary.""" if self.store is None: assoc = None else: assoc = self._getAssociation(service_endpoint) request = AuthRequest(service_endpoint, assoc) request.return_to_args[self.openid1_nonce_query_arg_name] = mkNonce() if request.message.isOpenID1(): request.return_to_args[self.openid1_return_to_identifier_name] = \ request.endpoint.claimed_id return request
python
def begin(self, service_endpoint): """Create an AuthRequest object for the specified service_endpoint. This method will create an association if necessary.""" if self.store is None: assoc = None else: assoc = self._getAssociation(service_endpoint) request = AuthRequest(service_endpoint, assoc) request.return_to_args[self.openid1_nonce_query_arg_name] = mkNonce() if request.message.isOpenID1(): request.return_to_args[self.openid1_return_to_identifier_name] = \ request.endpoint.claimed_id return request
[ "def", "begin", "(", "self", ",", "service_endpoint", ")", ":", "if", "self", ".", "store", "is", "None", ":", "assoc", "=", "None", "else", ":", "assoc", "=", "self", ".", "_getAssociation", "(", "service_endpoint", ")", "request", "=", "AuthRequest", "(", "service_endpoint", ",", "assoc", ")", "request", ".", "return_to_args", "[", "self", ".", "openid1_nonce_query_arg_name", "]", "=", "mkNonce", "(", ")", "if", "request", ".", "message", ".", "isOpenID1", "(", ")", ":", "request", ".", "return_to_args", "[", "self", ".", "openid1_return_to_identifier_name", "]", "=", "request", ".", "endpoint", ".", "claimed_id", "return", "request" ]
Create an AuthRequest object for the specified service_endpoint. This method will create an association if necessary.
[ "Create", "an", "AuthRequest", "object", "for", "the", "specified", "service_endpoint", ".", "This", "method", "will", "create", "an", "association", "if", "necessary", "." ]
f7e13536f0d1828d3cef5ae7a7b55cabadff37fc
https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/consumer/consumer.py#L592-L608
16,626
openid/python-openid
openid/consumer/consumer.py
GenericConsumer.complete
def complete(self, message, endpoint, return_to): """Process the OpenID message, using the specified endpoint and return_to URL as context. This method will handle any OpenID message that is sent to the return_to URL. """ mode = message.getArg(OPENID_NS, 'mode', '<No mode set>') modeMethod = getattr(self, '_complete_' + mode, self._completeInvalid) return modeMethod(message, endpoint, return_to)
python
def complete(self, message, endpoint, return_to): """Process the OpenID message, using the specified endpoint and return_to URL as context. This method will handle any OpenID message that is sent to the return_to URL. """ mode = message.getArg(OPENID_NS, 'mode', '<No mode set>') modeMethod = getattr(self, '_complete_' + mode, self._completeInvalid) return modeMethod(message, endpoint, return_to)
[ "def", "complete", "(", "self", ",", "message", ",", "endpoint", ",", "return_to", ")", ":", "mode", "=", "message", ".", "getArg", "(", "OPENID_NS", ",", "'mode'", ",", "'<No mode set>'", ")", "modeMethod", "=", "getattr", "(", "self", ",", "'_complete_'", "+", "mode", ",", "self", ".", "_completeInvalid", ")", "return", "modeMethod", "(", "message", ",", "endpoint", ",", "return_to", ")" ]
Process the OpenID message, using the specified endpoint and return_to URL as context. This method will handle any OpenID message that is sent to the return_to URL.
[ "Process", "the", "OpenID", "message", "using", "the", "specified", "endpoint", "and", "return_to", "URL", "as", "context", ".", "This", "method", "will", "handle", "any", "OpenID", "message", "that", "is", "sent", "to", "the", "return_to", "URL", "." ]
f7e13536f0d1828d3cef5ae7a7b55cabadff37fc
https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/consumer/consumer.py#L610-L620
16,627
openid/python-openid
openid/consumer/consumer.py
GenericConsumer._checkSetupNeeded
def _checkSetupNeeded(self, message): """Check an id_res message to see if it is a checkid_immediate cancel response. @raises SetupNeededError: if it is a checkid_immediate cancellation """ # In OpenID 1, we check to see if this is a cancel from # immediate mode by the presence of the user_setup_url # parameter. if message.isOpenID1(): user_setup_url = message.getArg(OPENID1_NS, 'user_setup_url') if user_setup_url is not None: raise SetupNeededError(user_setup_url)
python
def _checkSetupNeeded(self, message): """Check an id_res message to see if it is a checkid_immediate cancel response. @raises SetupNeededError: if it is a checkid_immediate cancellation """ # In OpenID 1, we check to see if this is a cancel from # immediate mode by the presence of the user_setup_url # parameter. if message.isOpenID1(): user_setup_url = message.getArg(OPENID1_NS, 'user_setup_url') if user_setup_url is not None: raise SetupNeededError(user_setup_url)
[ "def", "_checkSetupNeeded", "(", "self", ",", "message", ")", ":", "# In OpenID 1, we check to see if this is a cancel from", "# immediate mode by the presence of the user_setup_url", "# parameter.", "if", "message", ".", "isOpenID1", "(", ")", ":", "user_setup_url", "=", "message", ".", "getArg", "(", "OPENID1_NS", ",", "'user_setup_url'", ")", "if", "user_setup_url", "is", "not", "None", ":", "raise", "SetupNeededError", "(", "user_setup_url", ")" ]
Check an id_res message to see if it is a checkid_immediate cancel response. @raises SetupNeededError: if it is a checkid_immediate cancellation
[ "Check", "an", "id_res", "message", "to", "see", "if", "it", "is", "a", "checkid_immediate", "cancel", "response", "." ]
f7e13536f0d1828d3cef5ae7a7b55cabadff37fc
https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/consumer/consumer.py#L687-L699
16,628
openid/python-openid
openid/consumer/consumer.py
GenericConsumer._doIdRes
def _doIdRes(self, message, endpoint, return_to): """Handle id_res responses that are not cancellations of immediate mode requests. @param message: the response paramaters. @param endpoint: the discovered endpoint object. May be None. @raises ProtocolError: If the message contents are not well-formed according to the OpenID specification. This includes missing fields or not signing fields that should be signed. @raises DiscoveryFailure: If the subject of the id_res message does not match the supplied endpoint, and discovery on the identifier in the message fails (this should only happen when using OpenID 2) @returntype: L{Response} """ # Checks for presence of appropriate fields (and checks # signed list fields) self._idResCheckForFields(message) if not self._checkReturnTo(message, return_to): raise ProtocolError( "return_to does not match return URL. Expected %r, got %r" % (return_to, message.getArg(OPENID_NS, 'return_to'))) # Verify discovery information: endpoint = self._verifyDiscoveryResults(message, endpoint) logging.info("Received id_res response from %s using association %s" % (endpoint.server_url, message.getArg(OPENID_NS, 'assoc_handle'))) self._idResCheckSignature(message, endpoint.server_url) # Will raise a ProtocolError if the nonce is bad self._idResCheckNonce(message, endpoint) signed_list_str = message.getArg(OPENID_NS, 'signed', no_default) signed_list = signed_list_str.split(',') signed_fields = ["openid." + s for s in signed_list] return SuccessResponse(endpoint, message, signed_fields)
python
def _doIdRes(self, message, endpoint, return_to): """Handle id_res responses that are not cancellations of immediate mode requests. @param message: the response paramaters. @param endpoint: the discovered endpoint object. May be None. @raises ProtocolError: If the message contents are not well-formed according to the OpenID specification. This includes missing fields or not signing fields that should be signed. @raises DiscoveryFailure: If the subject of the id_res message does not match the supplied endpoint, and discovery on the identifier in the message fails (this should only happen when using OpenID 2) @returntype: L{Response} """ # Checks for presence of appropriate fields (and checks # signed list fields) self._idResCheckForFields(message) if not self._checkReturnTo(message, return_to): raise ProtocolError( "return_to does not match return URL. Expected %r, got %r" % (return_to, message.getArg(OPENID_NS, 'return_to'))) # Verify discovery information: endpoint = self._verifyDiscoveryResults(message, endpoint) logging.info("Received id_res response from %s using association %s" % (endpoint.server_url, message.getArg(OPENID_NS, 'assoc_handle'))) self._idResCheckSignature(message, endpoint.server_url) # Will raise a ProtocolError if the nonce is bad self._idResCheckNonce(message, endpoint) signed_list_str = message.getArg(OPENID_NS, 'signed', no_default) signed_list = signed_list_str.split(',') signed_fields = ["openid." + s for s in signed_list] return SuccessResponse(endpoint, message, signed_fields)
[ "def", "_doIdRes", "(", "self", ",", "message", ",", "endpoint", ",", "return_to", ")", ":", "# Checks for presence of appropriate fields (and checks", "# signed list fields)", "self", ".", "_idResCheckForFields", "(", "message", ")", "if", "not", "self", ".", "_checkReturnTo", "(", "message", ",", "return_to", ")", ":", "raise", "ProtocolError", "(", "\"return_to does not match return URL. Expected %r, got %r\"", "%", "(", "return_to", ",", "message", ".", "getArg", "(", "OPENID_NS", ",", "'return_to'", ")", ")", ")", "# Verify discovery information:", "endpoint", "=", "self", ".", "_verifyDiscoveryResults", "(", "message", ",", "endpoint", ")", "logging", ".", "info", "(", "\"Received id_res response from %s using association %s\"", "%", "(", "endpoint", ".", "server_url", ",", "message", ".", "getArg", "(", "OPENID_NS", ",", "'assoc_handle'", ")", ")", ")", "self", ".", "_idResCheckSignature", "(", "message", ",", "endpoint", ".", "server_url", ")", "# Will raise a ProtocolError if the nonce is bad", "self", ".", "_idResCheckNonce", "(", "message", ",", "endpoint", ")", "signed_list_str", "=", "message", ".", "getArg", "(", "OPENID_NS", ",", "'signed'", ",", "no_default", ")", "signed_list", "=", "signed_list_str", ".", "split", "(", "','", ")", "signed_fields", "=", "[", "\"openid.\"", "+", "s", "for", "s", "in", "signed_list", "]", "return", "SuccessResponse", "(", "endpoint", ",", "message", ",", "signed_fields", ")" ]
Handle id_res responses that are not cancellations of immediate mode requests. @param message: the response paramaters. @param endpoint: the discovered endpoint object. May be None. @raises ProtocolError: If the message contents are not well-formed according to the OpenID specification. This includes missing fields or not signing fields that should be signed. @raises DiscoveryFailure: If the subject of the id_res message does not match the supplied endpoint, and discovery on the identifier in the message fails (this should only happen when using OpenID 2) @returntype: L{Response}
[ "Handle", "id_res", "responses", "that", "are", "not", "cancellations", "of", "immediate", "mode", "requests", "." ]
f7e13536f0d1828d3cef5ae7a7b55cabadff37fc
https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/consumer/consumer.py#L701-L744
16,629
openid/python-openid
openid/consumer/consumer.py
GenericConsumer._verifyReturnToArgs
def _verifyReturnToArgs(query): """Verify that the arguments in the return_to URL are present in this response. """ message = Message.fromPostArgs(query) return_to = message.getArg(OPENID_NS, 'return_to') if return_to is None: raise ProtocolError('Response has no return_to') parsed_url = urlparse(return_to) rt_query = parsed_url[4] parsed_args = cgi.parse_qsl(rt_query) for rt_key, rt_value in parsed_args: try: value = query[rt_key] if rt_value != value: format = ("parameter %s value %r does not match " "return_to's value %r") raise ProtocolError(format % (rt_key, value, rt_value)) except KeyError: format = "return_to parameter %s absent from query %r" raise ProtocolError(format % (rt_key, query)) # Make sure all non-OpenID arguments in the response are also # in the signed return_to. bare_args = message.getArgs(BARE_NS) for pair in bare_args.iteritems(): if pair not in parsed_args: raise ProtocolError("Parameter %s not in return_to URL" % (pair[0],))
python
def _verifyReturnToArgs(query): """Verify that the arguments in the return_to URL are present in this response. """ message = Message.fromPostArgs(query) return_to = message.getArg(OPENID_NS, 'return_to') if return_to is None: raise ProtocolError('Response has no return_to') parsed_url = urlparse(return_to) rt_query = parsed_url[4] parsed_args = cgi.parse_qsl(rt_query) for rt_key, rt_value in parsed_args: try: value = query[rt_key] if rt_value != value: format = ("parameter %s value %r does not match " "return_to's value %r") raise ProtocolError(format % (rt_key, value, rt_value)) except KeyError: format = "return_to parameter %s absent from query %r" raise ProtocolError(format % (rt_key, query)) # Make sure all non-OpenID arguments in the response are also # in the signed return_to. bare_args = message.getArgs(BARE_NS) for pair in bare_args.iteritems(): if pair not in parsed_args: raise ProtocolError("Parameter %s not in return_to URL" % (pair[0],))
[ "def", "_verifyReturnToArgs", "(", "query", ")", ":", "message", "=", "Message", ".", "fromPostArgs", "(", "query", ")", "return_to", "=", "message", ".", "getArg", "(", "OPENID_NS", ",", "'return_to'", ")", "if", "return_to", "is", "None", ":", "raise", "ProtocolError", "(", "'Response has no return_to'", ")", "parsed_url", "=", "urlparse", "(", "return_to", ")", "rt_query", "=", "parsed_url", "[", "4", "]", "parsed_args", "=", "cgi", ".", "parse_qsl", "(", "rt_query", ")", "for", "rt_key", ",", "rt_value", "in", "parsed_args", ":", "try", ":", "value", "=", "query", "[", "rt_key", "]", "if", "rt_value", "!=", "value", ":", "format", "=", "(", "\"parameter %s value %r does not match \"", "\"return_to's value %r\"", ")", "raise", "ProtocolError", "(", "format", "%", "(", "rt_key", ",", "value", ",", "rt_value", ")", ")", "except", "KeyError", ":", "format", "=", "\"return_to parameter %s absent from query %r\"", "raise", "ProtocolError", "(", "format", "%", "(", "rt_key", ",", "query", ")", ")", "# Make sure all non-OpenID arguments in the response are also", "# in the signed return_to.", "bare_args", "=", "message", ".", "getArgs", "(", "BARE_NS", ")", "for", "pair", "in", "bare_args", ".", "iteritems", "(", ")", ":", "if", "pair", "not", "in", "parsed_args", ":", "raise", "ProtocolError", "(", "\"Parameter %s not in return_to URL\"", "%", "(", "pair", "[", "0", "]", ",", ")", ")" ]
Verify that the arguments in the return_to URL are present in this response.
[ "Verify", "that", "the", "arguments", "in", "the", "return_to", "URL", "are", "present", "in", "this", "response", "." ]
f7e13536f0d1828d3cef5ae7a7b55cabadff37fc
https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/consumer/consumer.py#L843-L873
16,630
openid/python-openid
openid/consumer/consumer.py
GenericConsumer._verifyDiscoveryResults
def _verifyDiscoveryResults(self, resp_msg, endpoint=None): """ Extract the information from an OpenID assertion message and verify it against the original @param endpoint: The endpoint that resulted from doing discovery @param resp_msg: The id_res message object @returns: the verified endpoint """ if resp_msg.getOpenIDNamespace() == OPENID2_NS: return self._verifyDiscoveryResultsOpenID2(resp_msg, endpoint) else: return self._verifyDiscoveryResultsOpenID1(resp_msg, endpoint)
python
def _verifyDiscoveryResults(self, resp_msg, endpoint=None): """ Extract the information from an OpenID assertion message and verify it against the original @param endpoint: The endpoint that resulted from doing discovery @param resp_msg: The id_res message object @returns: the verified endpoint """ if resp_msg.getOpenIDNamespace() == OPENID2_NS: return self._verifyDiscoveryResultsOpenID2(resp_msg, endpoint) else: return self._verifyDiscoveryResultsOpenID1(resp_msg, endpoint)
[ "def", "_verifyDiscoveryResults", "(", "self", ",", "resp_msg", ",", "endpoint", "=", "None", ")", ":", "if", "resp_msg", ".", "getOpenIDNamespace", "(", ")", "==", "OPENID2_NS", ":", "return", "self", ".", "_verifyDiscoveryResultsOpenID2", "(", "resp_msg", ",", "endpoint", ")", "else", ":", "return", "self", ".", "_verifyDiscoveryResultsOpenID1", "(", "resp_msg", ",", "endpoint", ")" ]
Extract the information from an OpenID assertion message and verify it against the original @param endpoint: The endpoint that resulted from doing discovery @param resp_msg: The id_res message object @returns: the verified endpoint
[ "Extract", "the", "information", "from", "an", "OpenID", "assertion", "message", "and", "verify", "it", "against", "the", "original" ]
f7e13536f0d1828d3cef5ae7a7b55cabadff37fc
https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/consumer/consumer.py#L877-L890
16,631
openid/python-openid
openid/consumer/consumer.py
GenericConsumer._verifyDiscoverySingle
def _verifyDiscoverySingle(self, endpoint, to_match): """Verify that the given endpoint matches the information extracted from the OpenID assertion, and raise an exception if there is a mismatch. @type endpoint: openid.consumer.discover.OpenIDServiceEndpoint @type to_match: openid.consumer.discover.OpenIDServiceEndpoint @rtype: NoneType @raises ProtocolError: when the endpoint does not match the discovered information. """ # Every type URI that's in the to_match endpoint has to be # present in the discovered endpoint. for type_uri in to_match.type_uris: if not endpoint.usesExtension(type_uri): raise TypeURIMismatch(type_uri, endpoint) # Fragments do not influence discovery, so we can't compare a # claimed identifier with a fragment to discovered information. defragged_claimed_id, _ = urldefrag(to_match.claimed_id) if defragged_claimed_id != endpoint.claimed_id: raise ProtocolError( 'Claimed ID does not match (different subjects!), ' 'Expected %s, got %s' % (defragged_claimed_id, endpoint.claimed_id)) if to_match.getLocalID() != endpoint.getLocalID(): raise ProtocolError('local_id mismatch. Expected %s, got %s' % (to_match.getLocalID(), endpoint.getLocalID())) # If the server URL is None, this must be an OpenID 1 # response, because op_endpoint is a required parameter in # OpenID 2. In that case, we don't actually care what the # discovered server_url is, because signature checking or # check_auth should take care of that check for us. if to_match.server_url is None: assert to_match.preferredNamespace() == OPENID1_NS, ( """The code calling this must ensure that OpenID 2 responses have a non-none `openid.op_endpoint' and that it is set as the `server_url' attribute of the `to_match' endpoint.""") elif to_match.server_url != endpoint.server_url: raise ProtocolError('OP Endpoint mismatch. Expected %s, got %s' % (to_match.server_url, endpoint.server_url))
python
def _verifyDiscoverySingle(self, endpoint, to_match): """Verify that the given endpoint matches the information extracted from the OpenID assertion, and raise an exception if there is a mismatch. @type endpoint: openid.consumer.discover.OpenIDServiceEndpoint @type to_match: openid.consumer.discover.OpenIDServiceEndpoint @rtype: NoneType @raises ProtocolError: when the endpoint does not match the discovered information. """ # Every type URI that's in the to_match endpoint has to be # present in the discovered endpoint. for type_uri in to_match.type_uris: if not endpoint.usesExtension(type_uri): raise TypeURIMismatch(type_uri, endpoint) # Fragments do not influence discovery, so we can't compare a # claimed identifier with a fragment to discovered information. defragged_claimed_id, _ = urldefrag(to_match.claimed_id) if defragged_claimed_id != endpoint.claimed_id: raise ProtocolError( 'Claimed ID does not match (different subjects!), ' 'Expected %s, got %s' % (defragged_claimed_id, endpoint.claimed_id)) if to_match.getLocalID() != endpoint.getLocalID(): raise ProtocolError('local_id mismatch. Expected %s, got %s' % (to_match.getLocalID(), endpoint.getLocalID())) # If the server URL is None, this must be an OpenID 1 # response, because op_endpoint is a required parameter in # OpenID 2. In that case, we don't actually care what the # discovered server_url is, because signature checking or # check_auth should take care of that check for us. if to_match.server_url is None: assert to_match.preferredNamespace() == OPENID1_NS, ( """The code calling this must ensure that OpenID 2 responses have a non-none `openid.op_endpoint' and that it is set as the `server_url' attribute of the `to_match' endpoint.""") elif to_match.server_url != endpoint.server_url: raise ProtocolError('OP Endpoint mismatch. Expected %s, got %s' % (to_match.server_url, endpoint.server_url))
[ "def", "_verifyDiscoverySingle", "(", "self", ",", "endpoint", ",", "to_match", ")", ":", "# Every type URI that's in the to_match endpoint has to be", "# present in the discovered endpoint.", "for", "type_uri", "in", "to_match", ".", "type_uris", ":", "if", "not", "endpoint", ".", "usesExtension", "(", "type_uri", ")", ":", "raise", "TypeURIMismatch", "(", "type_uri", ",", "endpoint", ")", "# Fragments do not influence discovery, so we can't compare a", "# claimed identifier with a fragment to discovered information.", "defragged_claimed_id", ",", "_", "=", "urldefrag", "(", "to_match", ".", "claimed_id", ")", "if", "defragged_claimed_id", "!=", "endpoint", ".", "claimed_id", ":", "raise", "ProtocolError", "(", "'Claimed ID does not match (different subjects!), '", "'Expected %s, got %s'", "%", "(", "defragged_claimed_id", ",", "endpoint", ".", "claimed_id", ")", ")", "if", "to_match", ".", "getLocalID", "(", ")", "!=", "endpoint", ".", "getLocalID", "(", ")", ":", "raise", "ProtocolError", "(", "'local_id mismatch. Expected %s, got %s'", "%", "(", "to_match", ".", "getLocalID", "(", ")", ",", "endpoint", ".", "getLocalID", "(", ")", ")", ")", "# If the server URL is None, this must be an OpenID 1", "# response, because op_endpoint is a required parameter in", "# OpenID 2. In that case, we don't actually care what the", "# discovered server_url is, because signature checking or", "# check_auth should take care of that check for us.", "if", "to_match", ".", "server_url", "is", "None", ":", "assert", "to_match", ".", "preferredNamespace", "(", ")", "==", "OPENID1_NS", ",", "(", "\"\"\"The code calling this must ensure that OpenID 2\n responses have a non-none `openid.op_endpoint' and\n that it is set as the `server_url' attribute of the\n `to_match' endpoint.\"\"\"", ")", "elif", "to_match", ".", "server_url", "!=", "endpoint", ".", "server_url", ":", "raise", "ProtocolError", "(", "'OP Endpoint mismatch. Expected %s, got %s'", "%", "(", "to_match", ".", "server_url", ",", "endpoint", ".", "server_url", ")", ")" ]
Verify that the given endpoint matches the information extracted from the OpenID assertion, and raise an exception if there is a mismatch. @type endpoint: openid.consumer.discover.OpenIDServiceEndpoint @type to_match: openid.consumer.discover.OpenIDServiceEndpoint @rtype: NoneType @raises ProtocolError: when the endpoint does not match the discovered information.
[ "Verify", "that", "the", "given", "endpoint", "matches", "the", "information", "extracted", "from", "the", "OpenID", "assertion", "and", "raise", "an", "exception", "if", "there", "is", "a", "mismatch", "." ]
f7e13536f0d1828d3cef5ae7a7b55cabadff37fc
https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/consumer/consumer.py#L989-L1035
16,632
openid/python-openid
openid/consumer/consumer.py
GenericConsumer._discoverAndVerify
def _discoverAndVerify(self, claimed_id, to_match_endpoints): """Given an endpoint object created from the information in an OpenID response, perform discovery and verify the discovery results, returning the matching endpoint that is the result of doing that discovery. @type to_match: openid.consumer.discover.OpenIDServiceEndpoint @param to_match: The endpoint whose information we're confirming @rtype: openid.consumer.discover.OpenIDServiceEndpoint @returns: The result of performing discovery on the claimed identifier in `to_match' @raises DiscoveryFailure: when discovery fails. """ logging.info('Performing discovery on %s' % (claimed_id,)) _, services = self._discover(claimed_id) if not services: raise DiscoveryFailure('No OpenID information found at %s' % (claimed_id,), None) return self._verifyDiscoveredServices(claimed_id, services, to_match_endpoints)
python
def _discoverAndVerify(self, claimed_id, to_match_endpoints): """Given an endpoint object created from the information in an OpenID response, perform discovery and verify the discovery results, returning the matching endpoint that is the result of doing that discovery. @type to_match: openid.consumer.discover.OpenIDServiceEndpoint @param to_match: The endpoint whose information we're confirming @rtype: openid.consumer.discover.OpenIDServiceEndpoint @returns: The result of performing discovery on the claimed identifier in `to_match' @raises DiscoveryFailure: when discovery fails. """ logging.info('Performing discovery on %s' % (claimed_id,)) _, services = self._discover(claimed_id) if not services: raise DiscoveryFailure('No OpenID information found at %s' % (claimed_id,), None) return self._verifyDiscoveredServices(claimed_id, services, to_match_endpoints)
[ "def", "_discoverAndVerify", "(", "self", ",", "claimed_id", ",", "to_match_endpoints", ")", ":", "logging", ".", "info", "(", "'Performing discovery on %s'", "%", "(", "claimed_id", ",", ")", ")", "_", ",", "services", "=", "self", ".", "_discover", "(", "claimed_id", ")", "if", "not", "services", ":", "raise", "DiscoveryFailure", "(", "'No OpenID information found at %s'", "%", "(", "claimed_id", ",", ")", ",", "None", ")", "return", "self", ".", "_verifyDiscoveredServices", "(", "claimed_id", ",", "services", ",", "to_match_endpoints", ")" ]
Given an endpoint object created from the information in an OpenID response, perform discovery and verify the discovery results, returning the matching endpoint that is the result of doing that discovery. @type to_match: openid.consumer.discover.OpenIDServiceEndpoint @param to_match: The endpoint whose information we're confirming @rtype: openid.consumer.discover.OpenIDServiceEndpoint @returns: The result of performing discovery on the claimed identifier in `to_match' @raises DiscoveryFailure: when discovery fails.
[ "Given", "an", "endpoint", "object", "created", "from", "the", "information", "in", "an", "OpenID", "response", "perform", "discovery", "and", "verify", "the", "discovery", "results", "returning", "the", "matching", "endpoint", "that", "is", "the", "result", "of", "doing", "that", "discovery", "." ]
f7e13536f0d1828d3cef5ae7a7b55cabadff37fc
https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/consumer/consumer.py#L1037-L1058
16,633
openid/python-openid
openid/consumer/consumer.py
GenericConsumer._processCheckAuthResponse
def _processCheckAuthResponse(self, response, server_url): """Process the response message from a check_authentication request, invalidating associations if requested. """ is_valid = response.getArg(OPENID_NS, 'is_valid', 'false') invalidate_handle = response.getArg(OPENID_NS, 'invalidate_handle') if invalidate_handle is not None: logging.info( 'Received "invalidate_handle" from server %s' % (server_url,)) if self.store is None: logging.error('Unexpectedly got invalidate_handle without ' 'a store!') else: self.store.removeAssociation(server_url, invalidate_handle) if is_valid == 'true': return True else: logging.error('Server responds that checkAuth call is not valid') return False
python
def _processCheckAuthResponse(self, response, server_url): """Process the response message from a check_authentication request, invalidating associations if requested. """ is_valid = response.getArg(OPENID_NS, 'is_valid', 'false') invalidate_handle = response.getArg(OPENID_NS, 'invalidate_handle') if invalidate_handle is not None: logging.info( 'Received "invalidate_handle" from server %s' % (server_url,)) if self.store is None: logging.error('Unexpectedly got invalidate_handle without ' 'a store!') else: self.store.removeAssociation(server_url, invalidate_handle) if is_valid == 'true': return True else: logging.error('Server responds that checkAuth call is not valid') return False
[ "def", "_processCheckAuthResponse", "(", "self", ",", "response", ",", "server_url", ")", ":", "is_valid", "=", "response", ".", "getArg", "(", "OPENID_NS", ",", "'is_valid'", ",", "'false'", ")", "invalidate_handle", "=", "response", ".", "getArg", "(", "OPENID_NS", ",", "'invalidate_handle'", ")", "if", "invalidate_handle", "is", "not", "None", ":", "logging", ".", "info", "(", "'Received \"invalidate_handle\" from server %s'", "%", "(", "server_url", ",", ")", ")", "if", "self", ".", "store", "is", "None", ":", "logging", ".", "error", "(", "'Unexpectedly got invalidate_handle without '", "'a store!'", ")", "else", ":", "self", ".", "store", ".", "removeAssociation", "(", "server_url", ",", "invalidate_handle", ")", "if", "is_valid", "==", "'true'", ":", "return", "True", "else", ":", "logging", ".", "error", "(", "'Server responds that checkAuth call is not valid'", ")", "return", "False" ]
Process the response message from a check_authentication request, invalidating associations if requested.
[ "Process", "the", "response", "message", "from", "a", "check_authentication", "request", "invalidating", "associations", "if", "requested", "." ]
f7e13536f0d1828d3cef5ae7a7b55cabadff37fc
https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/consumer/consumer.py#L1125-L1145
16,634
openid/python-openid
openid/consumer/consumer.py
GenericConsumer._getAssociation
def _getAssociation(self, endpoint): """Get an association for the endpoint's server_url. First try seeing if we have a good association in the store. If we do not, then attempt to negotiate an association with the server. If we negotiate a good association, it will get stored. @returns: A valid association for the endpoint's server_url or None @rtype: openid.association.Association or NoneType """ assoc = self.store.getAssociation(endpoint.server_url) if assoc is None or assoc.expiresIn <= 0: assoc = self._negotiateAssociation(endpoint) if assoc is not None: self.store.storeAssociation(endpoint.server_url, assoc) return assoc
python
def _getAssociation(self, endpoint): """Get an association for the endpoint's server_url. First try seeing if we have a good association in the store. If we do not, then attempt to negotiate an association with the server. If we negotiate a good association, it will get stored. @returns: A valid association for the endpoint's server_url or None @rtype: openid.association.Association or NoneType """ assoc = self.store.getAssociation(endpoint.server_url) if assoc is None or assoc.expiresIn <= 0: assoc = self._negotiateAssociation(endpoint) if assoc is not None: self.store.storeAssociation(endpoint.server_url, assoc) return assoc
[ "def", "_getAssociation", "(", "self", ",", "endpoint", ")", ":", "assoc", "=", "self", ".", "store", ".", "getAssociation", "(", "endpoint", ".", "server_url", ")", "if", "assoc", "is", "None", "or", "assoc", ".", "expiresIn", "<=", "0", ":", "assoc", "=", "self", ".", "_negotiateAssociation", "(", "endpoint", ")", "if", "assoc", "is", "not", "None", ":", "self", ".", "store", ".", "storeAssociation", "(", "endpoint", ".", "server_url", ",", "assoc", ")", "return", "assoc" ]
Get an association for the endpoint's server_url. First try seeing if we have a good association in the store. If we do not, then attempt to negotiate an association with the server. If we negotiate a good association, it will get stored. @returns: A valid association for the endpoint's server_url or None @rtype: openid.association.Association or NoneType
[ "Get", "an", "association", "for", "the", "endpoint", "s", "server_url", "." ]
f7e13536f0d1828d3cef5ae7a7b55cabadff37fc
https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/consumer/consumer.py#L1147-L1166
16,635
openid/python-openid
openid/consumer/consumer.py
GenericConsumer._extractSupportedAssociationType
def _extractSupportedAssociationType(self, server_error, endpoint, assoc_type): """Handle ServerErrors resulting from association requests. @returns: If server replied with an C{unsupported-type} error, return a tuple of supported C{association_type}, C{session_type}. Otherwise logs the error and returns None. @rtype: tuple or None """ # Any error message whose code is not 'unsupported-type' # should be considered a total failure. if server_error.error_code != 'unsupported-type' or \ server_error.message.isOpenID1(): logging.error( 'Server error when requesting an association from %r: %s' % (endpoint.server_url, server_error.error_text)) return None # The server didn't like the association/session type # that we sent, and it sent us back a message that # might tell us how to handle it. logging.error( 'Unsupported association type %s: %s' % (assoc_type, server_error.error_text,)) # Extract the session_type and assoc_type from the # error message assoc_type = server_error.message.getArg(OPENID_NS, 'assoc_type') session_type = server_error.message.getArg(OPENID_NS, 'session_type') if assoc_type is None or session_type is None: logging.error('Server responded with unsupported association ' 'session but did not supply a fallback.') return None elif not self.negotiator.isAllowed(assoc_type, session_type): fmt = ('Server sent unsupported session/association type: ' 'session_type=%s, assoc_type=%s') logging.error(fmt % (session_type, assoc_type)) return None else: return assoc_type, session_type
python
def _extractSupportedAssociationType(self, server_error, endpoint, assoc_type): """Handle ServerErrors resulting from association requests. @returns: If server replied with an C{unsupported-type} error, return a tuple of supported C{association_type}, C{session_type}. Otherwise logs the error and returns None. @rtype: tuple or None """ # Any error message whose code is not 'unsupported-type' # should be considered a total failure. if server_error.error_code != 'unsupported-type' or \ server_error.message.isOpenID1(): logging.error( 'Server error when requesting an association from %r: %s' % (endpoint.server_url, server_error.error_text)) return None # The server didn't like the association/session type # that we sent, and it sent us back a message that # might tell us how to handle it. logging.error( 'Unsupported association type %s: %s' % (assoc_type, server_error.error_text,)) # Extract the session_type and assoc_type from the # error message assoc_type = server_error.message.getArg(OPENID_NS, 'assoc_type') session_type = server_error.message.getArg(OPENID_NS, 'session_type') if assoc_type is None or session_type is None: logging.error('Server responded with unsupported association ' 'session but did not supply a fallback.') return None elif not self.negotiator.isAllowed(assoc_type, session_type): fmt = ('Server sent unsupported session/association type: ' 'session_type=%s, assoc_type=%s') logging.error(fmt % (session_type, assoc_type)) return None else: return assoc_type, session_type
[ "def", "_extractSupportedAssociationType", "(", "self", ",", "server_error", ",", "endpoint", ",", "assoc_type", ")", ":", "# Any error message whose code is not 'unsupported-type'", "# should be considered a total failure.", "if", "server_error", ".", "error_code", "!=", "'unsupported-type'", "or", "server_error", ".", "message", ".", "isOpenID1", "(", ")", ":", "logging", ".", "error", "(", "'Server error when requesting an association from %r: %s'", "%", "(", "endpoint", ".", "server_url", ",", "server_error", ".", "error_text", ")", ")", "return", "None", "# The server didn't like the association/session type", "# that we sent, and it sent us back a message that", "# might tell us how to handle it.", "logging", ".", "error", "(", "'Unsupported association type %s: %s'", "%", "(", "assoc_type", ",", "server_error", ".", "error_text", ",", ")", ")", "# Extract the session_type and assoc_type from the", "# error message", "assoc_type", "=", "server_error", ".", "message", ".", "getArg", "(", "OPENID_NS", ",", "'assoc_type'", ")", "session_type", "=", "server_error", ".", "message", ".", "getArg", "(", "OPENID_NS", ",", "'session_type'", ")", "if", "assoc_type", "is", "None", "or", "session_type", "is", "None", ":", "logging", ".", "error", "(", "'Server responded with unsupported association '", "'session but did not supply a fallback.'", ")", "return", "None", "elif", "not", "self", ".", "negotiator", ".", "isAllowed", "(", "assoc_type", ",", "session_type", ")", ":", "fmt", "=", "(", "'Server sent unsupported session/association type: '", "'session_type=%s, assoc_type=%s'", ")", "logging", ".", "error", "(", "fmt", "%", "(", "session_type", ",", "assoc_type", ")", ")", "return", "None", "else", ":", "return", "assoc_type", ",", "session_type" ]
Handle ServerErrors resulting from association requests. @returns: If server replied with an C{unsupported-type} error, return a tuple of supported C{association_type}, C{session_type}. Otherwise logs the error and returns None. @rtype: tuple or None
[ "Handle", "ServerErrors", "resulting", "from", "association", "requests", "." ]
f7e13536f0d1828d3cef5ae7a7b55cabadff37fc
https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/consumer/consumer.py#L1207-L1247
16,636
openid/python-openid
openid/consumer/consumer.py
GenericConsumer._requestAssociation
def _requestAssociation(self, endpoint, assoc_type, session_type): """Make and process one association request to this endpoint's OP endpoint URL. @returns: An association object or None if the association processing failed. @raises ServerError: when the remote OpenID server returns an error. """ assoc_session, args = self._createAssociateRequest( endpoint, assoc_type, session_type) try: response = self._makeKVPost(args, endpoint.server_url) except fetchers.HTTPFetchingError, why: logging.exception('openid.associate request failed: %s' % (why[0],)) return None try: assoc = self._extractAssociation(response, assoc_session) except KeyError, why: logging.exception('Missing required parameter in response from %s: %s' % (endpoint.server_url, why[0])) return None except ProtocolError, why: logging.exception('Protocol error parsing response from %s: %s' % ( endpoint.server_url, why[0])) return None else: return assoc
python
def _requestAssociation(self, endpoint, assoc_type, session_type): """Make and process one association request to this endpoint's OP endpoint URL. @returns: An association object or None if the association processing failed. @raises ServerError: when the remote OpenID server returns an error. """ assoc_session, args = self._createAssociateRequest( endpoint, assoc_type, session_type) try: response = self._makeKVPost(args, endpoint.server_url) except fetchers.HTTPFetchingError, why: logging.exception('openid.associate request failed: %s' % (why[0],)) return None try: assoc = self._extractAssociation(response, assoc_session) except KeyError, why: logging.exception('Missing required parameter in response from %s: %s' % (endpoint.server_url, why[0])) return None except ProtocolError, why: logging.exception('Protocol error parsing response from %s: %s' % ( endpoint.server_url, why[0])) return None else: return assoc
[ "def", "_requestAssociation", "(", "self", ",", "endpoint", ",", "assoc_type", ",", "session_type", ")", ":", "assoc_session", ",", "args", "=", "self", ".", "_createAssociateRequest", "(", "endpoint", ",", "assoc_type", ",", "session_type", ")", "try", ":", "response", "=", "self", ".", "_makeKVPost", "(", "args", ",", "endpoint", ".", "server_url", ")", "except", "fetchers", ".", "HTTPFetchingError", ",", "why", ":", "logging", ".", "exception", "(", "'openid.associate request failed: %s'", "%", "(", "why", "[", "0", "]", ",", ")", ")", "return", "None", "try", ":", "assoc", "=", "self", ".", "_extractAssociation", "(", "response", ",", "assoc_session", ")", "except", "KeyError", ",", "why", ":", "logging", ".", "exception", "(", "'Missing required parameter in response from %s: %s'", "%", "(", "endpoint", ".", "server_url", ",", "why", "[", "0", "]", ")", ")", "return", "None", "except", "ProtocolError", ",", "why", ":", "logging", ".", "exception", "(", "'Protocol error parsing response from %s: %s'", "%", "(", "endpoint", ".", "server_url", ",", "why", "[", "0", "]", ")", ")", "return", "None", "else", ":", "return", "assoc" ]
Make and process one association request to this endpoint's OP endpoint URL. @returns: An association object or None if the association processing failed. @raises ServerError: when the remote OpenID server returns an error.
[ "Make", "and", "process", "one", "association", "request", "to", "this", "endpoint", "s", "OP", "endpoint", "URL", "." ]
f7e13536f0d1828d3cef5ae7a7b55cabadff37fc
https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/consumer/consumer.py#L1250-L1279
16,637
openid/python-openid
openid/consumer/consumer.py
GenericConsumer._createAssociateRequest
def _createAssociateRequest(self, endpoint, assoc_type, session_type): """Create an association request for the given assoc_type and session_type. @param endpoint: The endpoint whose server_url will be queried. The important bit about the endpoint is whether it's in compatiblity mode (OpenID 1.1) @param assoc_type: The association type that the request should ask for. @type assoc_type: str @param session_type: The session type that should be used in the association request. The session_type is used to create an association session object, and that session object is asked for any additional fields that it needs to add to the request. @type session_type: str @returns: a pair of the association session object and the request message that will be sent to the server. @rtype: (association session type (depends on session_type), openid.message.Message) """ session_type_class = self.session_types[session_type] assoc_session = session_type_class() args = { 'mode': 'associate', 'assoc_type': assoc_type, } if not endpoint.compatibilityMode(): args['ns'] = OPENID2_NS # Leave out the session type if we're in compatibility mode # *and* it's no-encryption. if (not endpoint.compatibilityMode() or assoc_session.session_type != 'no-encryption'): args['session_type'] = assoc_session.session_type args.update(assoc_session.getRequest()) message = Message.fromOpenIDArgs(args) return assoc_session, message
python
def _createAssociateRequest(self, endpoint, assoc_type, session_type): """Create an association request for the given assoc_type and session_type. @param endpoint: The endpoint whose server_url will be queried. The important bit about the endpoint is whether it's in compatiblity mode (OpenID 1.1) @param assoc_type: The association type that the request should ask for. @type assoc_type: str @param session_type: The session type that should be used in the association request. The session_type is used to create an association session object, and that session object is asked for any additional fields that it needs to add to the request. @type session_type: str @returns: a pair of the association session object and the request message that will be sent to the server. @rtype: (association session type (depends on session_type), openid.message.Message) """ session_type_class = self.session_types[session_type] assoc_session = session_type_class() args = { 'mode': 'associate', 'assoc_type': assoc_type, } if not endpoint.compatibilityMode(): args['ns'] = OPENID2_NS # Leave out the session type if we're in compatibility mode # *and* it's no-encryption. if (not endpoint.compatibilityMode() or assoc_session.session_type != 'no-encryption'): args['session_type'] = assoc_session.session_type args.update(assoc_session.getRequest()) message = Message.fromOpenIDArgs(args) return assoc_session, message
[ "def", "_createAssociateRequest", "(", "self", ",", "endpoint", ",", "assoc_type", ",", "session_type", ")", ":", "session_type_class", "=", "self", ".", "session_types", "[", "session_type", "]", "assoc_session", "=", "session_type_class", "(", ")", "args", "=", "{", "'mode'", ":", "'associate'", ",", "'assoc_type'", ":", "assoc_type", ",", "}", "if", "not", "endpoint", ".", "compatibilityMode", "(", ")", ":", "args", "[", "'ns'", "]", "=", "OPENID2_NS", "# Leave out the session type if we're in compatibility mode", "# *and* it's no-encryption.", "if", "(", "not", "endpoint", ".", "compatibilityMode", "(", ")", "or", "assoc_session", ".", "session_type", "!=", "'no-encryption'", ")", ":", "args", "[", "'session_type'", "]", "=", "assoc_session", ".", "session_type", "args", ".", "update", "(", "assoc_session", ".", "getRequest", "(", ")", ")", "message", "=", "Message", ".", "fromOpenIDArgs", "(", "args", ")", "return", "assoc_session", ",", "message" ]
Create an association request for the given assoc_type and session_type. @param endpoint: The endpoint whose server_url will be queried. The important bit about the endpoint is whether it's in compatiblity mode (OpenID 1.1) @param assoc_type: The association type that the request should ask for. @type assoc_type: str @param session_type: The session type that should be used in the association request. The session_type is used to create an association session object, and that session object is asked for any additional fields that it needs to add to the request. @type session_type: str @returns: a pair of the association session object and the request message that will be sent to the server. @rtype: (association session type (depends on session_type), openid.message.Message)
[ "Create", "an", "association", "request", "for", "the", "given", "assoc_type", "and", "session_type", "." ]
f7e13536f0d1828d3cef5ae7a7b55cabadff37fc
https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/consumer/consumer.py#L1281-L1324
16,638
openid/python-openid
openid/consumer/consumer.py
GenericConsumer._extractAssociation
def _extractAssociation(self, assoc_response, assoc_session): """Attempt to extract an association from the response, given the association response message and the established association session. @param assoc_response: The association response message from the server @type assoc_response: openid.message.Message @param assoc_session: The association session object that was used when making the request @type assoc_session: depends on the session type of the request @raises ProtocolError: when data is malformed @raises KeyError: when a field is missing @rtype: openid.association.Association """ # Extract the common fields from the response, raising an # exception if they are not found assoc_type = assoc_response.getArg( OPENID_NS, 'assoc_type', no_default) assoc_handle = assoc_response.getArg( OPENID_NS, 'assoc_handle', no_default) # expires_in is a base-10 string. The Python parsing will # accept literals that have whitespace around them and will # accept negative values. Neither of these are really in-spec, # but we think it's OK to accept them. expires_in_str = assoc_response.getArg( OPENID_NS, 'expires_in', no_default) try: expires_in = int(expires_in_str) except ValueError, why: raise ProtocolError('Invalid expires_in field: %s' % (why[0],)) # OpenID 1 has funny association session behaviour. if assoc_response.isOpenID1(): session_type = self._getOpenID1SessionType(assoc_response) else: session_type = assoc_response.getArg( OPENID2_NS, 'session_type', no_default) # Session type mismatch if assoc_session.session_type != session_type: if (assoc_response.isOpenID1() and session_type == 'no-encryption'): # In OpenID 1, any association request can result in a # 'no-encryption' association response. Setting # assoc_session to a new no-encryption session should # make the rest of this function work properly for # that case. assoc_session = PlainTextConsumerSession() else: # Any other mismatch, regardless of protocol version # results in the failure of the association session # altogether. fmt = 'Session type mismatch. Expected %r, got %r' message = fmt % (assoc_session.session_type, session_type) raise ProtocolError(message) # Make sure assoc_type is valid for session_type if assoc_type not in assoc_session.allowed_assoc_types: fmt = 'Unsupported assoc_type for session %s returned: %s' raise ProtocolError(fmt % (assoc_session.session_type, assoc_type)) # Delegate to the association session to extract the secret # from the response, however is appropriate for that session # type. try: secret = assoc_session.extractSecret(assoc_response) except ValueError, why: fmt = 'Malformed response for %s session: %s' raise ProtocolError(fmt % (assoc_session.session_type, why[0])) return Association.fromExpiresIn( expires_in, assoc_handle, secret, assoc_type)
python
def _extractAssociation(self, assoc_response, assoc_session): """Attempt to extract an association from the response, given the association response message and the established association session. @param assoc_response: The association response message from the server @type assoc_response: openid.message.Message @param assoc_session: The association session object that was used when making the request @type assoc_session: depends on the session type of the request @raises ProtocolError: when data is malformed @raises KeyError: when a field is missing @rtype: openid.association.Association """ # Extract the common fields from the response, raising an # exception if they are not found assoc_type = assoc_response.getArg( OPENID_NS, 'assoc_type', no_default) assoc_handle = assoc_response.getArg( OPENID_NS, 'assoc_handle', no_default) # expires_in is a base-10 string. The Python parsing will # accept literals that have whitespace around them and will # accept negative values. Neither of these are really in-spec, # but we think it's OK to accept them. expires_in_str = assoc_response.getArg( OPENID_NS, 'expires_in', no_default) try: expires_in = int(expires_in_str) except ValueError, why: raise ProtocolError('Invalid expires_in field: %s' % (why[0],)) # OpenID 1 has funny association session behaviour. if assoc_response.isOpenID1(): session_type = self._getOpenID1SessionType(assoc_response) else: session_type = assoc_response.getArg( OPENID2_NS, 'session_type', no_default) # Session type mismatch if assoc_session.session_type != session_type: if (assoc_response.isOpenID1() and session_type == 'no-encryption'): # In OpenID 1, any association request can result in a # 'no-encryption' association response. Setting # assoc_session to a new no-encryption session should # make the rest of this function work properly for # that case. assoc_session = PlainTextConsumerSession() else: # Any other mismatch, regardless of protocol version # results in the failure of the association session # altogether. fmt = 'Session type mismatch. Expected %r, got %r' message = fmt % (assoc_session.session_type, session_type) raise ProtocolError(message) # Make sure assoc_type is valid for session_type if assoc_type not in assoc_session.allowed_assoc_types: fmt = 'Unsupported assoc_type for session %s returned: %s' raise ProtocolError(fmt % (assoc_session.session_type, assoc_type)) # Delegate to the association session to extract the secret # from the response, however is appropriate for that session # type. try: secret = assoc_session.extractSecret(assoc_response) except ValueError, why: fmt = 'Malformed response for %s session: %s' raise ProtocolError(fmt % (assoc_session.session_type, why[0])) return Association.fromExpiresIn( expires_in, assoc_handle, secret, assoc_type)
[ "def", "_extractAssociation", "(", "self", ",", "assoc_response", ",", "assoc_session", ")", ":", "# Extract the common fields from the response, raising an", "# exception if they are not found", "assoc_type", "=", "assoc_response", ".", "getArg", "(", "OPENID_NS", ",", "'assoc_type'", ",", "no_default", ")", "assoc_handle", "=", "assoc_response", ".", "getArg", "(", "OPENID_NS", ",", "'assoc_handle'", ",", "no_default", ")", "# expires_in is a base-10 string. The Python parsing will", "# accept literals that have whitespace around them and will", "# accept negative values. Neither of these are really in-spec,", "# but we think it's OK to accept them.", "expires_in_str", "=", "assoc_response", ".", "getArg", "(", "OPENID_NS", ",", "'expires_in'", ",", "no_default", ")", "try", ":", "expires_in", "=", "int", "(", "expires_in_str", ")", "except", "ValueError", ",", "why", ":", "raise", "ProtocolError", "(", "'Invalid expires_in field: %s'", "%", "(", "why", "[", "0", "]", ",", ")", ")", "# OpenID 1 has funny association session behaviour.", "if", "assoc_response", ".", "isOpenID1", "(", ")", ":", "session_type", "=", "self", ".", "_getOpenID1SessionType", "(", "assoc_response", ")", "else", ":", "session_type", "=", "assoc_response", ".", "getArg", "(", "OPENID2_NS", ",", "'session_type'", ",", "no_default", ")", "# Session type mismatch", "if", "assoc_session", ".", "session_type", "!=", "session_type", ":", "if", "(", "assoc_response", ".", "isOpenID1", "(", ")", "and", "session_type", "==", "'no-encryption'", ")", ":", "# In OpenID 1, any association request can result in a", "# 'no-encryption' association response. Setting", "# assoc_session to a new no-encryption session should", "# make the rest of this function work properly for", "# that case.", "assoc_session", "=", "PlainTextConsumerSession", "(", ")", "else", ":", "# Any other mismatch, regardless of protocol version", "# results in the failure of the association session", "# altogether.", "fmt", "=", "'Session type mismatch. Expected %r, got %r'", "message", "=", "fmt", "%", "(", "assoc_session", ".", "session_type", ",", "session_type", ")", "raise", "ProtocolError", "(", "message", ")", "# Make sure assoc_type is valid for session_type", "if", "assoc_type", "not", "in", "assoc_session", ".", "allowed_assoc_types", ":", "fmt", "=", "'Unsupported assoc_type for session %s returned: %s'", "raise", "ProtocolError", "(", "fmt", "%", "(", "assoc_session", ".", "session_type", ",", "assoc_type", ")", ")", "# Delegate to the association session to extract the secret", "# from the response, however is appropriate for that session", "# type.", "try", ":", "secret", "=", "assoc_session", ".", "extractSecret", "(", "assoc_response", ")", "except", "ValueError", ",", "why", ":", "fmt", "=", "'Malformed response for %s session: %s'", "raise", "ProtocolError", "(", "fmt", "%", "(", "assoc_session", ".", "session_type", ",", "why", "[", "0", "]", ")", ")", "return", "Association", ".", "fromExpiresIn", "(", "expires_in", ",", "assoc_handle", ",", "secret", ",", "assoc_type", ")" ]
Attempt to extract an association from the response, given the association response message and the established association session. @param assoc_response: The association response message from the server @type assoc_response: openid.message.Message @param assoc_session: The association session object that was used when making the request @type assoc_session: depends on the session type of the request @raises ProtocolError: when data is malformed @raises KeyError: when a field is missing @rtype: openid.association.Association
[ "Attempt", "to", "extract", "an", "association", "from", "the", "response", "given", "the", "association", "response", "message", "and", "the", "established", "association", "session", "." ]
f7e13536f0d1828d3cef5ae7a7b55cabadff37fc
https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/consumer/consumer.py#L1364-L1440
16,639
openid/python-openid
openid/consumer/consumer.py
AuthRequest.setAnonymous
def setAnonymous(self, is_anonymous): """Set whether this request should be made anonymously. If a request is anonymous, the identifier will not be sent in the request. This is only useful if you are making another kind of request with an extension in this request. Anonymous requests are not allowed when the request is made with OpenID 1. @raises ValueError: when attempting to set an OpenID1 request as anonymous """ if is_anonymous and self.message.isOpenID1(): raise ValueError('OpenID 1 requests MUST include the ' 'identifier in the request') else: self._anonymous = is_anonymous
python
def setAnonymous(self, is_anonymous): """Set whether this request should be made anonymously. If a request is anonymous, the identifier will not be sent in the request. This is only useful if you are making another kind of request with an extension in this request. Anonymous requests are not allowed when the request is made with OpenID 1. @raises ValueError: when attempting to set an OpenID1 request as anonymous """ if is_anonymous and self.message.isOpenID1(): raise ValueError('OpenID 1 requests MUST include the ' 'identifier in the request') else: self._anonymous = is_anonymous
[ "def", "setAnonymous", "(", "self", ",", "is_anonymous", ")", ":", "if", "is_anonymous", "and", "self", ".", "message", ".", "isOpenID1", "(", ")", ":", "raise", "ValueError", "(", "'OpenID 1 requests MUST include the '", "'identifier in the request'", ")", "else", ":", "self", ".", "_anonymous", "=", "is_anonymous" ]
Set whether this request should be made anonymously. If a request is anonymous, the identifier will not be sent in the request. This is only useful if you are making another kind of request with an extension in this request. Anonymous requests are not allowed when the request is made with OpenID 1. @raises ValueError: when attempting to set an OpenID1 request as anonymous
[ "Set", "whether", "this", "request", "should", "be", "made", "anonymously", ".", "If", "a", "request", "is", "anonymous", "the", "identifier", "will", "not", "be", "sent", "in", "the", "request", ".", "This", "is", "only", "useful", "if", "you", "are", "making", "another", "kind", "of", "request", "with", "an", "extension", "in", "this", "request", "." ]
f7e13536f0d1828d3cef5ae7a7b55cabadff37fc
https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/consumer/consumer.py#L1469-L1485
16,640
openid/python-openid
openid/consumer/consumer.py
AuthRequest.addExtensionArg
def addExtensionArg(self, namespace, key, value): """Add an extension argument to this OpenID authentication request. Use caution when adding arguments, because they will be URL-escaped and appended to the redirect URL, which can easily get quite long. @param namespace: The namespace for the extension. For example, the simple registration extension uses the namespace C{sreg}. @type namespace: str @param key: The key within the extension namespace. For example, the nickname field in the simple registration extension's key is C{nickname}. @type key: str @param value: The value to provide to the server for this argument. @type value: str """ self.message.setArg(namespace, key, value)
python
def addExtensionArg(self, namespace, key, value): """Add an extension argument to this OpenID authentication request. Use caution when adding arguments, because they will be URL-escaped and appended to the redirect URL, which can easily get quite long. @param namespace: The namespace for the extension. For example, the simple registration extension uses the namespace C{sreg}. @type namespace: str @param key: The key within the extension namespace. For example, the nickname field in the simple registration extension's key is C{nickname}. @type key: str @param value: The value to provide to the server for this argument. @type value: str """ self.message.setArg(namespace, key, value)
[ "def", "addExtensionArg", "(", "self", ",", "namespace", ",", "key", ",", "value", ")", ":", "self", ".", "message", ".", "setArg", "(", "namespace", ",", "key", ",", "value", ")" ]
Add an extension argument to this OpenID authentication request. Use caution when adding arguments, because they will be URL-escaped and appended to the redirect URL, which can easily get quite long. @param namespace: The namespace for the extension. For example, the simple registration extension uses the namespace C{sreg}. @type namespace: str @param key: The key within the extension namespace. For example, the nickname field in the simple registration extension's key is C{nickname}. @type key: str @param value: The value to provide to the server for this argument. @type value: str
[ "Add", "an", "extension", "argument", "to", "this", "OpenID", "authentication", "request", "." ]
f7e13536f0d1828d3cef5ae7a7b55cabadff37fc
https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/consumer/consumer.py#L1496-L1521
16,641
openid/python-openid
openid/consumer/consumer.py
AuthRequest.redirectURL
def redirectURL(self, realm, return_to=None, immediate=False): """Returns a URL with an encoded OpenID request. The resulting URL is the OpenID provider's endpoint URL with parameters appended as query arguments. You should redirect the user agent to this URL. OpenID 2.0 endpoints also accept POST requests, see C{L{shouldSendRedirect}} and C{L{formMarkup}}. @param realm: The URL (or URL pattern) that identifies your web site to the user when she is authorizing it. @type realm: str @param return_to: The URL that the OpenID provider will send the user back to after attempting to verify her identity. Not specifying a return_to URL means that the user will not be returned to the site issuing the request upon its completion. @type return_to: str @param immediate: If True, the OpenID provider is to send back a response immediately, useful for behind-the-scenes authentication attempts. Otherwise the OpenID provider may engage the user before providing a response. This is the default case, as the user may need to provide credentials or approve the request before a positive response can be sent. @type immediate: bool @returns: The URL to redirect the user agent to. @returntype: str """ message = self.getMessage(realm, return_to, immediate) return message.toURL(self.endpoint.server_url)
python
def redirectURL(self, realm, return_to=None, immediate=False): """Returns a URL with an encoded OpenID request. The resulting URL is the OpenID provider's endpoint URL with parameters appended as query arguments. You should redirect the user agent to this URL. OpenID 2.0 endpoints also accept POST requests, see C{L{shouldSendRedirect}} and C{L{formMarkup}}. @param realm: The URL (or URL pattern) that identifies your web site to the user when she is authorizing it. @type realm: str @param return_to: The URL that the OpenID provider will send the user back to after attempting to verify her identity. Not specifying a return_to URL means that the user will not be returned to the site issuing the request upon its completion. @type return_to: str @param immediate: If True, the OpenID provider is to send back a response immediately, useful for behind-the-scenes authentication attempts. Otherwise the OpenID provider may engage the user before providing a response. This is the default case, as the user may need to provide credentials or approve the request before a positive response can be sent. @type immediate: bool @returns: The URL to redirect the user agent to. @returntype: str """ message = self.getMessage(realm, return_to, immediate) return message.toURL(self.endpoint.server_url)
[ "def", "redirectURL", "(", "self", ",", "realm", ",", "return_to", "=", "None", ",", "immediate", "=", "False", ")", ":", "message", "=", "self", ".", "getMessage", "(", "realm", ",", "return_to", ",", "immediate", ")", "return", "message", ".", "toURL", "(", "self", ".", "endpoint", ".", "server_url", ")" ]
Returns a URL with an encoded OpenID request. The resulting URL is the OpenID provider's endpoint URL with parameters appended as query arguments. You should redirect the user agent to this URL. OpenID 2.0 endpoints also accept POST requests, see C{L{shouldSendRedirect}} and C{L{formMarkup}}. @param realm: The URL (or URL pattern) that identifies your web site to the user when she is authorizing it. @type realm: str @param return_to: The URL that the OpenID provider will send the user back to after attempting to verify her identity. Not specifying a return_to URL means that the user will not be returned to the site issuing the request upon its completion. @type return_to: str @param immediate: If True, the OpenID provider is to send back a response immediately, useful for behind-the-scenes authentication attempts. Otherwise the OpenID provider may engage the user before providing a response. This is the default case, as the user may need to provide credentials or approve the request before a positive response can be sent. @type immediate: bool @returns: The URL to redirect the user agent to. @returntype: str
[ "Returns", "a", "URL", "with", "an", "encoded", "OpenID", "request", "." ]
f7e13536f0d1828d3cef5ae7a7b55cabadff37fc
https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/consumer/consumer.py#L1608-L1647
16,642
openid/python-openid
openid/consumer/consumer.py
AuthRequest.formMarkup
def formMarkup(self, realm, return_to=None, immediate=False, form_tag_attrs=None): """Get html for a form to submit this request to the IDP. @param form_tag_attrs: Dictionary of attributes to be added to the form tag. 'accept-charset' and 'enctype' have defaults that can be overridden. If a value is supplied for 'action' or 'method', it will be replaced. @type form_tag_attrs: {unicode: unicode} """ message = self.getMessage(realm, return_to, immediate) return message.toFormMarkup(self.endpoint.server_url, form_tag_attrs)
python
def formMarkup(self, realm, return_to=None, immediate=False, form_tag_attrs=None): """Get html for a form to submit this request to the IDP. @param form_tag_attrs: Dictionary of attributes to be added to the form tag. 'accept-charset' and 'enctype' have defaults that can be overridden. If a value is supplied for 'action' or 'method', it will be replaced. @type form_tag_attrs: {unicode: unicode} """ message = self.getMessage(realm, return_to, immediate) return message.toFormMarkup(self.endpoint.server_url, form_tag_attrs)
[ "def", "formMarkup", "(", "self", ",", "realm", ",", "return_to", "=", "None", ",", "immediate", "=", "False", ",", "form_tag_attrs", "=", "None", ")", ":", "message", "=", "self", ".", "getMessage", "(", "realm", ",", "return_to", ",", "immediate", ")", "return", "message", ".", "toFormMarkup", "(", "self", ".", "endpoint", ".", "server_url", ",", "form_tag_attrs", ")" ]
Get html for a form to submit this request to the IDP. @param form_tag_attrs: Dictionary of attributes to be added to the form tag. 'accept-charset' and 'enctype' have defaults that can be overridden. If a value is supplied for 'action' or 'method', it will be replaced. @type form_tag_attrs: {unicode: unicode}
[ "Get", "html", "for", "a", "form", "to", "submit", "this", "request", "to", "the", "IDP", "." ]
f7e13536f0d1828d3cef5ae7a7b55cabadff37fc
https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/consumer/consumer.py#L1649-L1661
16,643
openid/python-openid
openid/consumer/consumer.py
AuthRequest.htmlMarkup
def htmlMarkup(self, realm, return_to=None, immediate=False, form_tag_attrs=None): """Get an autosubmitting HTML page that submits this request to the IDP. This is just a wrapper for formMarkup. @see: formMarkup @returns: str """ return oidutil.autoSubmitHTML(self.formMarkup(realm, return_to, immediate, form_tag_attrs))
python
def htmlMarkup(self, realm, return_to=None, immediate=False, form_tag_attrs=None): """Get an autosubmitting HTML page that submits this request to the IDP. This is just a wrapper for formMarkup. @see: formMarkup @returns: str """ return oidutil.autoSubmitHTML(self.formMarkup(realm, return_to, immediate, form_tag_attrs))
[ "def", "htmlMarkup", "(", "self", ",", "realm", ",", "return_to", "=", "None", ",", "immediate", "=", "False", ",", "form_tag_attrs", "=", "None", ")", ":", "return", "oidutil", ".", "autoSubmitHTML", "(", "self", ".", "formMarkup", "(", "realm", ",", "return_to", ",", "immediate", ",", "form_tag_attrs", ")", ")" ]
Get an autosubmitting HTML page that submits this request to the IDP. This is just a wrapper for formMarkup. @see: formMarkup @returns: str
[ "Get", "an", "autosubmitting", "HTML", "page", "that", "submits", "this", "request", "to", "the", "IDP", ".", "This", "is", "just", "a", "wrapper", "for", "formMarkup", "." ]
f7e13536f0d1828d3cef5ae7a7b55cabadff37fc
https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/consumer/consumer.py#L1663-L1675
16,644
openid/python-openid
openid/consumer/consumer.py
SuccessResponse.isSigned
def isSigned(self, ns_uri, ns_key): """Return whether a particular key is signed, regardless of its namespace alias """ return self.message.getKey(ns_uri, ns_key) in self.signed_fields
python
def isSigned(self, ns_uri, ns_key): """Return whether a particular key is signed, regardless of its namespace alias """ return self.message.getKey(ns_uri, ns_key) in self.signed_fields
[ "def", "isSigned", "(", "self", ",", "ns_uri", ",", "ns_key", ")", ":", "return", "self", ".", "message", ".", "getKey", "(", "ns_uri", ",", "ns_key", ")", "in", "self", ".", "signed_fields" ]
Return whether a particular key is signed, regardless of its namespace alias
[ "Return", "whether", "a", "particular", "key", "is", "signed", "regardless", "of", "its", "namespace", "alias" ]
f7e13536f0d1828d3cef5ae7a7b55cabadff37fc
https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/consumer/consumer.py#L1759-L1763
16,645
openid/python-openid
openid/consumer/consumer.py
SuccessResponse.getSigned
def getSigned(self, ns_uri, ns_key, default=None): """Return the specified signed field if available, otherwise return default """ if self.isSigned(ns_uri, ns_key): return self.message.getArg(ns_uri, ns_key, default) else: return default
python
def getSigned(self, ns_uri, ns_key, default=None): """Return the specified signed field if available, otherwise return default """ if self.isSigned(ns_uri, ns_key): return self.message.getArg(ns_uri, ns_key, default) else: return default
[ "def", "getSigned", "(", "self", ",", "ns_uri", ",", "ns_key", ",", "default", "=", "None", ")", ":", "if", "self", ".", "isSigned", "(", "ns_uri", ",", "ns_key", ")", ":", "return", "self", ".", "message", ".", "getArg", "(", "ns_uri", ",", "ns_key", ",", "default", ")", "else", ":", "return", "default" ]
Return the specified signed field if available, otherwise return default
[ "Return", "the", "specified", "signed", "field", "if", "available", "otherwise", "return", "default" ]
f7e13536f0d1828d3cef5ae7a7b55cabadff37fc
https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/consumer/consumer.py#L1765-L1772
16,646
openid/python-openid
openid/consumer/consumer.py
SuccessResponse.getSignedNS
def getSignedNS(self, ns_uri): """Get signed arguments from the response message. Return a dict of all arguments in the specified namespace. If any of the arguments are not signed, return None. """ msg_args = self.message.getArgs(ns_uri) for key in msg_args.iterkeys(): if not self.isSigned(ns_uri, key): logging.info("SuccessResponse.getSignedNS: (%s, %s) not signed." % (ns_uri, key)) return None return msg_args
python
def getSignedNS(self, ns_uri): """Get signed arguments from the response message. Return a dict of all arguments in the specified namespace. If any of the arguments are not signed, return None. """ msg_args = self.message.getArgs(ns_uri) for key in msg_args.iterkeys(): if not self.isSigned(ns_uri, key): logging.info("SuccessResponse.getSignedNS: (%s, %s) not signed." % (ns_uri, key)) return None return msg_args
[ "def", "getSignedNS", "(", "self", ",", "ns_uri", ")", ":", "msg_args", "=", "self", ".", "message", ".", "getArgs", "(", "ns_uri", ")", "for", "key", "in", "msg_args", ".", "iterkeys", "(", ")", ":", "if", "not", "self", ".", "isSigned", "(", "ns_uri", ",", "key", ")", ":", "logging", ".", "info", "(", "\"SuccessResponse.getSignedNS: (%s, %s) not signed.\"", "%", "(", "ns_uri", ",", "key", ")", ")", "return", "None", "return", "msg_args" ]
Get signed arguments from the response message. Return a dict of all arguments in the specified namespace. If any of the arguments are not signed, return None.
[ "Get", "signed", "arguments", "from", "the", "response", "message", ".", "Return", "a", "dict", "of", "all", "arguments", "in", "the", "specified", "namespace", ".", "If", "any", "of", "the", "arguments", "are", "not", "signed", "return", "None", "." ]
f7e13536f0d1828d3cef5ae7a7b55cabadff37fc
https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/consumer/consumer.py#L1774-L1787
16,647
openid/python-openid
openid/consumer/consumer.py
SuccessResponse.extensionResponse
def extensionResponse(self, namespace_uri, require_signed): """Return response arguments in the specified namespace. @param namespace_uri: The namespace URI of the arguments to be returned. @param require_signed: True if the arguments should be among those signed in the response, False if you don't care. If require_signed is True and the arguments are not signed, return None. """ if require_signed: return self.getSignedNS(namespace_uri) else: return self.message.getArgs(namespace_uri)
python
def extensionResponse(self, namespace_uri, require_signed): """Return response arguments in the specified namespace. @param namespace_uri: The namespace URI of the arguments to be returned. @param require_signed: True if the arguments should be among those signed in the response, False if you don't care. If require_signed is True and the arguments are not signed, return None. """ if require_signed: return self.getSignedNS(namespace_uri) else: return self.message.getArgs(namespace_uri)
[ "def", "extensionResponse", "(", "self", ",", "namespace_uri", ",", "require_signed", ")", ":", "if", "require_signed", ":", "return", "self", ".", "getSignedNS", "(", "namespace_uri", ")", "else", ":", "return", "self", ".", "message", ".", "getArgs", "(", "namespace_uri", ")" ]
Return response arguments in the specified namespace. @param namespace_uri: The namespace URI of the arguments to be returned. @param require_signed: True if the arguments should be among those signed in the response, False if you don't care. If require_signed is True and the arguments are not signed, return None.
[ "Return", "response", "arguments", "in", "the", "specified", "namespace", "." ]
f7e13536f0d1828d3cef5ae7a7b55cabadff37fc
https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/consumer/consumer.py#L1789-L1804
16,648
openid/python-openid
openid/yadis/filters.py
mkFilter
def mkFilter(parts): """Convert a filter-convertable thing into a filter @param parts: a filter, an endpoint, a callable, or a list of any of these. """ # Convert the parts into a list, and pass to mkCompoundFilter if parts is None: parts = [BasicServiceEndpoint] try: parts = list(parts) except TypeError: return mkCompoundFilter([parts]) else: return mkCompoundFilter(parts)
python
def mkFilter(parts): """Convert a filter-convertable thing into a filter @param parts: a filter, an endpoint, a callable, or a list of any of these. """ # Convert the parts into a list, and pass to mkCompoundFilter if parts is None: parts = [BasicServiceEndpoint] try: parts = list(parts) except TypeError: return mkCompoundFilter([parts]) else: return mkCompoundFilter(parts)
[ "def", "mkFilter", "(", "parts", ")", ":", "# Convert the parts into a list, and pass to mkCompoundFilter", "if", "parts", "is", "None", ":", "parts", "=", "[", "BasicServiceEndpoint", "]", "try", ":", "parts", "=", "list", "(", "parts", ")", "except", "TypeError", ":", "return", "mkCompoundFilter", "(", "[", "parts", "]", ")", "else", ":", "return", "mkCompoundFilter", "(", "parts", ")" ]
Convert a filter-convertable thing into a filter @param parts: a filter, an endpoint, a callable, or a list of any of these.
[ "Convert", "a", "filter", "-", "convertable", "thing", "into", "a", "filter" ]
f7e13536f0d1828d3cef5ae7a7b55cabadff37fc
https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/yadis/filters.py#L146-L160
16,649
openid/python-openid
openid/yadis/filters.py
TransformFilterMaker.getServiceEndpoints
def getServiceEndpoints(self, yadis_url, service_element): """Returns an iterator of endpoint objects produced by the filter functions.""" endpoints = [] # Do an expansion of the service element by xrd:Type and xrd:URI for type_uris, uri, _ in expandService(service_element): # Create a basic endpoint object to represent this # yadis_url, Service, Type, URI combination endpoint = BasicServiceEndpoint( yadis_url, type_uris, uri, service_element) e = self.applyFilters(endpoint) if e is not None: endpoints.append(e) return endpoints
python
def getServiceEndpoints(self, yadis_url, service_element): """Returns an iterator of endpoint objects produced by the filter functions.""" endpoints = [] # Do an expansion of the service element by xrd:Type and xrd:URI for type_uris, uri, _ in expandService(service_element): # Create a basic endpoint object to represent this # yadis_url, Service, Type, URI combination endpoint = BasicServiceEndpoint( yadis_url, type_uris, uri, service_element) e = self.applyFilters(endpoint) if e is not None: endpoints.append(e) return endpoints
[ "def", "getServiceEndpoints", "(", "self", ",", "yadis_url", ",", "service_element", ")", ":", "endpoints", "=", "[", "]", "# Do an expansion of the service element by xrd:Type and xrd:URI", "for", "type_uris", ",", "uri", ",", "_", "in", "expandService", "(", "service_element", ")", ":", "# Create a basic endpoint object to represent this", "# yadis_url, Service, Type, URI combination", "endpoint", "=", "BasicServiceEndpoint", "(", "yadis_url", ",", "type_uris", ",", "uri", ",", "service_element", ")", "e", "=", "self", ".", "applyFilters", "(", "endpoint", ")", "if", "e", "is", "not", "None", ":", "endpoints", ".", "append", "(", "e", ")", "return", "endpoints" ]
Returns an iterator of endpoint objects produced by the filter functions.
[ "Returns", "an", "iterator", "of", "endpoint", "objects", "produced", "by", "the", "filter", "functions", "." ]
f7e13536f0d1828d3cef5ae7a7b55cabadff37fc
https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/yadis/filters.py#L95-L112
16,650
openid/python-openid
openid/yadis/filters.py
TransformFilterMaker.applyFilters
def applyFilters(self, endpoint): """Apply filter functions to an endpoint until one of them returns non-None.""" for filter_function in self.filter_functions: e = filter_function(endpoint) if e is not None: # Once one of the filters has returned an # endpoint, do not apply any more. return e return None
python
def applyFilters(self, endpoint): """Apply filter functions to an endpoint until one of them returns non-None.""" for filter_function in self.filter_functions: e = filter_function(endpoint) if e is not None: # Once one of the filters has returned an # endpoint, do not apply any more. return e return None
[ "def", "applyFilters", "(", "self", ",", "endpoint", ")", ":", "for", "filter_function", "in", "self", ".", "filter_functions", ":", "e", "=", "filter_function", "(", "endpoint", ")", "if", "e", "is", "not", "None", ":", "# Once one of the filters has returned an", "# endpoint, do not apply any more.", "return", "e", "return", "None" ]
Apply filter functions to an endpoint until one of them returns non-None.
[ "Apply", "filter", "functions", "to", "an", "endpoint", "until", "one", "of", "them", "returns", "non", "-", "None", "." ]
f7e13536f0d1828d3cef5ae7a7b55cabadff37fc
https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/yadis/filters.py#L114-L124
16,651
openid/python-openid
openid/yadis/filters.py
CompoundFilter.getServiceEndpoints
def getServiceEndpoints(self, yadis_url, service_element): """Generate all endpoint objects for all of the subfilters of this filter and return their concatenation.""" endpoints = [] for subfilter in self.subfilters: endpoints.extend( subfilter.getServiceEndpoints(yadis_url, service_element)) return endpoints
python
def getServiceEndpoints(self, yadis_url, service_element): """Generate all endpoint objects for all of the subfilters of this filter and return their concatenation.""" endpoints = [] for subfilter in self.subfilters: endpoints.extend( subfilter.getServiceEndpoints(yadis_url, service_element)) return endpoints
[ "def", "getServiceEndpoints", "(", "self", ",", "yadis_url", ",", "service_element", ")", ":", "endpoints", "=", "[", "]", "for", "subfilter", "in", "self", ".", "subfilters", ":", "endpoints", ".", "extend", "(", "subfilter", ".", "getServiceEndpoints", "(", "yadis_url", ",", "service_element", ")", ")", "return", "endpoints" ]
Generate all endpoint objects for all of the subfilters of this filter and return their concatenation.
[ "Generate", "all", "endpoint", "objects", "for", "all", "of", "the", "subfilters", "of", "this", "filter", "and", "return", "their", "concatenation", "." ]
f7e13536f0d1828d3cef5ae7a7b55cabadff37fc
https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/yadis/filters.py#L133-L140
16,652
openid/python-openid
openid/cryptutil.py
randomString
def randomString(length, chrs=None): """Produce a string of length random bytes, chosen from chrs.""" if chrs is None: return getBytes(length) else: n = len(chrs) return ''.join([chrs[randrange(n)] for _ in xrange(length)])
python
def randomString(length, chrs=None): """Produce a string of length random bytes, chosen from chrs.""" if chrs is None: return getBytes(length) else: n = len(chrs) return ''.join([chrs[randrange(n)] for _ in xrange(length)])
[ "def", "randomString", "(", "length", ",", "chrs", "=", "None", ")", ":", "if", "chrs", "is", "None", ":", "return", "getBytes", "(", "length", ")", "else", ":", "n", "=", "len", "(", "chrs", ")", "return", "''", ".", "join", "(", "[", "chrs", "[", "randrange", "(", "n", ")", "]", "for", "_", "in", "xrange", "(", "length", ")", "]", ")" ]
Produce a string of length random bytes, chosen from chrs.
[ "Produce", "a", "string", "of", "length", "random", "bytes", "chosen", "from", "chrs", "." ]
f7e13536f0d1828d3cef5ae7a7b55cabadff37fc
https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/cryptutil.py#L214-L220
16,653
ethereum/eth-hash
eth_hash/main.py
Keccak256._hasher_first_run
def _hasher_first_run(self, preimage): ''' Invoke the backend on-demand, and check an expected hash result, then replace this first run with the new hasher method. This is a bit of a hacky way to minimize overhead on hash calls after this first one. ''' new_hasher = self._backend.keccak256 assert new_hasher(b'') == b"\xc5\xd2F\x01\x86\xf7#<\x92~}\xb2\xdc\xc7\x03\xc0\xe5\x00\xb6S\xca\x82';\x7b\xfa\xd8\x04]\x85\xa4p" # noqa: E501 self.hasher = new_hasher return new_hasher(preimage)
python
def _hasher_first_run(self, preimage): ''' Invoke the backend on-demand, and check an expected hash result, then replace this first run with the new hasher method. This is a bit of a hacky way to minimize overhead on hash calls after this first one. ''' new_hasher = self._backend.keccak256 assert new_hasher(b'') == b"\xc5\xd2F\x01\x86\xf7#<\x92~}\xb2\xdc\xc7\x03\xc0\xe5\x00\xb6S\xca\x82';\x7b\xfa\xd8\x04]\x85\xa4p" # noqa: E501 self.hasher = new_hasher return new_hasher(preimage)
[ "def", "_hasher_first_run", "(", "self", ",", "preimage", ")", ":", "new_hasher", "=", "self", ".", "_backend", ".", "keccak256", "assert", "new_hasher", "(", "b''", ")", "==", "b\"\\xc5\\xd2F\\x01\\x86\\xf7#<\\x92~}\\xb2\\xdc\\xc7\\x03\\xc0\\xe5\\x00\\xb6S\\xca\\x82';\\x7b\\xfa\\xd8\\x04]\\x85\\xa4p\"", "# noqa: E501", "self", ".", "hasher", "=", "new_hasher", "return", "new_hasher", "(", "preimage", ")" ]
Invoke the backend on-demand, and check an expected hash result, then replace this first run with the new hasher method. This is a bit of a hacky way to minimize overhead on hash calls after this first one.
[ "Invoke", "the", "backend", "on", "-", "demand", "and", "check", "an", "expected", "hash", "result", "then", "replace", "this", "first", "run", "with", "the", "new", "hasher", "method", ".", "This", "is", "a", "bit", "of", "a", "hacky", "way", "to", "minimize", "overhead", "on", "hash", "calls", "after", "this", "first", "one", "." ]
d05c8ac0710e2dc16aae2c8a1e406ee7cbe78871
https://github.com/ethereum/eth-hash/blob/d05c8ac0710e2dc16aae2c8a1e406ee7cbe78871/eth_hash/main.py#L16-L25
16,654
lukasgeiter/mkdocs-awesome-pages-plugin
mkdocs_awesome_pages_plugin/utils.py
dirname
def dirname(path: Optional[str]) -> Optional[str]: """ Returns the directory component of a pathname and None if the argument is None """ if path is not None: return os.path.dirname(path)
python
def dirname(path: Optional[str]) -> Optional[str]: """ Returns the directory component of a pathname and None if the argument is None """ if path is not None: return os.path.dirname(path)
[ "def", "dirname", "(", "path", ":", "Optional", "[", "str", "]", ")", "->", "Optional", "[", "str", "]", ":", "if", "path", "is", "not", "None", ":", "return", "os", ".", "path", ".", "dirname", "(", "path", ")" ]
Returns the directory component of a pathname and None if the argument is None
[ "Returns", "the", "directory", "component", "of", "a", "pathname", "and", "None", "if", "the", "argument", "is", "None" ]
f5693418b71a0849c5fee3b3307e117983c4e2d8
https://github.com/lukasgeiter/mkdocs-awesome-pages-plugin/blob/f5693418b71a0849c5fee3b3307e117983c4e2d8/mkdocs_awesome_pages_plugin/utils.py#L19-L22
16,655
lukasgeiter/mkdocs-awesome-pages-plugin
mkdocs_awesome_pages_plugin/utils.py
basename
def basename(path: Optional[str]) -> Optional[str]: """ Returns the final component of a pathname and None if the argument is None """ if path is not None: return os.path.basename(path)
python
def basename(path: Optional[str]) -> Optional[str]: """ Returns the final component of a pathname and None if the argument is None """ if path is not None: return os.path.basename(path)
[ "def", "basename", "(", "path", ":", "Optional", "[", "str", "]", ")", "->", "Optional", "[", "str", "]", ":", "if", "path", "is", "not", "None", ":", "return", "os", ".", "path", ".", "basename", "(", "path", ")" ]
Returns the final component of a pathname and None if the argument is None
[ "Returns", "the", "final", "component", "of", "a", "pathname", "and", "None", "if", "the", "argument", "is", "None" ]
f5693418b71a0849c5fee3b3307e117983c4e2d8
https://github.com/lukasgeiter/mkdocs-awesome-pages-plugin/blob/f5693418b71a0849c5fee3b3307e117983c4e2d8/mkdocs_awesome_pages_plugin/utils.py#L25-L28
16,656
lukasgeiter/mkdocs-awesome-pages-plugin
mkdocs_awesome_pages_plugin/utils.py
normpath
def normpath(path: Optional[str]) -> Optional[str]: """ Normalizes the path, returns None if the argument is None """ if path is not None: return os.path.normpath(path)
python
def normpath(path: Optional[str]) -> Optional[str]: """ Normalizes the path, returns None if the argument is None """ if path is not None: return os.path.normpath(path)
[ "def", "normpath", "(", "path", ":", "Optional", "[", "str", "]", ")", "->", "Optional", "[", "str", "]", ":", "if", "path", "is", "not", "None", ":", "return", "os", ".", "path", ".", "normpath", "(", "path", ")" ]
Normalizes the path, returns None if the argument is None
[ "Normalizes", "the", "path", "returns", "None", "if", "the", "argument", "is", "None" ]
f5693418b71a0849c5fee3b3307e117983c4e2d8
https://github.com/lukasgeiter/mkdocs-awesome-pages-plugin/blob/f5693418b71a0849c5fee3b3307e117983c4e2d8/mkdocs_awesome_pages_plugin/utils.py#L31-L34
16,657
lukasgeiter/mkdocs-awesome-pages-plugin
mkdocs_awesome_pages_plugin/utils.py
join_paths
def join_paths(path1: Optional[str], path2: Optional[str]) -> Optional[str]: """ Joins two paths if neither of them is None """ if path1 is not None and path2 is not None: return os.path.join(path1, path2)
python
def join_paths(path1: Optional[str], path2: Optional[str]) -> Optional[str]: """ Joins two paths if neither of them is None """ if path1 is not None and path2 is not None: return os.path.join(path1, path2)
[ "def", "join_paths", "(", "path1", ":", "Optional", "[", "str", "]", ",", "path2", ":", "Optional", "[", "str", "]", ")", "->", "Optional", "[", "str", "]", ":", "if", "path1", "is", "not", "None", "and", "path2", "is", "not", "None", ":", "return", "os", ".", "path", ".", "join", "(", "path1", ",", "path2", ")" ]
Joins two paths if neither of them is None
[ "Joins", "two", "paths", "if", "neither", "of", "them", "is", "None" ]
f5693418b71a0849c5fee3b3307e117983c4e2d8
https://github.com/lukasgeiter/mkdocs-awesome-pages-plugin/blob/f5693418b71a0849c5fee3b3307e117983c4e2d8/mkdocs_awesome_pages_plugin/utils.py#L37-L40
16,658
msiemens/PyGitUp
PyGitUp/git_wrapper.py
GitWrapper.stasher
def stasher(self): """ A stashing contextmanager. """ # nonlocal for python2 stashed = [False] clean = [False] def stash(): if clean[0] or not self.repo.is_dirty(submodules=False): clean[0] = True return if stashed[0]: return if self.change_count > 1: message = 'stashing {0} changes' else: message = 'stashing {0} change' print(colored( message.format(self.change_count), 'magenta' )) try: self._run('stash') except GitError as e: raise StashError(stderr=e.stderr, stdout=e.stdout) stashed[0] = True yield stash if stashed[0]: print(colored('unstashing', 'magenta')) try: self._run('stash', 'pop') except GitError as e: raise UnstashError(stderr=e.stderr, stdout=e.stdout)
python
def stasher(self): """ A stashing contextmanager. """ # nonlocal for python2 stashed = [False] clean = [False] def stash(): if clean[0] or not self.repo.is_dirty(submodules=False): clean[0] = True return if stashed[0]: return if self.change_count > 1: message = 'stashing {0} changes' else: message = 'stashing {0} change' print(colored( message.format(self.change_count), 'magenta' )) try: self._run('stash') except GitError as e: raise StashError(stderr=e.stderr, stdout=e.stdout) stashed[0] = True yield stash if stashed[0]: print(colored('unstashing', 'magenta')) try: self._run('stash', 'pop') except GitError as e: raise UnstashError(stderr=e.stderr, stdout=e.stdout)
[ "def", "stasher", "(", "self", ")", ":", "# nonlocal for python2\r", "stashed", "=", "[", "False", "]", "clean", "=", "[", "False", "]", "def", "stash", "(", ")", ":", "if", "clean", "[", "0", "]", "or", "not", "self", ".", "repo", ".", "is_dirty", "(", "submodules", "=", "False", ")", ":", "clean", "[", "0", "]", "=", "True", "return", "if", "stashed", "[", "0", "]", ":", "return", "if", "self", ".", "change_count", ">", "1", ":", "message", "=", "'stashing {0} changes'", "else", ":", "message", "=", "'stashing {0} change'", "print", "(", "colored", "(", "message", ".", "format", "(", "self", ".", "change_count", ")", ",", "'magenta'", ")", ")", "try", ":", "self", ".", "_run", "(", "'stash'", ")", "except", "GitError", "as", "e", ":", "raise", "StashError", "(", "stderr", "=", "e", ".", "stderr", ",", "stdout", "=", "e", ".", "stdout", ")", "stashed", "[", "0", "]", "=", "True", "yield", "stash", "if", "stashed", "[", "0", "]", ":", "print", "(", "colored", "(", "'unstashing'", ",", "'magenta'", ")", ")", "try", ":", "self", ".", "_run", "(", "'stash'", ",", "'pop'", ")", "except", "GitError", "as", "e", ":", "raise", "UnstashError", "(", "stderr", "=", "e", ".", "stderr", ",", "stdout", "=", "e", ".", "stdout", ")" ]
A stashing contextmanager.
[ "A", "stashing", "contextmanager", "." ]
b1f78831cb6b8d29d3a7d59f7a2b54fdd0720e9c
https://github.com/msiemens/PyGitUp/blob/b1f78831cb6b8d29d3a7d59f7a2b54fdd0720e9c/PyGitUp/git_wrapper.py#L117-L154
16,659
msiemens/PyGitUp
PyGitUp/git_wrapper.py
GitWrapper.checkout
def checkout(self, branch_name): """ Checkout a branch by name. """ try: find( self.repo.branches, lambda b: b.name == branch_name ).checkout() except OrigCheckoutError as e: raise CheckoutError(branch_name, details=e)
python
def checkout(self, branch_name): """ Checkout a branch by name. """ try: find( self.repo.branches, lambda b: b.name == branch_name ).checkout() except OrigCheckoutError as e: raise CheckoutError(branch_name, details=e)
[ "def", "checkout", "(", "self", ",", "branch_name", ")", ":", "try", ":", "find", "(", "self", ".", "repo", ".", "branches", ",", "lambda", "b", ":", "b", ".", "name", "==", "branch_name", ")", ".", "checkout", "(", ")", "except", "OrigCheckoutError", "as", "e", ":", "raise", "CheckoutError", "(", "branch_name", ",", "details", "=", "e", ")" ]
Checkout a branch by name.
[ "Checkout", "a", "branch", "by", "name", "." ]
b1f78831cb6b8d29d3a7d59f7a2b54fdd0720e9c
https://github.com/msiemens/PyGitUp/blob/b1f78831cb6b8d29d3a7d59f7a2b54fdd0720e9c/PyGitUp/git_wrapper.py#L156-L163
16,660
msiemens/PyGitUp
PyGitUp/git_wrapper.py
GitWrapper.rebase
def rebase(self, target_branch): """ Rebase to target branch. """ current_branch = self.repo.active_branch arguments = ( ([self.config('git-up.rebase.arguments')] or []) + [target_branch.name] ) try: self._run('rebase', *arguments) except GitError as e: raise RebaseError(current_branch.name, target_branch.name, **e.__dict__)
python
def rebase(self, target_branch): """ Rebase to target branch. """ current_branch = self.repo.active_branch arguments = ( ([self.config('git-up.rebase.arguments')] or []) + [target_branch.name] ) try: self._run('rebase', *arguments) except GitError as e: raise RebaseError(current_branch.name, target_branch.name, **e.__dict__)
[ "def", "rebase", "(", "self", ",", "target_branch", ")", ":", "current_branch", "=", "self", ".", "repo", ".", "active_branch", "arguments", "=", "(", "(", "[", "self", ".", "config", "(", "'git-up.rebase.arguments'", ")", "]", "or", "[", "]", ")", "+", "[", "target_branch", ".", "name", "]", ")", "try", ":", "self", ".", "_run", "(", "'rebase'", ",", "*", "arguments", ")", "except", "GitError", "as", "e", ":", "raise", "RebaseError", "(", "current_branch", ".", "name", ",", "target_branch", ".", "name", ",", "*", "*", "e", ".", "__dict__", ")" ]
Rebase to target branch.
[ "Rebase", "to", "target", "branch", "." ]
b1f78831cb6b8d29d3a7d59f7a2b54fdd0720e9c
https://github.com/msiemens/PyGitUp/blob/b1f78831cb6b8d29d3a7d59f7a2b54fdd0720e9c/PyGitUp/git_wrapper.py#L165-L177
16,661
msiemens/PyGitUp
PyGitUp/git_wrapper.py
GitWrapper.push
def push(self, *args, **kwargs): ''' Push commits to remote ''' stdout = six.b('') # Execute command cmd = self.git.push(as_process=True, *args, **kwargs) # Capture output while True: output = cmd.stdout.read(1) sys.stdout.write(output.decode('utf-8')) sys.stdout.flush() stdout += output # Check for EOF if output == six.b(""): break # Wait for the process to quit try: cmd.wait() except GitCommandError as error: # Add more meta-information to errors message = "'{0}' returned exit status {1}".format( ' '.join(str(c) for c in error.command), error.status ) raise GitError(message, stderr=error.stderr, stdout=stdout) return stdout.strip()
python
def push(self, *args, **kwargs): ''' Push commits to remote ''' stdout = six.b('') # Execute command cmd = self.git.push(as_process=True, *args, **kwargs) # Capture output while True: output = cmd.stdout.read(1) sys.stdout.write(output.decode('utf-8')) sys.stdout.flush() stdout += output # Check for EOF if output == six.b(""): break # Wait for the process to quit try: cmd.wait() except GitCommandError as error: # Add more meta-information to errors message = "'{0}' returned exit status {1}".format( ' '.join(str(c) for c in error.command), error.status ) raise GitError(message, stderr=error.stderr, stdout=stdout) return stdout.strip()
[ "def", "push", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "stdout", "=", "six", ".", "b", "(", "''", ")", "# Execute command\r", "cmd", "=", "self", ".", "git", ".", "push", "(", "as_process", "=", "True", ",", "*", "args", ",", "*", "*", "kwargs", ")", "# Capture output\r", "while", "True", ":", "output", "=", "cmd", ".", "stdout", ".", "read", "(", "1", ")", "sys", ".", "stdout", ".", "write", "(", "output", ".", "decode", "(", "'utf-8'", ")", ")", "sys", ".", "stdout", ".", "flush", "(", ")", "stdout", "+=", "output", "# Check for EOF\r", "if", "output", "==", "six", ".", "b", "(", "\"\"", ")", ":", "break", "# Wait for the process to quit\r", "try", ":", "cmd", ".", "wait", "(", ")", "except", "GitCommandError", "as", "error", ":", "# Add more meta-information to errors\r", "message", "=", "\"'{0}' returned exit status {1}\"", ".", "format", "(", "' '", ".", "join", "(", "str", "(", "c", ")", "for", "c", "in", "error", ".", "command", ")", ",", "error", ".", "status", ")", "raise", "GitError", "(", "message", ",", "stderr", "=", "error", ".", "stderr", ",", "stdout", "=", "stdout", ")", "return", "stdout", ".", "strip", "(", ")" ]
Push commits to remote
[ "Push", "commits", "to", "remote" ]
b1f78831cb6b8d29d3a7d59f7a2b54fdd0720e9c
https://github.com/msiemens/PyGitUp/blob/b1f78831cb6b8d29d3a7d59f7a2b54fdd0720e9c/PyGitUp/git_wrapper.py#L220-L252
16,662
msiemens/PyGitUp
PyGitUp/git_wrapper.py
GitWrapper.change_count
def change_count(self): """ The number of changes in the working directory. """ status = self.git.status(porcelain=True, untracked_files='no').strip() if not status: return 0 else: return len(status.split('\n'))
python
def change_count(self): """ The number of changes in the working directory. """ status = self.git.status(porcelain=True, untracked_files='no').strip() if not status: return 0 else: return len(status.split('\n'))
[ "def", "change_count", "(", "self", ")", ":", "status", "=", "self", ".", "git", ".", "status", "(", "porcelain", "=", "True", ",", "untracked_files", "=", "'no'", ")", ".", "strip", "(", ")", "if", "not", "status", ":", "return", "0", "else", ":", "return", "len", "(", "status", ".", "split", "(", "'\\n'", ")", ")" ]
The number of changes in the working directory.
[ "The", "number", "of", "changes", "in", "the", "working", "directory", "." ]
b1f78831cb6b8d29d3a7d59f7a2b54fdd0720e9c
https://github.com/msiemens/PyGitUp/blob/b1f78831cb6b8d29d3a7d59f7a2b54fdd0720e9c/PyGitUp/git_wrapper.py#L262-L268
16,663
msiemens/PyGitUp
PyGitUp/utils.py
uniq
def uniq(seq): """ Return a copy of seq without duplicates. """ seen = set() return [x for x in seq if str(x) not in seen and not seen.add(str(x))]
python
def uniq(seq): """ Return a copy of seq without duplicates. """ seen = set() return [x for x in seq if str(x) not in seen and not seen.add(str(x))]
[ "def", "uniq", "(", "seq", ")", ":", "seen", "=", "set", "(", ")", "return", "[", "x", "for", "x", "in", "seq", "if", "str", "(", "x", ")", "not", "in", "seen", "and", "not", "seen", ".", "add", "(", "str", "(", "x", ")", ")", "]" ]
Return a copy of seq without duplicates.
[ "Return", "a", "copy", "of", "seq", "without", "duplicates", "." ]
b1f78831cb6b8d29d3a7d59f7a2b54fdd0720e9c
https://github.com/msiemens/PyGitUp/blob/b1f78831cb6b8d29d3a7d59f7a2b54fdd0720e9c/PyGitUp/utils.py#L24-L27
16,664
msiemens/PyGitUp
release.py
current_version
def current_version(): """ Get the current version number from setup.py """ # Monkeypatch setuptools.setup so we get the verison number import setuptools version = [None] def monkey_setup(**settings): version[0] = settings['version'] old_setup = setuptools.setup setuptools.setup = monkey_setup import setup # setup.py reload(setup) setuptools.setup = old_setup return version[0]
python
def current_version(): """ Get the current version number from setup.py """ # Monkeypatch setuptools.setup so we get the verison number import setuptools version = [None] def monkey_setup(**settings): version[0] = settings['version'] old_setup = setuptools.setup setuptools.setup = monkey_setup import setup # setup.py reload(setup) setuptools.setup = old_setup return version[0]
[ "def", "current_version", "(", ")", ":", "# Monkeypatch setuptools.setup so we get the verison number", "import", "setuptools", "version", "=", "[", "None", "]", "def", "monkey_setup", "(", "*", "*", "settings", ")", ":", "version", "[", "0", "]", "=", "settings", "[", "'version'", "]", "old_setup", "=", "setuptools", ".", "setup", "setuptools", ".", "setup", "=", "monkey_setup", "import", "setup", "# setup.py", "reload", "(", "setup", ")", "setuptools", ".", "setup", "=", "old_setup", "return", "version", "[", "0", "]" ]
Get the current version number from setup.py
[ "Get", "the", "current", "version", "number", "from", "setup", ".", "py" ]
b1f78831cb6b8d29d3a7d59f7a2b54fdd0720e9c
https://github.com/msiemens/PyGitUp/blob/b1f78831cb6b8d29d3a7d59f7a2b54fdd0720e9c/release.py#L22-L41
16,665
msiemens/PyGitUp
PyGitUp/gitup.py
run
def run(version, quiet, no_fetch, push, **kwargs): # pragma: no cover """ A nicer `git pull`. """ if version: if NO_DISTRIBUTE: print(colored('Please install \'git-up\' via pip in order to ' 'get version information.', 'yellow')) else: GitUp(sparse=True).version_info() return if quiet: sys.stdout = StringIO() try: gitup = GitUp() if push is not None: gitup.settings['push.auto'] = push # if arguments['--no-fetch'] or arguments['--no-f']: if no_fetch: gitup.should_fetch = False except GitError: sys.exit(1) # Error in constructor else: gitup.run()
python
def run(version, quiet, no_fetch, push, **kwargs): # pragma: no cover """ A nicer `git pull`. """ if version: if NO_DISTRIBUTE: print(colored('Please install \'git-up\' via pip in order to ' 'get version information.', 'yellow')) else: GitUp(sparse=True).version_info() return if quiet: sys.stdout = StringIO() try: gitup = GitUp() if push is not None: gitup.settings['push.auto'] = push # if arguments['--no-fetch'] or arguments['--no-f']: if no_fetch: gitup.should_fetch = False except GitError: sys.exit(1) # Error in constructor else: gitup.run()
[ "def", "run", "(", "version", ",", "quiet", ",", "no_fetch", ",", "push", ",", "*", "*", "kwargs", ")", ":", "# pragma: no cover\r", "if", "version", ":", "if", "NO_DISTRIBUTE", ":", "print", "(", "colored", "(", "'Please install \\'git-up\\' via pip in order to '", "'get version information.'", ",", "'yellow'", ")", ")", "else", ":", "GitUp", "(", "sparse", "=", "True", ")", ".", "version_info", "(", ")", "return", "if", "quiet", ":", "sys", ".", "stdout", "=", "StringIO", "(", ")", "try", ":", "gitup", "=", "GitUp", "(", ")", "if", "push", "is", "not", "None", ":", "gitup", ".", "settings", "[", "'push.auto'", "]", "=", "push", "# if arguments['--no-fetch'] or arguments['--no-f']:\r", "if", "no_fetch", ":", "gitup", ".", "should_fetch", "=", "False", "except", "GitError", ":", "sys", ".", "exit", "(", "1", ")", "# Error in constructor\r", "else", ":", "gitup", ".", "run", "(", ")" ]
A nicer `git pull`.
[ "A", "nicer", "git", "pull", "." ]
b1f78831cb6b8d29d3a7d59f7a2b54fdd0720e9c
https://github.com/msiemens/PyGitUp/blob/b1f78831cb6b8d29d3a7d59f7a2b54fdd0720e9c/PyGitUp/gitup.py#L628-L656
16,666
msiemens/PyGitUp
PyGitUp/gitup.py
GitUp.run
def run(self): """ Run all the git-up stuff. """ try: if self.should_fetch: self.fetch() self.rebase_all_branches() if self.with_bundler(): self.check_bundler() if self.settings['push.auto']: self.push() except GitError as error: self.print_error(error) # Used for test cases if self.testing: raise else: # pragma: no cover sys.exit(1)
python
def run(self): """ Run all the git-up stuff. """ try: if self.should_fetch: self.fetch() self.rebase_all_branches() if self.with_bundler(): self.check_bundler() if self.settings['push.auto']: self.push() except GitError as error: self.print_error(error) # Used for test cases if self.testing: raise else: # pragma: no cover sys.exit(1)
[ "def", "run", "(", "self", ")", ":", "try", ":", "if", "self", ".", "should_fetch", ":", "self", ".", "fetch", "(", ")", "self", ".", "rebase_all_branches", "(", ")", "if", "self", ".", "with_bundler", "(", ")", ":", "self", ".", "check_bundler", "(", ")", "if", "self", ".", "settings", "[", "'push.auto'", "]", ":", "self", ".", "push", "(", ")", "except", "GitError", "as", "error", ":", "self", ".", "print_error", "(", "error", ")", "# Used for test cases\r", "if", "self", ".", "testing", ":", "raise", "else", ":", "# pragma: no cover\r", "sys", ".", "exit", "(", "1", ")" ]
Run all the git-up stuff.
[ "Run", "all", "the", "git", "-", "up", "stuff", "." ]
b1f78831cb6b8d29d3a7d59f7a2b54fdd0720e9c
https://github.com/msiemens/PyGitUp/blob/b1f78831cb6b8d29d3a7d59f7a2b54fdd0720e9c/PyGitUp/gitup.py#L193-L214
16,667
msiemens/PyGitUp
PyGitUp/gitup.py
GitUp.fetch
def fetch(self): """ Fetch the recent refs from the remotes. Unless git-up.fetch.all is set to true, all remotes with locally existent branches will be fetched. """ fetch_kwargs = {'multiple': True} fetch_args = [] if self.is_prune(): fetch_kwargs['prune'] = True if self.settings['fetch.all']: fetch_kwargs['all'] = True else: if '.' in self.remotes: self.remotes.remove('.') if not self.remotes: # Only local target branches, # `git fetch --multiple` will fail return fetch_args.append(self.remotes) try: self.git.fetch(*fetch_args, **fetch_kwargs) except GitError as error: error.message = "`git fetch` failed" raise error
python
def fetch(self): """ Fetch the recent refs from the remotes. Unless git-up.fetch.all is set to true, all remotes with locally existent branches will be fetched. """ fetch_kwargs = {'multiple': True} fetch_args = [] if self.is_prune(): fetch_kwargs['prune'] = True if self.settings['fetch.all']: fetch_kwargs['all'] = True else: if '.' in self.remotes: self.remotes.remove('.') if not self.remotes: # Only local target branches, # `git fetch --multiple` will fail return fetch_args.append(self.remotes) try: self.git.fetch(*fetch_args, **fetch_kwargs) except GitError as error: error.message = "`git fetch` failed" raise error
[ "def", "fetch", "(", "self", ")", ":", "fetch_kwargs", "=", "{", "'multiple'", ":", "True", "}", "fetch_args", "=", "[", "]", "if", "self", ".", "is_prune", "(", ")", ":", "fetch_kwargs", "[", "'prune'", "]", "=", "True", "if", "self", ".", "settings", "[", "'fetch.all'", "]", ":", "fetch_kwargs", "[", "'all'", "]", "=", "True", "else", ":", "if", "'.'", "in", "self", ".", "remotes", ":", "self", ".", "remotes", ".", "remove", "(", "'.'", ")", "if", "not", "self", ".", "remotes", ":", "# Only local target branches,\r", "# `git fetch --multiple` will fail\r", "return", "fetch_args", ".", "append", "(", "self", ".", "remotes", ")", "try", ":", "self", ".", "git", ".", "fetch", "(", "*", "fetch_args", ",", "*", "*", "fetch_kwargs", ")", "except", "GitError", "as", "error", ":", "error", ".", "message", "=", "\"`git fetch` failed\"", "raise", "error" ]
Fetch the recent refs from the remotes. Unless git-up.fetch.all is set to true, all remotes with locally existent branches will be fetched.
[ "Fetch", "the", "recent", "refs", "from", "the", "remotes", ".", "Unless", "git", "-", "up", ".", "fetch", ".", "all", "is", "set", "to", "true", "all", "remotes", "with", "locally", "existent", "branches", "will", "be", "fetched", "." ]
b1f78831cb6b8d29d3a7d59f7a2b54fdd0720e9c
https://github.com/msiemens/PyGitUp/blob/b1f78831cb6b8d29d3a7d59f7a2b54fdd0720e9c/PyGitUp/gitup.py#L311-L341
16,668
msiemens/PyGitUp
PyGitUp/gitup.py
GitUp.log
def log(self, branch, remote): """ Call a log-command, if set by git-up.fetch.all. """ log_hook = self.settings['rebase.log-hook'] if log_hook: if ON_WINDOWS: # pragma: no cover # Running a string in CMD from Python is not that easy on # Windows. Running 'cmd /C log_hook' produces problems when # using multiple statements or things like 'echo'. Therefore, # we write the string to a bat file and execute it. # In addition, we replace occurences of $1 with %1 and so forth # in case the user is used to Bash or sh. # If there are occurences of %something, we'll replace it with # %%something. This is the case when running something like # 'git log --pretty=format:"%Cred%h..."'. # Also, we replace a semicolon with a newline, because if you # start with 'echo' on Windows, it will simply echo the # semicolon and the commands behind instead of echoing and then # running other commands # Prepare log_hook log_hook = re.sub(r'\$(\d+)', r'%\1', log_hook) log_hook = re.sub(r'%(?!\d)', '%%', log_hook) log_hook = re.sub(r'; ?', r'\n', log_hook) # Write log_hook to an temporary file and get it's path with NamedTemporaryFile( prefix='PyGitUp.', suffix='.bat', delete=False ) as bat_file: # Don't echo all commands bat_file.file.write(b'@echo off\n') # Run log_hook bat_file.file.write(log_hook.encode('utf-8')) # Run bat_file state = subprocess.call( [bat_file.name, branch.name, remote.name] ) # Clean up file os.remove(bat_file.name) else: # pragma: no cover # Run log_hook via 'shell -c' state = subprocess.call( [log_hook, 'git-up', branch.name, remote.name], shell=True ) if self.testing: assert state == 0, 'log_hook returned != 0'
python
def log(self, branch, remote): """ Call a log-command, if set by git-up.fetch.all. """ log_hook = self.settings['rebase.log-hook'] if log_hook: if ON_WINDOWS: # pragma: no cover # Running a string in CMD from Python is not that easy on # Windows. Running 'cmd /C log_hook' produces problems when # using multiple statements or things like 'echo'. Therefore, # we write the string to a bat file and execute it. # In addition, we replace occurences of $1 with %1 and so forth # in case the user is used to Bash or sh. # If there are occurences of %something, we'll replace it with # %%something. This is the case when running something like # 'git log --pretty=format:"%Cred%h..."'. # Also, we replace a semicolon with a newline, because if you # start with 'echo' on Windows, it will simply echo the # semicolon and the commands behind instead of echoing and then # running other commands # Prepare log_hook log_hook = re.sub(r'\$(\d+)', r'%\1', log_hook) log_hook = re.sub(r'%(?!\d)', '%%', log_hook) log_hook = re.sub(r'; ?', r'\n', log_hook) # Write log_hook to an temporary file and get it's path with NamedTemporaryFile( prefix='PyGitUp.', suffix='.bat', delete=False ) as bat_file: # Don't echo all commands bat_file.file.write(b'@echo off\n') # Run log_hook bat_file.file.write(log_hook.encode('utf-8')) # Run bat_file state = subprocess.call( [bat_file.name, branch.name, remote.name] ) # Clean up file os.remove(bat_file.name) else: # pragma: no cover # Run log_hook via 'shell -c' state = subprocess.call( [log_hook, 'git-up', branch.name, remote.name], shell=True ) if self.testing: assert state == 0, 'log_hook returned != 0'
[ "def", "log", "(", "self", ",", "branch", ",", "remote", ")", ":", "log_hook", "=", "self", ".", "settings", "[", "'rebase.log-hook'", "]", "if", "log_hook", ":", "if", "ON_WINDOWS", ":", "# pragma: no cover\r", "# Running a string in CMD from Python is not that easy on\r", "# Windows. Running 'cmd /C log_hook' produces problems when\r", "# using multiple statements or things like 'echo'. Therefore,\r", "# we write the string to a bat file and execute it.\r", "# In addition, we replace occurences of $1 with %1 and so forth\r", "# in case the user is used to Bash or sh.\r", "# If there are occurences of %something, we'll replace it with\r", "# %%something. This is the case when running something like\r", "# 'git log --pretty=format:\"%Cred%h...\"'.\r", "# Also, we replace a semicolon with a newline, because if you\r", "# start with 'echo' on Windows, it will simply echo the\r", "# semicolon and the commands behind instead of echoing and then\r", "# running other commands\r", "# Prepare log_hook\r", "log_hook", "=", "re", ".", "sub", "(", "r'\\$(\\d+)'", ",", "r'%\\1'", ",", "log_hook", ")", "log_hook", "=", "re", ".", "sub", "(", "r'%(?!\\d)'", ",", "'%%'", ",", "log_hook", ")", "log_hook", "=", "re", ".", "sub", "(", "r'; ?'", ",", "r'\\n'", ",", "log_hook", ")", "# Write log_hook to an temporary file and get it's path\r", "with", "NamedTemporaryFile", "(", "prefix", "=", "'PyGitUp.'", ",", "suffix", "=", "'.bat'", ",", "delete", "=", "False", ")", "as", "bat_file", ":", "# Don't echo all commands\r", "bat_file", ".", "file", ".", "write", "(", "b'@echo off\\n'", ")", "# Run log_hook\r", "bat_file", ".", "file", ".", "write", "(", "log_hook", ".", "encode", "(", "'utf-8'", ")", ")", "# Run bat_file\r", "state", "=", "subprocess", ".", "call", "(", "[", "bat_file", ".", "name", ",", "branch", ".", "name", ",", "remote", ".", "name", "]", ")", "# Clean up file\r", "os", ".", "remove", "(", "bat_file", ".", "name", ")", "else", ":", "# pragma: no cover\r", "# Run log_hook via 'shell -c'\r", "state", "=", "subprocess", ".", "call", "(", "[", "log_hook", ",", "'git-up'", ",", "branch", ".", "name", ",", "remote", ".", "name", "]", ",", "shell", "=", "True", ")", "if", "self", ".", "testing", ":", "assert", "state", "==", "0", ",", "'log_hook returned != 0'" ]
Call a log-command, if set by git-up.fetch.all.
[ "Call", "a", "log", "-", "command", "if", "set", "by", "git", "-", "up", ".", "fetch", ".", "all", "." ]
b1f78831cb6b8d29d3a7d59f7a2b54fdd0720e9c
https://github.com/msiemens/PyGitUp/blob/b1f78831cb6b8d29d3a7d59f7a2b54fdd0720e9c/PyGitUp/gitup.py#L374-L424
16,669
msiemens/PyGitUp
PyGitUp/gitup.py
GitUp.version_info
def version_info(self): """ Tell, what version we're running at and if it's up to date. """ # Retrive and show local version info package = pkg.get_distribution('git-up') local_version_str = package.version local_version = package.parsed_version print('GitUp version is: ' + colored('v' + local_version_str, 'green')) if not self.settings['updates.check']: return # Check for updates print('Checking for updates...', end='') try: # Get version information from the PyPI JSON API reader = codecs.getreader('utf-8') details = json.load(reader(urlopen(PYPI_URL))) online_version = details['info']['version'] except (HTTPError, URLError, ValueError): recent = True # To not disturb the user with HTTP/parsing errors else: recent = local_version >= pkg.parse_version(online_version) if not recent: # noinspection PyUnboundLocalVariable print( '\rRecent version is: ' + colored('v' + online_version, color='yellow', attrs=['bold']) ) print('Run \'pip install -U git-up\' to get the update.') else: # Clear the update line sys.stdout.write('\r' + ' ' * 80 + '\n')
python
def version_info(self): """ Tell, what version we're running at and if it's up to date. """ # Retrive and show local version info package = pkg.get_distribution('git-up') local_version_str = package.version local_version = package.parsed_version print('GitUp version is: ' + colored('v' + local_version_str, 'green')) if not self.settings['updates.check']: return # Check for updates print('Checking for updates...', end='') try: # Get version information from the PyPI JSON API reader = codecs.getreader('utf-8') details = json.load(reader(urlopen(PYPI_URL))) online_version = details['info']['version'] except (HTTPError, URLError, ValueError): recent = True # To not disturb the user with HTTP/parsing errors else: recent = local_version >= pkg.parse_version(online_version) if not recent: # noinspection PyUnboundLocalVariable print( '\rRecent version is: ' + colored('v' + online_version, color='yellow', attrs=['bold']) ) print('Run \'pip install -U git-up\' to get the update.') else: # Clear the update line sys.stdout.write('\r' + ' ' * 80 + '\n')
[ "def", "version_info", "(", "self", ")", ":", "# Retrive and show local version info\r", "package", "=", "pkg", ".", "get_distribution", "(", "'git-up'", ")", "local_version_str", "=", "package", ".", "version", "local_version", "=", "package", ".", "parsed_version", "print", "(", "'GitUp version is: '", "+", "colored", "(", "'v'", "+", "local_version_str", ",", "'green'", ")", ")", "if", "not", "self", ".", "settings", "[", "'updates.check'", "]", ":", "return", "# Check for updates\r", "print", "(", "'Checking for updates...'", ",", "end", "=", "''", ")", "try", ":", "# Get version information from the PyPI JSON API\r", "reader", "=", "codecs", ".", "getreader", "(", "'utf-8'", ")", "details", "=", "json", ".", "load", "(", "reader", "(", "urlopen", "(", "PYPI_URL", ")", ")", ")", "online_version", "=", "details", "[", "'info'", "]", "[", "'version'", "]", "except", "(", "HTTPError", ",", "URLError", ",", "ValueError", ")", ":", "recent", "=", "True", "# To not disturb the user with HTTP/parsing errors\r", "else", ":", "recent", "=", "local_version", ">=", "pkg", ".", "parse_version", "(", "online_version", ")", "if", "not", "recent", ":", "# noinspection PyUnboundLocalVariable\r", "print", "(", "'\\rRecent version is: '", "+", "colored", "(", "'v'", "+", "online_version", ",", "color", "=", "'yellow'", ",", "attrs", "=", "[", "'bold'", "]", ")", ")", "print", "(", "'Run \\'pip install -U git-up\\' to get the update.'", ")", "else", ":", "# Clear the update line\r", "sys", ".", "stdout", ".", "write", "(", "'\\r'", "+", "' '", "*", "80", "+", "'\\n'", ")" ]
Tell, what version we're running at and if it's up to date.
[ "Tell", "what", "version", "we", "re", "running", "at", "and", "if", "it", "s", "up", "to", "date", "." ]
b1f78831cb6b8d29d3a7d59f7a2b54fdd0720e9c
https://github.com/msiemens/PyGitUp/blob/b1f78831cb6b8d29d3a7d59f7a2b54fdd0720e9c/PyGitUp/gitup.py#L426-L461
16,670
msiemens/PyGitUp
PyGitUp/gitup.py
GitUp.load_config
def load_config(self): """ Load the configuration from git config. """ for key in self.settings: value = self.config(key) # Parse true/false if value == '' or value is None: continue # Not set by user, go on if value.lower() == 'true': value = True elif value.lower() == 'false': value = False elif value: pass # A user-defined string, store the value later self.settings[key] = value
python
def load_config(self): """ Load the configuration from git config. """ for key in self.settings: value = self.config(key) # Parse true/false if value == '' or value is None: continue # Not set by user, go on if value.lower() == 'true': value = True elif value.lower() == 'false': value = False elif value: pass # A user-defined string, store the value later self.settings[key] = value
[ "def", "load_config", "(", "self", ")", ":", "for", "key", "in", "self", ".", "settings", ":", "value", "=", "self", ".", "config", "(", "key", ")", "# Parse true/false\r", "if", "value", "==", "''", "or", "value", "is", "None", ":", "continue", "# Not set by user, go on\r", "if", "value", ".", "lower", "(", ")", "==", "'true'", ":", "value", "=", "True", "elif", "value", ".", "lower", "(", ")", "==", "'false'", ":", "value", "=", "False", "elif", "value", ":", "pass", "# A user-defined string, store the value later\r", "self", ".", "settings", "[", "key", "]", "=", "value" ]
Load the configuration from git config.
[ "Load", "the", "configuration", "from", "git", "config", "." ]
b1f78831cb6b8d29d3a7d59f7a2b54fdd0720e9c
https://github.com/msiemens/PyGitUp/blob/b1f78831cb6b8d29d3a7d59f7a2b54fdd0720e9c/PyGitUp/gitup.py#L467-L483
16,671
msiemens/PyGitUp
PyGitUp/gitup.py
GitUp.check_bundler
def check_bundler(self): """ Run the bundler check. """ def get_config(name): return name if self.config('bundler.' + name) else '' from pkg_resources import Requirement, resource_filename relative_path = os.path.join('PyGitUp', 'check-bundler.rb') bundler_script = resource_filename(Requirement.parse('git-up'), relative_path) assert os.path.exists(bundler_script), 'check-bundler.rb doesn\'t ' \ 'exist!' return_value = subprocess.call( ['ruby', bundler_script, get_config('autoinstall'), get_config('local'), get_config('rbenv')] ) if self.testing: assert return_value == 0, 'Errors while executing check-bundler.rb'
python
def check_bundler(self): """ Run the bundler check. """ def get_config(name): return name if self.config('bundler.' + name) else '' from pkg_resources import Requirement, resource_filename relative_path = os.path.join('PyGitUp', 'check-bundler.rb') bundler_script = resource_filename(Requirement.parse('git-up'), relative_path) assert os.path.exists(bundler_script), 'check-bundler.rb doesn\'t ' \ 'exist!' return_value = subprocess.call( ['ruby', bundler_script, get_config('autoinstall'), get_config('local'), get_config('rbenv')] ) if self.testing: assert return_value == 0, 'Errors while executing check-bundler.rb'
[ "def", "check_bundler", "(", "self", ")", ":", "def", "get_config", "(", "name", ")", ":", "return", "name", "if", "self", ".", "config", "(", "'bundler.'", "+", "name", ")", "else", "''", "from", "pkg_resources", "import", "Requirement", ",", "resource_filename", "relative_path", "=", "os", ".", "path", ".", "join", "(", "'PyGitUp'", ",", "'check-bundler.rb'", ")", "bundler_script", "=", "resource_filename", "(", "Requirement", ".", "parse", "(", "'git-up'", ")", ",", "relative_path", ")", "assert", "os", ".", "path", ".", "exists", "(", "bundler_script", ")", ",", "'check-bundler.rb doesn\\'t '", "'exist!'", "return_value", "=", "subprocess", ".", "call", "(", "[", "'ruby'", ",", "bundler_script", ",", "get_config", "(", "'autoinstall'", ")", ",", "get_config", "(", "'local'", ")", ",", "get_config", "(", "'rbenv'", ")", "]", ")", "if", "self", ".", "testing", ":", "assert", "return_value", "==", "0", ",", "'Errors while executing check-bundler.rb'" ]
Run the bundler check.
[ "Run", "the", "bundler", "check", "." ]
b1f78831cb6b8d29d3a7d59f7a2b54fdd0720e9c
https://github.com/msiemens/PyGitUp/blob/b1f78831cb6b8d29d3a7d59f7a2b54fdd0720e9c/PyGitUp/gitup.py#L555-L576
16,672
mikemaccana/python-docx
docx.py
opendocx
def opendocx(file): '''Open a docx file, return a document XML tree''' mydoc = zipfile.ZipFile(file) xmlcontent = mydoc.read('word/document.xml') document = etree.fromstring(xmlcontent) return document
python
def opendocx(file): '''Open a docx file, return a document XML tree''' mydoc = zipfile.ZipFile(file) xmlcontent = mydoc.read('word/document.xml') document = etree.fromstring(xmlcontent) return document
[ "def", "opendocx", "(", "file", ")", ":", "mydoc", "=", "zipfile", ".", "ZipFile", "(", "file", ")", "xmlcontent", "=", "mydoc", ".", "read", "(", "'word/document.xml'", ")", "document", "=", "etree", ".", "fromstring", "(", "xmlcontent", ")", "return", "document" ]
Open a docx file, return a document XML tree
[ "Open", "a", "docx", "file", "return", "a", "document", "XML", "tree" ]
4c9b46dbebe3d2a9b82dbcd35af36584a36fd9fe
https://github.com/mikemaccana/python-docx/blob/4c9b46dbebe3d2a9b82dbcd35af36584a36fd9fe/docx.py#L81-L86
16,673
mikemaccana/python-docx
docx.py
makeelement
def makeelement(tagname, tagtext=None, nsprefix='w', attributes=None, attrnsprefix=None): '''Create an element & return it''' # Deal with list of nsprefix by making namespacemap namespacemap = None if isinstance(nsprefix, list): namespacemap = {} for prefix in nsprefix: namespacemap[prefix] = nsprefixes[prefix] # FIXME: rest of code below expects a single prefix nsprefix = nsprefix[0] if nsprefix: namespace = '{%s}' % nsprefixes[nsprefix] else: # For when namespace = None namespace = '' newelement = etree.Element(namespace+tagname, nsmap=namespacemap) # Add attributes with namespaces if attributes: # If they haven't bothered setting attribute namespace, use an empty # string (equivalent of no namespace) if not attrnsprefix: # Quick hack: it seems every element that has a 'w' nsprefix for # its tag uses the same prefix for it's attributes if nsprefix == 'w': attributenamespace = namespace else: attributenamespace = '' else: attributenamespace = '{'+nsprefixes[attrnsprefix]+'}' for tagattribute in attributes: newelement.set(attributenamespace+tagattribute, attributes[tagattribute]) if tagtext: newelement.text = tagtext return newelement
python
def makeelement(tagname, tagtext=None, nsprefix='w', attributes=None, attrnsprefix=None): '''Create an element & return it''' # Deal with list of nsprefix by making namespacemap namespacemap = None if isinstance(nsprefix, list): namespacemap = {} for prefix in nsprefix: namespacemap[prefix] = nsprefixes[prefix] # FIXME: rest of code below expects a single prefix nsprefix = nsprefix[0] if nsprefix: namespace = '{%s}' % nsprefixes[nsprefix] else: # For when namespace = None namespace = '' newelement = etree.Element(namespace+tagname, nsmap=namespacemap) # Add attributes with namespaces if attributes: # If they haven't bothered setting attribute namespace, use an empty # string (equivalent of no namespace) if not attrnsprefix: # Quick hack: it seems every element that has a 'w' nsprefix for # its tag uses the same prefix for it's attributes if nsprefix == 'w': attributenamespace = namespace else: attributenamespace = '' else: attributenamespace = '{'+nsprefixes[attrnsprefix]+'}' for tagattribute in attributes: newelement.set(attributenamespace+tagattribute, attributes[tagattribute]) if tagtext: newelement.text = tagtext return newelement
[ "def", "makeelement", "(", "tagname", ",", "tagtext", "=", "None", ",", "nsprefix", "=", "'w'", ",", "attributes", "=", "None", ",", "attrnsprefix", "=", "None", ")", ":", "# Deal with list of nsprefix by making namespacemap", "namespacemap", "=", "None", "if", "isinstance", "(", "nsprefix", ",", "list", ")", ":", "namespacemap", "=", "{", "}", "for", "prefix", "in", "nsprefix", ":", "namespacemap", "[", "prefix", "]", "=", "nsprefixes", "[", "prefix", "]", "# FIXME: rest of code below expects a single prefix", "nsprefix", "=", "nsprefix", "[", "0", "]", "if", "nsprefix", ":", "namespace", "=", "'{%s}'", "%", "nsprefixes", "[", "nsprefix", "]", "else", ":", "# For when namespace = None", "namespace", "=", "''", "newelement", "=", "etree", ".", "Element", "(", "namespace", "+", "tagname", ",", "nsmap", "=", "namespacemap", ")", "# Add attributes with namespaces", "if", "attributes", ":", "# If they haven't bothered setting attribute namespace, use an empty", "# string (equivalent of no namespace)", "if", "not", "attrnsprefix", ":", "# Quick hack: it seems every element that has a 'w' nsprefix for", "# its tag uses the same prefix for it's attributes", "if", "nsprefix", "==", "'w'", ":", "attributenamespace", "=", "namespace", "else", ":", "attributenamespace", "=", "''", "else", ":", "attributenamespace", "=", "'{'", "+", "nsprefixes", "[", "attrnsprefix", "]", "+", "'}'", "for", "tagattribute", "in", "attributes", ":", "newelement", ".", "set", "(", "attributenamespace", "+", "tagattribute", ",", "attributes", "[", "tagattribute", "]", ")", "if", "tagtext", ":", "newelement", ".", "text", "=", "tagtext", "return", "newelement" ]
Create an element & return it
[ "Create", "an", "element", "&", "return", "it" ]
4c9b46dbebe3d2a9b82dbcd35af36584a36fd9fe
https://github.com/mikemaccana/python-docx/blob/4c9b46dbebe3d2a9b82dbcd35af36584a36fd9fe/docx.py#L95-L131
16,674
mikemaccana/python-docx
docx.py
heading
def heading(headingtext, headinglevel, lang='en'): '''Make a new heading, return the heading element''' lmap = {'en': 'Heading', 'it': 'Titolo'} # Make our elements paragraph = makeelement('p') pr = makeelement('pPr') pStyle = makeelement( 'pStyle', attributes={'val': lmap[lang]+str(headinglevel)}) run = makeelement('r') text = makeelement('t', tagtext=headingtext) # Add the text the run, and the run to the paragraph pr.append(pStyle) run.append(text) paragraph.append(pr) paragraph.append(run) # Return the combined paragraph return paragraph
python
def heading(headingtext, headinglevel, lang='en'): '''Make a new heading, return the heading element''' lmap = {'en': 'Heading', 'it': 'Titolo'} # Make our elements paragraph = makeelement('p') pr = makeelement('pPr') pStyle = makeelement( 'pStyle', attributes={'val': lmap[lang]+str(headinglevel)}) run = makeelement('r') text = makeelement('t', tagtext=headingtext) # Add the text the run, and the run to the paragraph pr.append(pStyle) run.append(text) paragraph.append(pr) paragraph.append(run) # Return the combined paragraph return paragraph
[ "def", "heading", "(", "headingtext", ",", "headinglevel", ",", "lang", "=", "'en'", ")", ":", "lmap", "=", "{", "'en'", ":", "'Heading'", ",", "'it'", ":", "'Titolo'", "}", "# Make our elements", "paragraph", "=", "makeelement", "(", "'p'", ")", "pr", "=", "makeelement", "(", "'pPr'", ")", "pStyle", "=", "makeelement", "(", "'pStyle'", ",", "attributes", "=", "{", "'val'", ":", "lmap", "[", "lang", "]", "+", "str", "(", "headinglevel", ")", "}", ")", "run", "=", "makeelement", "(", "'r'", ")", "text", "=", "makeelement", "(", "'t'", ",", "tagtext", "=", "headingtext", ")", "# Add the text the run, and the run to the paragraph", "pr", ".", "append", "(", "pStyle", ")", "run", ".", "append", "(", "text", ")", "paragraph", ".", "append", "(", "pr", ")", "paragraph", ".", "append", "(", "run", ")", "# Return the combined paragraph", "return", "paragraph" ]
Make a new heading, return the heading element
[ "Make", "a", "new", "heading", "return", "the", "heading", "element" ]
4c9b46dbebe3d2a9b82dbcd35af36584a36fd9fe
https://github.com/mikemaccana/python-docx/blob/4c9b46dbebe3d2a9b82dbcd35af36584a36fd9fe/docx.py#L278-L294
16,675
mikemaccana/python-docx
docx.py
clean
def clean(document): """ Perform misc cleaning operations on documents. Returns cleaned document. """ newdocument = document # Clean empty text and r tags for t in ('t', 'r'): rmlist = [] for element in newdocument.iter(): if element.tag == '{%s}%s' % (nsprefixes['w'], t): if not element.text and not len(element): rmlist.append(element) for element in rmlist: element.getparent().remove(element) return newdocument
python
def clean(document): """ Perform misc cleaning operations on documents. Returns cleaned document. """ newdocument = document # Clean empty text and r tags for t in ('t', 'r'): rmlist = [] for element in newdocument.iter(): if element.tag == '{%s}%s' % (nsprefixes['w'], t): if not element.text and not len(element): rmlist.append(element) for element in rmlist: element.getparent().remove(element) return newdocument
[ "def", "clean", "(", "document", ")", ":", "newdocument", "=", "document", "# Clean empty text and r tags", "for", "t", "in", "(", "'t'", ",", "'r'", ")", ":", "rmlist", "=", "[", "]", "for", "element", "in", "newdocument", ".", "iter", "(", ")", ":", "if", "element", ".", "tag", "==", "'{%s}%s'", "%", "(", "nsprefixes", "[", "'w'", "]", ",", "t", ")", ":", "if", "not", "element", ".", "text", "and", "not", "len", "(", "element", ")", ":", "rmlist", ".", "append", "(", "element", ")", "for", "element", "in", "rmlist", ":", "element", ".", "getparent", "(", ")", ".", "remove", "(", "element", ")", "return", "newdocument" ]
Perform misc cleaning operations on documents. Returns cleaned document.
[ "Perform", "misc", "cleaning", "operations", "on", "documents", ".", "Returns", "cleaned", "document", "." ]
4c9b46dbebe3d2a9b82dbcd35af36584a36fd9fe
https://github.com/mikemaccana/python-docx/blob/4c9b46dbebe3d2a9b82dbcd35af36584a36fd9fe/docx.py#L644-L661
16,676
mikemaccana/python-docx
docx.py
findTypeParent
def findTypeParent(element, tag): """ Finds fist parent of element of the given type @param object element: etree element @param string the tag parent to search for @return object element: the found parent or None when not found """ p = element while True: p = p.getparent() if p.tag == tag: return p # Not found return None
python
def findTypeParent(element, tag): """ Finds fist parent of element of the given type @param object element: etree element @param string the tag parent to search for @return object element: the found parent or None when not found """ p = element while True: p = p.getparent() if p.tag == tag: return p # Not found return None
[ "def", "findTypeParent", "(", "element", ",", "tag", ")", ":", "p", "=", "element", "while", "True", ":", "p", "=", "p", ".", "getparent", "(", ")", "if", "p", ".", "tag", "==", "tag", ":", "return", "p", "# Not found", "return", "None" ]
Finds fist parent of element of the given type @param object element: etree element @param string the tag parent to search for @return object element: the found parent or None when not found
[ "Finds", "fist", "parent", "of", "element", "of", "the", "given", "type" ]
4c9b46dbebe3d2a9b82dbcd35af36584a36fd9fe
https://github.com/mikemaccana/python-docx/blob/4c9b46dbebe3d2a9b82dbcd35af36584a36fd9fe/docx.py#L664-L680
16,677
mikemaccana/python-docx
docx.py
AdvSearch
def AdvSearch(document, search, bs=3): '''Return set of all regex matches This is an advanced version of python-docx.search() that takes into account blocks of <bs> elements at a time. What it does: It searches the entire document body for text blocks. Since the text to search could be spawned across multiple text blocks, we need to adopt some sort of algorithm to handle this situation. The smaller matching group of blocks (up to bs) is then adopted. If the matching group has more than one block, blocks other than first are cleared and all the replacement text is put on first block. Examples: original text blocks : [ 'Hel', 'lo,', ' world!' ] search : 'Hello,' output blocks : [ 'Hello,' ] original text blocks : [ 'Hel', 'lo', ' __', 'name', '__!' ] search : '(__[a-z]+__)' output blocks : [ '__name__' ] @param instance document: The original document @param str search: The text to search for (regexp) append, or a list of etree elements @param int bs: See above @return set All occurences of search string ''' # Compile the search regexp searchre = re.compile(search) matches = [] # Will match against searchels. Searchels is a list that contains last # n text elements found in the document. 1 < n < bs searchels = [] for element in document.iter(): if element.tag == '{%s}t' % nsprefixes['w']: # t (text) elements if element.text: # Add this element to searchels searchels.append(element) if len(searchels) > bs: # Is searchels is too long, remove first elements searchels.pop(0) # Search all combinations, of searchels, starting from # smaller up to bigger ones # l = search lenght # s = search start # e = element IDs to merge found = False for l in range(1, len(searchels)+1): if found: break for s in range(len(searchels)): if found: break if s+l <= len(searchels): e = range(s, s+l) txtsearch = '' for k in e: txtsearch += searchels[k].text # Searcs for the text in the whole txtsearch match = searchre.search(txtsearch) if match: matches.append(match.group()) found = True return set(matches)
python
def AdvSearch(document, search, bs=3): '''Return set of all regex matches This is an advanced version of python-docx.search() that takes into account blocks of <bs> elements at a time. What it does: It searches the entire document body for text blocks. Since the text to search could be spawned across multiple text blocks, we need to adopt some sort of algorithm to handle this situation. The smaller matching group of blocks (up to bs) is then adopted. If the matching group has more than one block, blocks other than first are cleared and all the replacement text is put on first block. Examples: original text blocks : [ 'Hel', 'lo,', ' world!' ] search : 'Hello,' output blocks : [ 'Hello,' ] original text blocks : [ 'Hel', 'lo', ' __', 'name', '__!' ] search : '(__[a-z]+__)' output blocks : [ '__name__' ] @param instance document: The original document @param str search: The text to search for (regexp) append, or a list of etree elements @param int bs: See above @return set All occurences of search string ''' # Compile the search regexp searchre = re.compile(search) matches = [] # Will match against searchels. Searchels is a list that contains last # n text elements found in the document. 1 < n < bs searchels = [] for element in document.iter(): if element.tag == '{%s}t' % nsprefixes['w']: # t (text) elements if element.text: # Add this element to searchels searchels.append(element) if len(searchels) > bs: # Is searchels is too long, remove first elements searchels.pop(0) # Search all combinations, of searchels, starting from # smaller up to bigger ones # l = search lenght # s = search start # e = element IDs to merge found = False for l in range(1, len(searchels)+1): if found: break for s in range(len(searchels)): if found: break if s+l <= len(searchels): e = range(s, s+l) txtsearch = '' for k in e: txtsearch += searchels[k].text # Searcs for the text in the whole txtsearch match = searchre.search(txtsearch) if match: matches.append(match.group()) found = True return set(matches)
[ "def", "AdvSearch", "(", "document", ",", "search", ",", "bs", "=", "3", ")", ":", "# Compile the search regexp", "searchre", "=", "re", ".", "compile", "(", "search", ")", "matches", "=", "[", "]", "# Will match against searchels. Searchels is a list that contains last", "# n text elements found in the document. 1 < n < bs", "searchels", "=", "[", "]", "for", "element", "in", "document", ".", "iter", "(", ")", ":", "if", "element", ".", "tag", "==", "'{%s}t'", "%", "nsprefixes", "[", "'w'", "]", ":", "# t (text) elements", "if", "element", ".", "text", ":", "# Add this element to searchels", "searchels", ".", "append", "(", "element", ")", "if", "len", "(", "searchels", ")", ">", "bs", ":", "# Is searchels is too long, remove first elements", "searchels", ".", "pop", "(", "0", ")", "# Search all combinations, of searchels, starting from", "# smaller up to bigger ones", "# l = search lenght", "# s = search start", "# e = element IDs to merge", "found", "=", "False", "for", "l", "in", "range", "(", "1", ",", "len", "(", "searchels", ")", "+", "1", ")", ":", "if", "found", ":", "break", "for", "s", "in", "range", "(", "len", "(", "searchels", ")", ")", ":", "if", "found", ":", "break", "if", "s", "+", "l", "<=", "len", "(", "searchels", ")", ":", "e", "=", "range", "(", "s", ",", "s", "+", "l", ")", "txtsearch", "=", "''", "for", "k", "in", "e", ":", "txtsearch", "+=", "searchels", "[", "k", "]", ".", "text", "# Searcs for the text in the whole txtsearch", "match", "=", "searchre", ".", "search", "(", "txtsearch", ")", "if", "match", ":", "matches", ".", "append", "(", "match", ".", "group", "(", ")", ")", "found", "=", "True", "return", "set", "(", "matches", ")" ]
Return set of all regex matches This is an advanced version of python-docx.search() that takes into account blocks of <bs> elements at a time. What it does: It searches the entire document body for text blocks. Since the text to search could be spawned across multiple text blocks, we need to adopt some sort of algorithm to handle this situation. The smaller matching group of blocks (up to bs) is then adopted. If the matching group has more than one block, blocks other than first are cleared and all the replacement text is put on first block. Examples: original text blocks : [ 'Hel', 'lo,', ' world!' ] search : 'Hello,' output blocks : [ 'Hello,' ] original text blocks : [ 'Hel', 'lo', ' __', 'name', '__!' ] search : '(__[a-z]+__)' output blocks : [ '__name__' ] @param instance document: The original document @param str search: The text to search for (regexp) append, or a list of etree elements @param int bs: See above @return set All occurences of search string
[ "Return", "set", "of", "all", "regex", "matches" ]
4c9b46dbebe3d2a9b82dbcd35af36584a36fd9fe
https://github.com/mikemaccana/python-docx/blob/4c9b46dbebe3d2a9b82dbcd35af36584a36fd9fe/docx.py#L683-L756
16,678
mikemaccana/python-docx
docx.py
getdocumenttext
def getdocumenttext(document): '''Return the raw text of a document, as a list of paragraphs.''' paratextlist = [] # Compile a list of all paragraph (p) elements paralist = [] for element in document.iter(): # Find p (paragraph) elements if element.tag == '{'+nsprefixes['w']+'}p': paralist.append(element) # Since a single sentence might be spread over multiple text elements, # iterate through each paragraph, appending all text (t) children to that # paragraphs text. for para in paralist: paratext = u'' # Loop through each paragraph for element in para.iter(): # Find t (text) elements if element.tag == '{'+nsprefixes['w']+'}t': if element.text: paratext = paratext+element.text elif element.tag == '{'+nsprefixes['w']+'}tab': paratext = paratext + '\t' # Add our completed paragraph text to the list of paragraph text if not len(paratext) == 0: paratextlist.append(paratext) return paratextlist
python
def getdocumenttext(document): '''Return the raw text of a document, as a list of paragraphs.''' paratextlist = [] # Compile a list of all paragraph (p) elements paralist = [] for element in document.iter(): # Find p (paragraph) elements if element.tag == '{'+nsprefixes['w']+'}p': paralist.append(element) # Since a single sentence might be spread over multiple text elements, # iterate through each paragraph, appending all text (t) children to that # paragraphs text. for para in paralist: paratext = u'' # Loop through each paragraph for element in para.iter(): # Find t (text) elements if element.tag == '{'+nsprefixes['w']+'}t': if element.text: paratext = paratext+element.text elif element.tag == '{'+nsprefixes['w']+'}tab': paratext = paratext + '\t' # Add our completed paragraph text to the list of paragraph text if not len(paratext) == 0: paratextlist.append(paratext) return paratextlist
[ "def", "getdocumenttext", "(", "document", ")", ":", "paratextlist", "=", "[", "]", "# Compile a list of all paragraph (p) elements", "paralist", "=", "[", "]", "for", "element", "in", "document", ".", "iter", "(", ")", ":", "# Find p (paragraph) elements", "if", "element", ".", "tag", "==", "'{'", "+", "nsprefixes", "[", "'w'", "]", "+", "'}p'", ":", "paralist", ".", "append", "(", "element", ")", "# Since a single sentence might be spread over multiple text elements,", "# iterate through each paragraph, appending all text (t) children to that", "# paragraphs text.", "for", "para", "in", "paralist", ":", "paratext", "=", "u''", "# Loop through each paragraph", "for", "element", "in", "para", ".", "iter", "(", ")", ":", "# Find t (text) elements", "if", "element", ".", "tag", "==", "'{'", "+", "nsprefixes", "[", "'w'", "]", "+", "'}t'", ":", "if", "element", ".", "text", ":", "paratext", "=", "paratext", "+", "element", ".", "text", "elif", "element", ".", "tag", "==", "'{'", "+", "nsprefixes", "[", "'w'", "]", "+", "'}tab'", ":", "paratext", "=", "paratext", "+", "'\\t'", "# Add our completed paragraph text to the list of paragraph text", "if", "not", "len", "(", "paratext", ")", "==", "0", ":", "paratextlist", ".", "append", "(", "paratext", ")", "return", "paratextlist" ]
Return the raw text of a document, as a list of paragraphs.
[ "Return", "the", "raw", "text", "of", "a", "document", "as", "a", "list", "of", "paragraphs", "." ]
4c9b46dbebe3d2a9b82dbcd35af36584a36fd9fe
https://github.com/mikemaccana/python-docx/blob/4c9b46dbebe3d2a9b82dbcd35af36584a36fd9fe/docx.py#L910-L935
16,679
mikemaccana/python-docx
docx.py
wordrelationships
def wordrelationships(relationshiplist): '''Generate a Word relationships file''' # Default list of relationships # FIXME: using string hack instead of making element #relationships = makeelement('Relationships', nsprefix='pr') relationships = etree.fromstring( '<Relationships xmlns="http://schemas.openxmlformats.org/package/2006' '/relationships"></Relationships>') count = 0 for relationship in relationshiplist: # Relationship IDs (rId) start at 1. rel_elm = makeelement('Relationship', nsprefix=None, attributes={'Id': 'rId'+str(count+1), 'Type': relationship[0], 'Target': relationship[1]} ) relationships.append(rel_elm) count += 1 return relationships
python
def wordrelationships(relationshiplist): '''Generate a Word relationships file''' # Default list of relationships # FIXME: using string hack instead of making element #relationships = makeelement('Relationships', nsprefix='pr') relationships = etree.fromstring( '<Relationships xmlns="http://schemas.openxmlformats.org/package/2006' '/relationships"></Relationships>') count = 0 for relationship in relationshiplist: # Relationship IDs (rId) start at 1. rel_elm = makeelement('Relationship', nsprefix=None, attributes={'Id': 'rId'+str(count+1), 'Type': relationship[0], 'Target': relationship[1]} ) relationships.append(rel_elm) count += 1 return relationships
[ "def", "wordrelationships", "(", "relationshiplist", ")", ":", "# Default list of relationships", "# FIXME: using string hack instead of making element", "#relationships = makeelement('Relationships', nsprefix='pr')", "relationships", "=", "etree", ".", "fromstring", "(", "'<Relationships xmlns=\"http://schemas.openxmlformats.org/package/2006'", "'/relationships\"></Relationships>'", ")", "count", "=", "0", "for", "relationship", "in", "relationshiplist", ":", "# Relationship IDs (rId) start at 1.", "rel_elm", "=", "makeelement", "(", "'Relationship'", ",", "nsprefix", "=", "None", ",", "attributes", "=", "{", "'Id'", ":", "'rId'", "+", "str", "(", "count", "+", "1", ")", ",", "'Type'", ":", "relationship", "[", "0", "]", ",", "'Target'", ":", "relationship", "[", "1", "]", "}", ")", "relationships", ".", "append", "(", "rel_elm", ")", "count", "+=", "1", "return", "relationships" ]
Generate a Word relationships file
[ "Generate", "a", "Word", "relationships", "file" ]
4c9b46dbebe3d2a9b82dbcd35af36584a36fd9fe
https://github.com/mikemaccana/python-docx/blob/4c9b46dbebe3d2a9b82dbcd35af36584a36fd9fe/docx.py#L1031-L1049
16,680
mikemaccana/python-docx
docx.py
savedocx
def savedocx( document, coreprops, appprops, contenttypes, websettings, wordrelationships, output, imagefiledict=None): """ Save a modified document """ if imagefiledict is None: warn( 'Using savedocx() without imagefiledict parameter will be deprec' 'ated in the future.', PendingDeprecationWarning ) assert os.path.isdir(template_dir) docxfile = zipfile.ZipFile( output, mode='w', compression=zipfile.ZIP_DEFLATED) # Move to the template data path prev_dir = os.path.abspath('.') # save previous working dir os.chdir(template_dir) # Serialize our trees into out zip file treesandfiles = { document: 'word/document.xml', coreprops: 'docProps/core.xml', appprops: 'docProps/app.xml', contenttypes: '[Content_Types].xml', websettings: 'word/webSettings.xml', wordrelationships: 'word/_rels/document.xml.rels' } for tree in treesandfiles: log.info('Saving: %s' % treesandfiles[tree]) treestring = etree.tostring(tree, pretty_print=True) docxfile.writestr(treesandfiles[tree], treestring) # Add & compress images, if applicable if imagefiledict is not None: for imagepath, picrelid in imagefiledict.items(): archivename = 'word/media/%s_%s' % (picrelid, basename(imagepath)) log.info('Saving: %s', archivename) docxfile.write(imagepath, archivename) # Add & compress support files files_to_ignore = ['.DS_Store'] # nuisance from some os's for dirpath, dirnames, filenames in os.walk('.'): for filename in filenames: if filename in files_to_ignore: continue templatefile = join(dirpath, filename) archivename = templatefile[2:] log.info('Saving: %s', archivename) docxfile.write(templatefile, archivename) log.info('Saved new file to: %r', output) docxfile.close() os.chdir(prev_dir) # restore previous working dir return
python
def savedocx( document, coreprops, appprops, contenttypes, websettings, wordrelationships, output, imagefiledict=None): """ Save a modified document """ if imagefiledict is None: warn( 'Using savedocx() without imagefiledict parameter will be deprec' 'ated in the future.', PendingDeprecationWarning ) assert os.path.isdir(template_dir) docxfile = zipfile.ZipFile( output, mode='w', compression=zipfile.ZIP_DEFLATED) # Move to the template data path prev_dir = os.path.abspath('.') # save previous working dir os.chdir(template_dir) # Serialize our trees into out zip file treesandfiles = { document: 'word/document.xml', coreprops: 'docProps/core.xml', appprops: 'docProps/app.xml', contenttypes: '[Content_Types].xml', websettings: 'word/webSettings.xml', wordrelationships: 'word/_rels/document.xml.rels' } for tree in treesandfiles: log.info('Saving: %s' % treesandfiles[tree]) treestring = etree.tostring(tree, pretty_print=True) docxfile.writestr(treesandfiles[tree], treestring) # Add & compress images, if applicable if imagefiledict is not None: for imagepath, picrelid in imagefiledict.items(): archivename = 'word/media/%s_%s' % (picrelid, basename(imagepath)) log.info('Saving: %s', archivename) docxfile.write(imagepath, archivename) # Add & compress support files files_to_ignore = ['.DS_Store'] # nuisance from some os's for dirpath, dirnames, filenames in os.walk('.'): for filename in filenames: if filename in files_to_ignore: continue templatefile = join(dirpath, filename) archivename = templatefile[2:] log.info('Saving: %s', archivename) docxfile.write(templatefile, archivename) log.info('Saved new file to: %r', output) docxfile.close() os.chdir(prev_dir) # restore previous working dir return
[ "def", "savedocx", "(", "document", ",", "coreprops", ",", "appprops", ",", "contenttypes", ",", "websettings", ",", "wordrelationships", ",", "output", ",", "imagefiledict", "=", "None", ")", ":", "if", "imagefiledict", "is", "None", ":", "warn", "(", "'Using savedocx() without imagefiledict parameter will be deprec'", "'ated in the future.'", ",", "PendingDeprecationWarning", ")", "assert", "os", ".", "path", ".", "isdir", "(", "template_dir", ")", "docxfile", "=", "zipfile", ".", "ZipFile", "(", "output", ",", "mode", "=", "'w'", ",", "compression", "=", "zipfile", ".", "ZIP_DEFLATED", ")", "# Move to the template data path", "prev_dir", "=", "os", ".", "path", ".", "abspath", "(", "'.'", ")", "# save previous working dir", "os", ".", "chdir", "(", "template_dir", ")", "# Serialize our trees into out zip file", "treesandfiles", "=", "{", "document", ":", "'word/document.xml'", ",", "coreprops", ":", "'docProps/core.xml'", ",", "appprops", ":", "'docProps/app.xml'", ",", "contenttypes", ":", "'[Content_Types].xml'", ",", "websettings", ":", "'word/webSettings.xml'", ",", "wordrelationships", ":", "'word/_rels/document.xml.rels'", "}", "for", "tree", "in", "treesandfiles", ":", "log", ".", "info", "(", "'Saving: %s'", "%", "treesandfiles", "[", "tree", "]", ")", "treestring", "=", "etree", ".", "tostring", "(", "tree", ",", "pretty_print", "=", "True", ")", "docxfile", ".", "writestr", "(", "treesandfiles", "[", "tree", "]", ",", "treestring", ")", "# Add & compress images, if applicable", "if", "imagefiledict", "is", "not", "None", ":", "for", "imagepath", ",", "picrelid", "in", "imagefiledict", ".", "items", "(", ")", ":", "archivename", "=", "'word/media/%s_%s'", "%", "(", "picrelid", ",", "basename", "(", "imagepath", ")", ")", "log", ".", "info", "(", "'Saving: %s'", ",", "archivename", ")", "docxfile", ".", "write", "(", "imagepath", ",", "archivename", ")", "# Add & compress support files", "files_to_ignore", "=", "[", "'.DS_Store'", "]", "# nuisance from some os's", "for", "dirpath", ",", "dirnames", ",", "filenames", "in", "os", ".", "walk", "(", "'.'", ")", ":", "for", "filename", "in", "filenames", ":", "if", "filename", "in", "files_to_ignore", ":", "continue", "templatefile", "=", "join", "(", "dirpath", ",", "filename", ")", "archivename", "=", "templatefile", "[", "2", ":", "]", "log", ".", "info", "(", "'Saving: %s'", ",", "archivename", ")", "docxfile", ".", "write", "(", "templatefile", ",", "archivename", ")", "log", ".", "info", "(", "'Saved new file to: %r'", ",", "output", ")", "docxfile", ".", "close", "(", ")", "os", ".", "chdir", "(", "prev_dir", ")", "# restore previous working dir", "return" ]
Save a modified document
[ "Save", "a", "modified", "document" ]
4c9b46dbebe3d2a9b82dbcd35af36584a36fd9fe
https://github.com/mikemaccana/python-docx/blob/4c9b46dbebe3d2a9b82dbcd35af36584a36fd9fe/docx.py#L1052-L1107
16,681
couchbase/couchbase-python-client
couchbase/bucket.py
_depr
def _depr(fn, usage, stacklevel=3): """Internal convenience function for deprecation warnings""" warn('{0} is deprecated. Use {1} instead'.format(fn, usage), stacklevel=stacklevel, category=DeprecationWarning)
python
def _depr(fn, usage, stacklevel=3): """Internal convenience function for deprecation warnings""" warn('{0} is deprecated. Use {1} instead'.format(fn, usage), stacklevel=stacklevel, category=DeprecationWarning)
[ "def", "_depr", "(", "fn", ",", "usage", ",", "stacklevel", "=", "3", ")", ":", "warn", "(", "'{0} is deprecated. Use {1} instead'", ".", "format", "(", "fn", ",", "usage", ")", ",", "stacklevel", "=", "stacklevel", ",", "category", "=", "DeprecationWarning", ")" ]
Internal convenience function for deprecation warnings
[ "Internal", "convenience", "function", "for", "deprecation", "warnings" ]
a7bada167785bf79a29c39f820d932a433a6a535
https://github.com/couchbase/couchbase-python-client/blob/a7bada167785bf79a29c39f820d932a433a6a535/couchbase/bucket.py#L44-L47
16,682
couchbase/couchbase-python-client
couchbase/bucket.py
Bucket.upsert
def upsert(self, key, value, cas=0, ttl=0, format=None, persist_to=0, replicate_to=0): """Unconditionally store the object in Couchbase. :param key: The key to set the value with. By default, the key must be either a :class:`bytes` or :class:`str` object encodable as UTF-8. If a custom `transcoder` class is used (see :meth:`~__init__`), then the key object is passed directly to the transcoder, which may serialize it how it wishes. :type key: string or bytes :param value: The value to set for the key. This should be a native Python value which will be transparently serialized to JSON by the library. Do not pass already-serialized JSON as the value or it will be serialized again. If you are using a different `format` setting (see `format` parameter), and/or a custom transcoder then value for this argument may need to conform to different criteria. :param int cas: The _CAS_ value to use. If supplied, the value will only be stored if it already exists with the supplied CAS :param int ttl: If specified, the key will expire after this many seconds :param int format: If specified, indicates the `format` to use when encoding the value. If none is specified, it will use the `default_format` For more info see :attr:`~.default_format` :param int persist_to: Perform durability checking on this many nodes nodes for persistence to disk. See :meth:`endure` for more information :param int replicate_to: Perform durability checking on this many replicas for presence in memory. See :meth:`endure` for more information. :raise: :exc:`.ArgumentError` if an argument is supplied that is not applicable in this context. For example setting the CAS as a string. :raise: :exc`.CouchbaseNetworkError` :raise: :exc:`.KeyExistsError` if the key already exists on the server with a different CAS value. :raise: :exc:`.ValueFormatError` if the value cannot be serialized with chosen encoder, e.g. if you try to store a dictionary in plain mode. :return: :class:`~.Result`. Simple set:: cb.upsert('key', 'value') Force JSON document format for value:: cb.upsert('foo', {'bar': 'baz'}, format=couchbase.FMT_JSON) Insert JSON from a string:: JSONstr = '{"key1": "value1", "key2": 123}' JSONobj = json.loads(JSONstr) cb.upsert("documentID", JSONobj, format=couchbase.FMT_JSON) Force UTF8 document format for value:: cb.upsert('foo', "<xml></xml>", format=couchbase.FMT_UTF8) Perform optimistic locking by specifying last known CAS version:: cb.upsert('foo', 'bar', cas=8835713818674332672) Several sets at the same time (mutli-set):: cb.upsert_multi({'foo': 'bar', 'baz': 'value'}) .. seealso:: :meth:`upsert_multi` """ return _Base.upsert(self, key, value, cas=cas, ttl=ttl, format=format, persist_to=persist_to, replicate_to=replicate_to)
python
def upsert(self, key, value, cas=0, ttl=0, format=None, persist_to=0, replicate_to=0): """Unconditionally store the object in Couchbase. :param key: The key to set the value with. By default, the key must be either a :class:`bytes` or :class:`str` object encodable as UTF-8. If a custom `transcoder` class is used (see :meth:`~__init__`), then the key object is passed directly to the transcoder, which may serialize it how it wishes. :type key: string or bytes :param value: The value to set for the key. This should be a native Python value which will be transparently serialized to JSON by the library. Do not pass already-serialized JSON as the value or it will be serialized again. If you are using a different `format` setting (see `format` parameter), and/or a custom transcoder then value for this argument may need to conform to different criteria. :param int cas: The _CAS_ value to use. If supplied, the value will only be stored if it already exists with the supplied CAS :param int ttl: If specified, the key will expire after this many seconds :param int format: If specified, indicates the `format` to use when encoding the value. If none is specified, it will use the `default_format` For more info see :attr:`~.default_format` :param int persist_to: Perform durability checking on this many nodes nodes for persistence to disk. See :meth:`endure` for more information :param int replicate_to: Perform durability checking on this many replicas for presence in memory. See :meth:`endure` for more information. :raise: :exc:`.ArgumentError` if an argument is supplied that is not applicable in this context. For example setting the CAS as a string. :raise: :exc`.CouchbaseNetworkError` :raise: :exc:`.KeyExistsError` if the key already exists on the server with a different CAS value. :raise: :exc:`.ValueFormatError` if the value cannot be serialized with chosen encoder, e.g. if you try to store a dictionary in plain mode. :return: :class:`~.Result`. Simple set:: cb.upsert('key', 'value') Force JSON document format for value:: cb.upsert('foo', {'bar': 'baz'}, format=couchbase.FMT_JSON) Insert JSON from a string:: JSONstr = '{"key1": "value1", "key2": 123}' JSONobj = json.loads(JSONstr) cb.upsert("documentID", JSONobj, format=couchbase.FMT_JSON) Force UTF8 document format for value:: cb.upsert('foo', "<xml></xml>", format=couchbase.FMT_UTF8) Perform optimistic locking by specifying last known CAS version:: cb.upsert('foo', 'bar', cas=8835713818674332672) Several sets at the same time (mutli-set):: cb.upsert_multi({'foo': 'bar', 'baz': 'value'}) .. seealso:: :meth:`upsert_multi` """ return _Base.upsert(self, key, value, cas=cas, ttl=ttl, format=format, persist_to=persist_to, replicate_to=replicate_to)
[ "def", "upsert", "(", "self", ",", "key", ",", "value", ",", "cas", "=", "0", ",", "ttl", "=", "0", ",", "format", "=", "None", ",", "persist_to", "=", "0", ",", "replicate_to", "=", "0", ")", ":", "return", "_Base", ".", "upsert", "(", "self", ",", "key", ",", "value", ",", "cas", "=", "cas", ",", "ttl", "=", "ttl", ",", "format", "=", "format", ",", "persist_to", "=", "persist_to", ",", "replicate_to", "=", "replicate_to", ")" ]
Unconditionally store the object in Couchbase. :param key: The key to set the value with. By default, the key must be either a :class:`bytes` or :class:`str` object encodable as UTF-8. If a custom `transcoder` class is used (see :meth:`~__init__`), then the key object is passed directly to the transcoder, which may serialize it how it wishes. :type key: string or bytes :param value: The value to set for the key. This should be a native Python value which will be transparently serialized to JSON by the library. Do not pass already-serialized JSON as the value or it will be serialized again. If you are using a different `format` setting (see `format` parameter), and/or a custom transcoder then value for this argument may need to conform to different criteria. :param int cas: The _CAS_ value to use. If supplied, the value will only be stored if it already exists with the supplied CAS :param int ttl: If specified, the key will expire after this many seconds :param int format: If specified, indicates the `format` to use when encoding the value. If none is specified, it will use the `default_format` For more info see :attr:`~.default_format` :param int persist_to: Perform durability checking on this many nodes nodes for persistence to disk. See :meth:`endure` for more information :param int replicate_to: Perform durability checking on this many replicas for presence in memory. See :meth:`endure` for more information. :raise: :exc:`.ArgumentError` if an argument is supplied that is not applicable in this context. For example setting the CAS as a string. :raise: :exc`.CouchbaseNetworkError` :raise: :exc:`.KeyExistsError` if the key already exists on the server with a different CAS value. :raise: :exc:`.ValueFormatError` if the value cannot be serialized with chosen encoder, e.g. if you try to store a dictionary in plain mode. :return: :class:`~.Result`. Simple set:: cb.upsert('key', 'value') Force JSON document format for value:: cb.upsert('foo', {'bar': 'baz'}, format=couchbase.FMT_JSON) Insert JSON from a string:: JSONstr = '{"key1": "value1", "key2": 123}' JSONobj = json.loads(JSONstr) cb.upsert("documentID", JSONobj, format=couchbase.FMT_JSON) Force UTF8 document format for value:: cb.upsert('foo', "<xml></xml>", format=couchbase.FMT_UTF8) Perform optimistic locking by specifying last known CAS version:: cb.upsert('foo', 'bar', cas=8835713818674332672) Several sets at the same time (mutli-set):: cb.upsert_multi({'foo': 'bar', 'baz': 'value'}) .. seealso:: :meth:`upsert_multi`
[ "Unconditionally", "store", "the", "object", "in", "Couchbase", "." ]
a7bada167785bf79a29c39f820d932a433a6a535
https://github.com/couchbase/couchbase-python-client/blob/a7bada167785bf79a29c39f820d932a433a6a535/couchbase/bucket.py#L328-L410
16,683
couchbase/couchbase-python-client
couchbase/bucket.py
Bucket.insert
def insert(self, key, value, ttl=0, format=None, persist_to=0, replicate_to=0): """Store an object in Couchbase unless it already exists. Follows the same conventions as :meth:`upsert` but the value is stored only if it does not exist already. Conversely, the value is not stored if the key already exists. Notably missing from this method is the `cas` parameter, this is because `insert` will only succeed if a key does not already exist on the server (and thus can have no CAS) :raise: :exc:`.KeyExistsError` if the key already exists .. seealso:: :meth:`upsert`, :meth:`insert_multi` """ return _Base.insert(self, key, value, ttl=ttl, format=format, persist_to=persist_to, replicate_to=replicate_to)
python
def insert(self, key, value, ttl=0, format=None, persist_to=0, replicate_to=0): """Store an object in Couchbase unless it already exists. Follows the same conventions as :meth:`upsert` but the value is stored only if it does not exist already. Conversely, the value is not stored if the key already exists. Notably missing from this method is the `cas` parameter, this is because `insert` will only succeed if a key does not already exist on the server (and thus can have no CAS) :raise: :exc:`.KeyExistsError` if the key already exists .. seealso:: :meth:`upsert`, :meth:`insert_multi` """ return _Base.insert(self, key, value, ttl=ttl, format=format, persist_to=persist_to, replicate_to=replicate_to)
[ "def", "insert", "(", "self", ",", "key", ",", "value", ",", "ttl", "=", "0", ",", "format", "=", "None", ",", "persist_to", "=", "0", ",", "replicate_to", "=", "0", ")", ":", "return", "_Base", ".", "insert", "(", "self", ",", "key", ",", "value", ",", "ttl", "=", "ttl", ",", "format", "=", "format", ",", "persist_to", "=", "persist_to", ",", "replicate_to", "=", "replicate_to", ")" ]
Store an object in Couchbase unless it already exists. Follows the same conventions as :meth:`upsert` but the value is stored only if it does not exist already. Conversely, the value is not stored if the key already exists. Notably missing from this method is the `cas` parameter, this is because `insert` will only succeed if a key does not already exist on the server (and thus can have no CAS) :raise: :exc:`.KeyExistsError` if the key already exists .. seealso:: :meth:`upsert`, :meth:`insert_multi`
[ "Store", "an", "object", "in", "Couchbase", "unless", "it", "already", "exists", "." ]
a7bada167785bf79a29c39f820d932a433a6a535
https://github.com/couchbase/couchbase-python-client/blob/a7bada167785bf79a29c39f820d932a433a6a535/couchbase/bucket.py#L412-L428
16,684
couchbase/couchbase-python-client
couchbase/bucket.py
Bucket.prepend
def prepend(self, key, value, cas=0, format=None, persist_to=0, replicate_to=0): """Prepend a string to an existing value in Couchbase. .. seealso:: :meth:`append`, :meth:`prepend_multi` """ return _Base.prepend(self, key, value, cas=cas, format=format, persist_to=persist_to, replicate_to=replicate_to)
python
def prepend(self, key, value, cas=0, format=None, persist_to=0, replicate_to=0): """Prepend a string to an existing value in Couchbase. .. seealso:: :meth:`append`, :meth:`prepend_multi` """ return _Base.prepend(self, key, value, cas=cas, format=format, persist_to=persist_to, replicate_to=replicate_to)
[ "def", "prepend", "(", "self", ",", "key", ",", "value", ",", "cas", "=", "0", ",", "format", "=", "None", ",", "persist_to", "=", "0", ",", "replicate_to", "=", "0", ")", ":", "return", "_Base", ".", "prepend", "(", "self", ",", "key", ",", "value", ",", "cas", "=", "cas", ",", "format", "=", "format", ",", "persist_to", "=", "persist_to", ",", "replicate_to", "=", "replicate_to", ")" ]
Prepend a string to an existing value in Couchbase. .. seealso:: :meth:`append`, :meth:`prepend_multi`
[ "Prepend", "a", "string", "to", "an", "existing", "value", "in", "Couchbase", "." ]
a7bada167785bf79a29c39f820d932a433a6a535
https://github.com/couchbase/couchbase-python-client/blob/a7bada167785bf79a29c39f820d932a433a6a535/couchbase/bucket.py#L475-L482
16,685
couchbase/couchbase-python-client
couchbase/bucket.py
Bucket.get
def get(self, key, ttl=0, quiet=None, replica=False, no_format=False): """Obtain an object stored in Couchbase by given key. :param string key: The key to fetch. The type of key is the same as mentioned in :meth:`upsert` :param int ttl: If specified, indicates that the key's expiration time should be *modified* when retrieving the value. :param boolean quiet: causes `get` to return None instead of raising an exception when the key is not found. It defaults to the value set by :attr:`~quiet` on the instance. In `quiet` mode, the error may still be obtained by inspecting the :attr:`~.Result.rc` attribute of the :class:`.Result` object, or checking :attr:`.Result.success`. Note that the default value is `None`, which means to use the :attr:`quiet`. If it is a boolean (i.e. `True` or `False`) it will override the `couchbase.bucket.Bucket`-level :attr:`quiet` attribute. :param bool replica: Whether to fetch this key from a replica rather than querying the master server. This is primarily useful when operations with the master fail (possibly due to a configuration change). It should normally be used in an exception handler like so Using the ``replica`` option:: try: res = c.get("key", quiet=True) # suppress not-found errors catch CouchbaseError: res = c.get("key", replica=True, quiet=True) :param bool no_format: If set to ``True``, then the value will always be delivered in the :class:`~couchbase.result.Result` object as being of :data:`~couchbase.FMT_BYTES`. This is a item-local equivalent of using the :attr:`data_passthrough` option :raise: :exc:`.NotFoundError` if the key does not exist :raise: :exc:`.CouchbaseNetworkError` :raise: :exc:`.ValueFormatError` if the value cannot be deserialized with chosen decoder, e.g. if you try to retreive an object stored with an unrecognized format :return: A :class:`~.Result` object Simple get:: value = cb.get('key').value Get multiple values:: cb.get_multi(['foo', 'bar']) # { 'foo' : <Result(...)>, 'bar' : <Result(...)> } Inspect the flags:: rv = cb.get("key") value, flags, cas = rv.value, rv.flags, rv.cas Update the expiration time:: rv = cb.get("key", ttl=10) # Expires in ten seconds .. seealso:: :meth:`get_multi` """ return _Base.get(self, key, ttl=ttl, quiet=quiet, replica=replica, no_format=no_format)
python
def get(self, key, ttl=0, quiet=None, replica=False, no_format=False): """Obtain an object stored in Couchbase by given key. :param string key: The key to fetch. The type of key is the same as mentioned in :meth:`upsert` :param int ttl: If specified, indicates that the key's expiration time should be *modified* when retrieving the value. :param boolean quiet: causes `get` to return None instead of raising an exception when the key is not found. It defaults to the value set by :attr:`~quiet` on the instance. In `quiet` mode, the error may still be obtained by inspecting the :attr:`~.Result.rc` attribute of the :class:`.Result` object, or checking :attr:`.Result.success`. Note that the default value is `None`, which means to use the :attr:`quiet`. If it is a boolean (i.e. `True` or `False`) it will override the `couchbase.bucket.Bucket`-level :attr:`quiet` attribute. :param bool replica: Whether to fetch this key from a replica rather than querying the master server. This is primarily useful when operations with the master fail (possibly due to a configuration change). It should normally be used in an exception handler like so Using the ``replica`` option:: try: res = c.get("key", quiet=True) # suppress not-found errors catch CouchbaseError: res = c.get("key", replica=True, quiet=True) :param bool no_format: If set to ``True``, then the value will always be delivered in the :class:`~couchbase.result.Result` object as being of :data:`~couchbase.FMT_BYTES`. This is a item-local equivalent of using the :attr:`data_passthrough` option :raise: :exc:`.NotFoundError` if the key does not exist :raise: :exc:`.CouchbaseNetworkError` :raise: :exc:`.ValueFormatError` if the value cannot be deserialized with chosen decoder, e.g. if you try to retreive an object stored with an unrecognized format :return: A :class:`~.Result` object Simple get:: value = cb.get('key').value Get multiple values:: cb.get_multi(['foo', 'bar']) # { 'foo' : <Result(...)>, 'bar' : <Result(...)> } Inspect the flags:: rv = cb.get("key") value, flags, cas = rv.value, rv.flags, rv.cas Update the expiration time:: rv = cb.get("key", ttl=10) # Expires in ten seconds .. seealso:: :meth:`get_multi` """ return _Base.get(self, key, ttl=ttl, quiet=quiet, replica=replica, no_format=no_format)
[ "def", "get", "(", "self", ",", "key", ",", "ttl", "=", "0", ",", "quiet", "=", "None", ",", "replica", "=", "False", ",", "no_format", "=", "False", ")", ":", "return", "_Base", ".", "get", "(", "self", ",", "key", ",", "ttl", "=", "ttl", ",", "quiet", "=", "quiet", ",", "replica", "=", "replica", ",", "no_format", "=", "no_format", ")" ]
Obtain an object stored in Couchbase by given key. :param string key: The key to fetch. The type of key is the same as mentioned in :meth:`upsert` :param int ttl: If specified, indicates that the key's expiration time should be *modified* when retrieving the value. :param boolean quiet: causes `get` to return None instead of raising an exception when the key is not found. It defaults to the value set by :attr:`~quiet` on the instance. In `quiet` mode, the error may still be obtained by inspecting the :attr:`~.Result.rc` attribute of the :class:`.Result` object, or checking :attr:`.Result.success`. Note that the default value is `None`, which means to use the :attr:`quiet`. If it is a boolean (i.e. `True` or `False`) it will override the `couchbase.bucket.Bucket`-level :attr:`quiet` attribute. :param bool replica: Whether to fetch this key from a replica rather than querying the master server. This is primarily useful when operations with the master fail (possibly due to a configuration change). It should normally be used in an exception handler like so Using the ``replica`` option:: try: res = c.get("key", quiet=True) # suppress not-found errors catch CouchbaseError: res = c.get("key", replica=True, quiet=True) :param bool no_format: If set to ``True``, then the value will always be delivered in the :class:`~couchbase.result.Result` object as being of :data:`~couchbase.FMT_BYTES`. This is a item-local equivalent of using the :attr:`data_passthrough` option :raise: :exc:`.NotFoundError` if the key does not exist :raise: :exc:`.CouchbaseNetworkError` :raise: :exc:`.ValueFormatError` if the value cannot be deserialized with chosen decoder, e.g. if you try to retreive an object stored with an unrecognized format :return: A :class:`~.Result` object Simple get:: value = cb.get('key').value Get multiple values:: cb.get_multi(['foo', 'bar']) # { 'foo' : <Result(...)>, 'bar' : <Result(...)> } Inspect the flags:: rv = cb.get("key") value, flags, cas = rv.value, rv.flags, rv.cas Update the expiration time:: rv = cb.get("key", ttl=10) # Expires in ten seconds .. seealso:: :meth:`get_multi`
[ "Obtain", "an", "object", "stored", "in", "Couchbase", "by", "given", "key", "." ]
a7bada167785bf79a29c39f820d932a433a6a535
https://github.com/couchbase/couchbase-python-client/blob/a7bada167785bf79a29c39f820d932a433a6a535/couchbase/bucket.py#L484-L554
16,686
couchbase/couchbase-python-client
couchbase/bucket.py
Bucket.touch
def touch(self, key, ttl=0): """Update a key's expiration time :param string key: The key whose expiration time should be modified :param int ttl: The new expiration time. If the expiration time is `0` then the key never expires (and any existing expiration is removed) :return: :class:`.OperationResult` Update the expiration time of a key :: cb.upsert("key", ttl=100) # expires in 100 seconds cb.touch("key", ttl=0) # key should never expire now :raise: The same things that :meth:`get` does .. seealso:: :meth:`get` - which can be used to get *and* update the expiration, :meth:`touch_multi` """ return _Base.touch(self, key, ttl=ttl)
python
def touch(self, key, ttl=0): """Update a key's expiration time :param string key: The key whose expiration time should be modified :param int ttl: The new expiration time. If the expiration time is `0` then the key never expires (and any existing expiration is removed) :return: :class:`.OperationResult` Update the expiration time of a key :: cb.upsert("key", ttl=100) # expires in 100 seconds cb.touch("key", ttl=0) # key should never expire now :raise: The same things that :meth:`get` does .. seealso:: :meth:`get` - which can be used to get *and* update the expiration, :meth:`touch_multi` """ return _Base.touch(self, key, ttl=ttl)
[ "def", "touch", "(", "self", ",", "key", ",", "ttl", "=", "0", ")", ":", "return", "_Base", ".", "touch", "(", "self", ",", "key", ",", "ttl", "=", "ttl", ")" ]
Update a key's expiration time :param string key: The key whose expiration time should be modified :param int ttl: The new expiration time. If the expiration time is `0` then the key never expires (and any existing expiration is removed) :return: :class:`.OperationResult` Update the expiration time of a key :: cb.upsert("key", ttl=100) # expires in 100 seconds cb.touch("key", ttl=0) # key should never expire now :raise: The same things that :meth:`get` does .. seealso:: :meth:`get` - which can be used to get *and* update the expiration, :meth:`touch_multi`
[ "Update", "a", "key", "s", "expiration", "time" ]
a7bada167785bf79a29c39f820d932a433a6a535
https://github.com/couchbase/couchbase-python-client/blob/a7bada167785bf79a29c39f820d932a433a6a535/couchbase/bucket.py#L556-L578
16,687
couchbase/couchbase-python-client
couchbase/bucket.py
Bucket.lock
def lock(self, key, ttl=0): """Lock and retrieve a key-value entry in Couchbase. :param key: A string which is the key to lock. :param ttl: a TTL for which the lock should be valid. While the lock is active, attempts to access the key (via other :meth:`lock`, :meth:`upsert` or other mutation calls) will fail with an :exc:`.KeyExistsError`. Note that the value for this option is limited by the maximum allowable lock time determined by the server (currently, this is 30 seconds). If passed a higher value, the server will silently lower this to its maximum limit. This function otherwise functions similarly to :meth:`get`; specifically, it will return the value upon success. Note the :attr:`~.Result.cas` value from the :class:`.Result` object. This will be needed to :meth:`unlock` the key. Note the lock will also be implicitly released if modified by one of the :meth:`upsert` family of functions when the valid CAS is supplied :raise: :exc:`.TemporaryFailError` if the key is already locked. :raise: See :meth:`get` for possible exceptions Lock a key :: rv = cb.lock("locked_key", ttl=5) # This key is now locked for the next 5 seconds. # attempts to access this key will fail until the lock # is released. # do important stuff... cb.unlock("locked_key", rv.cas) Lock a key, implicitly unlocking with :meth:`upsert` with CAS :: rv = self.cb.lock("locked_key", ttl=5) new_value = rv.value.upper() cb.upsert("locked_key", new_value, rv.cas) Poll and Lock :: rv = None begin_time = time.time() while time.time() - begin_time < 15: try: rv = cb.lock("key", ttl=10) break except TemporaryFailError: print("Key is currently locked.. waiting") time.sleep(1) if not rv: raise Exception("Waited too long..") # Do stuff.. cb.unlock("key", rv.cas) .. seealso:: :meth:`get`, :meth:`lock_multi`, :meth:`unlock` """ return _Base.lock(self, key, ttl=ttl)
python
def lock(self, key, ttl=0): """Lock and retrieve a key-value entry in Couchbase. :param key: A string which is the key to lock. :param ttl: a TTL for which the lock should be valid. While the lock is active, attempts to access the key (via other :meth:`lock`, :meth:`upsert` or other mutation calls) will fail with an :exc:`.KeyExistsError`. Note that the value for this option is limited by the maximum allowable lock time determined by the server (currently, this is 30 seconds). If passed a higher value, the server will silently lower this to its maximum limit. This function otherwise functions similarly to :meth:`get`; specifically, it will return the value upon success. Note the :attr:`~.Result.cas` value from the :class:`.Result` object. This will be needed to :meth:`unlock` the key. Note the lock will also be implicitly released if modified by one of the :meth:`upsert` family of functions when the valid CAS is supplied :raise: :exc:`.TemporaryFailError` if the key is already locked. :raise: See :meth:`get` for possible exceptions Lock a key :: rv = cb.lock("locked_key", ttl=5) # This key is now locked for the next 5 seconds. # attempts to access this key will fail until the lock # is released. # do important stuff... cb.unlock("locked_key", rv.cas) Lock a key, implicitly unlocking with :meth:`upsert` with CAS :: rv = self.cb.lock("locked_key", ttl=5) new_value = rv.value.upper() cb.upsert("locked_key", new_value, rv.cas) Poll and Lock :: rv = None begin_time = time.time() while time.time() - begin_time < 15: try: rv = cb.lock("key", ttl=10) break except TemporaryFailError: print("Key is currently locked.. waiting") time.sleep(1) if not rv: raise Exception("Waited too long..") # Do stuff.. cb.unlock("key", rv.cas) .. seealso:: :meth:`get`, :meth:`lock_multi`, :meth:`unlock` """ return _Base.lock(self, key, ttl=ttl)
[ "def", "lock", "(", "self", ",", "key", ",", "ttl", "=", "0", ")", ":", "return", "_Base", ".", "lock", "(", "self", ",", "key", ",", "ttl", "=", "ttl", ")" ]
Lock and retrieve a key-value entry in Couchbase. :param key: A string which is the key to lock. :param ttl: a TTL for which the lock should be valid. While the lock is active, attempts to access the key (via other :meth:`lock`, :meth:`upsert` or other mutation calls) will fail with an :exc:`.KeyExistsError`. Note that the value for this option is limited by the maximum allowable lock time determined by the server (currently, this is 30 seconds). If passed a higher value, the server will silently lower this to its maximum limit. This function otherwise functions similarly to :meth:`get`; specifically, it will return the value upon success. Note the :attr:`~.Result.cas` value from the :class:`.Result` object. This will be needed to :meth:`unlock` the key. Note the lock will also be implicitly released if modified by one of the :meth:`upsert` family of functions when the valid CAS is supplied :raise: :exc:`.TemporaryFailError` if the key is already locked. :raise: See :meth:`get` for possible exceptions Lock a key :: rv = cb.lock("locked_key", ttl=5) # This key is now locked for the next 5 seconds. # attempts to access this key will fail until the lock # is released. # do important stuff... cb.unlock("locked_key", rv.cas) Lock a key, implicitly unlocking with :meth:`upsert` with CAS :: rv = self.cb.lock("locked_key", ttl=5) new_value = rv.value.upper() cb.upsert("locked_key", new_value, rv.cas) Poll and Lock :: rv = None begin_time = time.time() while time.time() - begin_time < 15: try: rv = cb.lock("key", ttl=10) break except TemporaryFailError: print("Key is currently locked.. waiting") time.sleep(1) if not rv: raise Exception("Waited too long..") # Do stuff.. cb.unlock("key", rv.cas) .. seealso:: :meth:`get`, :meth:`lock_multi`, :meth:`unlock`
[ "Lock", "and", "retrieve", "a", "key", "-", "value", "entry", "in", "Couchbase", "." ]
a7bada167785bf79a29c39f820d932a433a6a535
https://github.com/couchbase/couchbase-python-client/blob/a7bada167785bf79a29c39f820d932a433a6a535/couchbase/bucket.py#L580-L647
16,688
couchbase/couchbase-python-client
couchbase/bucket.py
Bucket.unlock
def unlock(self, key, cas): """Unlock a Locked Key in Couchbase. This unlocks an item previously locked by :meth:`lock` :param key: The key to unlock :param cas: The cas returned from :meth:`lock`'s :class:`.Result` object. See :meth:`lock` for an example. :raise: :exc:`.TemporaryFailError` if the CAS supplied does not match the CAS on the server (possibly because it was unlocked by previous call). .. seealso:: :meth:`lock` :meth:`unlock_multi` """ return _Base.unlock(self, key, cas=cas)
python
def unlock(self, key, cas): """Unlock a Locked Key in Couchbase. This unlocks an item previously locked by :meth:`lock` :param key: The key to unlock :param cas: The cas returned from :meth:`lock`'s :class:`.Result` object. See :meth:`lock` for an example. :raise: :exc:`.TemporaryFailError` if the CAS supplied does not match the CAS on the server (possibly because it was unlocked by previous call). .. seealso:: :meth:`lock` :meth:`unlock_multi` """ return _Base.unlock(self, key, cas=cas)
[ "def", "unlock", "(", "self", ",", "key", ",", "cas", ")", ":", "return", "_Base", ".", "unlock", "(", "self", ",", "key", ",", "cas", "=", "cas", ")" ]
Unlock a Locked Key in Couchbase. This unlocks an item previously locked by :meth:`lock` :param key: The key to unlock :param cas: The cas returned from :meth:`lock`'s :class:`.Result` object. See :meth:`lock` for an example. :raise: :exc:`.TemporaryFailError` if the CAS supplied does not match the CAS on the server (possibly because it was unlocked by previous call). .. seealso:: :meth:`lock` :meth:`unlock_multi`
[ "Unlock", "a", "Locked", "Key", "in", "Couchbase", "." ]
a7bada167785bf79a29c39f820d932a433a6a535
https://github.com/couchbase/couchbase-python-client/blob/a7bada167785bf79a29c39f820d932a433a6a535/couchbase/bucket.py#L649-L666
16,689
couchbase/couchbase-python-client
couchbase/bucket.py
Bucket.remove
def remove(self, key, cas=0, quiet=None, persist_to=0, replicate_to=0): """Remove the key-value entry for a given key in Couchbase. :param key: A string which is the key to remove. The format and type of the key follows the same conventions as in :meth:`upsert` :type key: string, dict, or tuple/list :param int cas: The CAS to use for the removal operation. If specified, the key will only be removed from the server if it has the same CAS as specified. This is useful to remove a key only if its value has not been changed from the version currently visible to the client. If the CAS on the server does not match the one specified, an exception is thrown. :param boolean quiet: Follows the same semantics as `quiet` in :meth:`get` :param int persist_to: If set, wait for the item to be removed from the storage of at least these many nodes :param int replicate_to: If set, wait for the item to be removed from the cache of at least these many nodes (excluding the master) :raise: :exc:`.NotFoundError` if the key does not exist. :raise: :exc:`.KeyExistsError` if a CAS was specified, but the CAS on the server had changed :return: A :class:`~.Result` object. Simple remove:: ok = cb.remove("key").success Don't complain if key does not exist:: ok = cb.remove("key", quiet=True) Only remove if CAS matches our version:: rv = cb.get("key") cb.remove("key", cas=rv.cas) Remove multiple keys:: oks = cb.remove_multi(["key1", "key2", "key3"]) Remove multiple keys with CAS:: oks = cb.remove({ "key1" : cas1, "key2" : cas2, "key3" : cas3 }) .. seealso:: :meth:`remove_multi`, :meth:`endure` for more information on the ``persist_to`` and ``replicate_to`` options. """ return _Base.remove(self, key, cas=cas, quiet=quiet, persist_to=persist_to, replicate_to=replicate_to)
python
def remove(self, key, cas=0, quiet=None, persist_to=0, replicate_to=0): """Remove the key-value entry for a given key in Couchbase. :param key: A string which is the key to remove. The format and type of the key follows the same conventions as in :meth:`upsert` :type key: string, dict, or tuple/list :param int cas: The CAS to use for the removal operation. If specified, the key will only be removed from the server if it has the same CAS as specified. This is useful to remove a key only if its value has not been changed from the version currently visible to the client. If the CAS on the server does not match the one specified, an exception is thrown. :param boolean quiet: Follows the same semantics as `quiet` in :meth:`get` :param int persist_to: If set, wait for the item to be removed from the storage of at least these many nodes :param int replicate_to: If set, wait for the item to be removed from the cache of at least these many nodes (excluding the master) :raise: :exc:`.NotFoundError` if the key does not exist. :raise: :exc:`.KeyExistsError` if a CAS was specified, but the CAS on the server had changed :return: A :class:`~.Result` object. Simple remove:: ok = cb.remove("key").success Don't complain if key does not exist:: ok = cb.remove("key", quiet=True) Only remove if CAS matches our version:: rv = cb.get("key") cb.remove("key", cas=rv.cas) Remove multiple keys:: oks = cb.remove_multi(["key1", "key2", "key3"]) Remove multiple keys with CAS:: oks = cb.remove({ "key1" : cas1, "key2" : cas2, "key3" : cas3 }) .. seealso:: :meth:`remove_multi`, :meth:`endure` for more information on the ``persist_to`` and ``replicate_to`` options. """ return _Base.remove(self, key, cas=cas, quiet=quiet, persist_to=persist_to, replicate_to=replicate_to)
[ "def", "remove", "(", "self", ",", "key", ",", "cas", "=", "0", ",", "quiet", "=", "None", ",", "persist_to", "=", "0", ",", "replicate_to", "=", "0", ")", ":", "return", "_Base", ".", "remove", "(", "self", ",", "key", ",", "cas", "=", "cas", ",", "quiet", "=", "quiet", ",", "persist_to", "=", "persist_to", ",", "replicate_to", "=", "replicate_to", ")" ]
Remove the key-value entry for a given key in Couchbase. :param key: A string which is the key to remove. The format and type of the key follows the same conventions as in :meth:`upsert` :type key: string, dict, or tuple/list :param int cas: The CAS to use for the removal operation. If specified, the key will only be removed from the server if it has the same CAS as specified. This is useful to remove a key only if its value has not been changed from the version currently visible to the client. If the CAS on the server does not match the one specified, an exception is thrown. :param boolean quiet: Follows the same semantics as `quiet` in :meth:`get` :param int persist_to: If set, wait for the item to be removed from the storage of at least these many nodes :param int replicate_to: If set, wait for the item to be removed from the cache of at least these many nodes (excluding the master) :raise: :exc:`.NotFoundError` if the key does not exist. :raise: :exc:`.KeyExistsError` if a CAS was specified, but the CAS on the server had changed :return: A :class:`~.Result` object. Simple remove:: ok = cb.remove("key").success Don't complain if key does not exist:: ok = cb.remove("key", quiet=True) Only remove if CAS matches our version:: rv = cb.get("key") cb.remove("key", cas=rv.cas) Remove multiple keys:: oks = cb.remove_multi(["key1", "key2", "key3"]) Remove multiple keys with CAS:: oks = cb.remove({ "key1" : cas1, "key2" : cas2, "key3" : cas3 }) .. seealso:: :meth:`remove_multi`, :meth:`endure` for more information on the ``persist_to`` and ``replicate_to`` options.
[ "Remove", "the", "key", "-", "value", "entry", "for", "a", "given", "key", "in", "Couchbase", "." ]
a7bada167785bf79a29c39f820d932a433a6a535
https://github.com/couchbase/couchbase-python-client/blob/a7bada167785bf79a29c39f820d932a433a6a535/couchbase/bucket.py#L668-L725
16,690
couchbase/couchbase-python-client
couchbase/bucket.py
Bucket.counter
def counter(self, key, delta=1, initial=None, ttl=0): """Increment or decrement the numeric value of an item. This method instructs the server to treat the item stored under the given key as a numeric counter. Counter operations require that the stored value exists as a string representation of a number (e.g. ``123``). If storing items using the :meth:`upsert` family of methods, and using the default :const:`couchbase.FMT_JSON` then the value will conform to this constraint. :param string key: A key whose counter value is to be modified :param int delta: an amount by which the key should be modified. If the number is negative then this number will be *subtracted* from the current value. :param initial: The initial value for the key, if it does not exist. If the key does not exist, this value is used, and `delta` is ignored. If this parameter is `None` then no initial value is used :type initial: int or `None` :param int ttl: The lifetime for the key, after which it will expire :raise: :exc:`.NotFoundError` if the key does not exist on the bucket (and `initial` was `None`) :raise: :exc:`.DeltaBadvalError` if the key exists, but the existing value is not numeric :return: A :class:`.Result` object. The current value of the counter may be obtained by inspecting the return value's `value` attribute. Simple increment:: rv = cb.counter("key") rv.value # 42 Increment by 10:: rv = cb.counter("key", delta=10) Decrement by 5:: rv = cb.counter("key", delta=-5) Increment by 20, set initial value to 5 if it does not exist:: rv = cb.counter("key", delta=20, initial=5) Increment three keys:: kv = cb.counter_multi(["foo", "bar", "baz"]) for key, result in kv.items(): print "Key %s has value %d now" % (key, result.value) .. seealso:: :meth:`counter_multi` """ return _Base.counter(self, key, delta=delta, initial=initial, ttl=ttl)
python
def counter(self, key, delta=1, initial=None, ttl=0): """Increment or decrement the numeric value of an item. This method instructs the server to treat the item stored under the given key as a numeric counter. Counter operations require that the stored value exists as a string representation of a number (e.g. ``123``). If storing items using the :meth:`upsert` family of methods, and using the default :const:`couchbase.FMT_JSON` then the value will conform to this constraint. :param string key: A key whose counter value is to be modified :param int delta: an amount by which the key should be modified. If the number is negative then this number will be *subtracted* from the current value. :param initial: The initial value for the key, if it does not exist. If the key does not exist, this value is used, and `delta` is ignored. If this parameter is `None` then no initial value is used :type initial: int or `None` :param int ttl: The lifetime for the key, after which it will expire :raise: :exc:`.NotFoundError` if the key does not exist on the bucket (and `initial` was `None`) :raise: :exc:`.DeltaBadvalError` if the key exists, but the existing value is not numeric :return: A :class:`.Result` object. The current value of the counter may be obtained by inspecting the return value's `value` attribute. Simple increment:: rv = cb.counter("key") rv.value # 42 Increment by 10:: rv = cb.counter("key", delta=10) Decrement by 5:: rv = cb.counter("key", delta=-5) Increment by 20, set initial value to 5 if it does not exist:: rv = cb.counter("key", delta=20, initial=5) Increment three keys:: kv = cb.counter_multi(["foo", "bar", "baz"]) for key, result in kv.items(): print "Key %s has value %d now" % (key, result.value) .. seealso:: :meth:`counter_multi` """ return _Base.counter(self, key, delta=delta, initial=initial, ttl=ttl)
[ "def", "counter", "(", "self", ",", "key", ",", "delta", "=", "1", ",", "initial", "=", "None", ",", "ttl", "=", "0", ")", ":", "return", "_Base", ".", "counter", "(", "self", ",", "key", ",", "delta", "=", "delta", ",", "initial", "=", "initial", ",", "ttl", "=", "ttl", ")" ]
Increment or decrement the numeric value of an item. This method instructs the server to treat the item stored under the given key as a numeric counter. Counter operations require that the stored value exists as a string representation of a number (e.g. ``123``). If storing items using the :meth:`upsert` family of methods, and using the default :const:`couchbase.FMT_JSON` then the value will conform to this constraint. :param string key: A key whose counter value is to be modified :param int delta: an amount by which the key should be modified. If the number is negative then this number will be *subtracted* from the current value. :param initial: The initial value for the key, if it does not exist. If the key does not exist, this value is used, and `delta` is ignored. If this parameter is `None` then no initial value is used :type initial: int or `None` :param int ttl: The lifetime for the key, after which it will expire :raise: :exc:`.NotFoundError` if the key does not exist on the bucket (and `initial` was `None`) :raise: :exc:`.DeltaBadvalError` if the key exists, but the existing value is not numeric :return: A :class:`.Result` object. The current value of the counter may be obtained by inspecting the return value's `value` attribute. Simple increment:: rv = cb.counter("key") rv.value # 42 Increment by 10:: rv = cb.counter("key", delta=10) Decrement by 5:: rv = cb.counter("key", delta=-5) Increment by 20, set initial value to 5 if it does not exist:: rv = cb.counter("key", delta=20, initial=5) Increment three keys:: kv = cb.counter_multi(["foo", "bar", "baz"]) for key, result in kv.items(): print "Key %s has value %d now" % (key, result.value) .. seealso:: :meth:`counter_multi`
[ "Increment", "or", "decrement", "the", "numeric", "value", "of", "an", "item", "." ]
a7bada167785bf79a29c39f820d932a433a6a535
https://github.com/couchbase/couchbase-python-client/blob/a7bada167785bf79a29c39f820d932a433a6a535/couchbase/bucket.py#L727-L784
16,691
couchbase/couchbase-python-client
couchbase/bucket.py
Bucket.mutate_in
def mutate_in(self, key, *specs, **kwargs): """Perform multiple atomic modifications within a document. :param key: The key of the document to modify :param specs: A list of specs (See :mod:`.couchbase.subdocument`) :param bool create_doc: Whether the document should be create if it doesn't exist :param bool insert_doc: If the document should be created anew, and the operations performed *only* if it does not exist. :param bool upsert_doc: If the document should be created anew if it does not exist. If it does exist the commands are still executed. :param kwargs: CAS, etc. :return: A :class:`~.couchbase.result.SubdocResult` object. Here's an example of adding a new tag to a "user" document and incrementing a modification counter:: import couchbase.subdocument as SD # .... cb.mutate_in('user', SD.array_addunique('tags', 'dog'), SD.counter('updates', 1)) .. note:: The `insert_doc` and `upsert_doc` options are mutually exclusive. Use `insert_doc` when you wish to create a new document with extended attributes (xattrs). .. seealso:: :mod:`.couchbase.subdocument` """ # Note we don't verify the validity of the options. lcb does that for # us. sdflags = kwargs.pop('_sd_doc_flags', 0) if kwargs.pop('insert_doc', False): sdflags |= _P.CMDSUBDOC_F_INSERT_DOC if kwargs.pop('upsert_doc', False): sdflags |= _P.CMDSUBDOC_F_UPSERT_DOC kwargs['_sd_doc_flags'] = sdflags return super(Bucket, self).mutate_in(key, specs, **kwargs)
python
def mutate_in(self, key, *specs, **kwargs): """Perform multiple atomic modifications within a document. :param key: The key of the document to modify :param specs: A list of specs (See :mod:`.couchbase.subdocument`) :param bool create_doc: Whether the document should be create if it doesn't exist :param bool insert_doc: If the document should be created anew, and the operations performed *only* if it does not exist. :param bool upsert_doc: If the document should be created anew if it does not exist. If it does exist the commands are still executed. :param kwargs: CAS, etc. :return: A :class:`~.couchbase.result.SubdocResult` object. Here's an example of adding a new tag to a "user" document and incrementing a modification counter:: import couchbase.subdocument as SD # .... cb.mutate_in('user', SD.array_addunique('tags', 'dog'), SD.counter('updates', 1)) .. note:: The `insert_doc` and `upsert_doc` options are mutually exclusive. Use `insert_doc` when you wish to create a new document with extended attributes (xattrs). .. seealso:: :mod:`.couchbase.subdocument` """ # Note we don't verify the validity of the options. lcb does that for # us. sdflags = kwargs.pop('_sd_doc_flags', 0) if kwargs.pop('insert_doc', False): sdflags |= _P.CMDSUBDOC_F_INSERT_DOC if kwargs.pop('upsert_doc', False): sdflags |= _P.CMDSUBDOC_F_UPSERT_DOC kwargs['_sd_doc_flags'] = sdflags return super(Bucket, self).mutate_in(key, specs, **kwargs)
[ "def", "mutate_in", "(", "self", ",", "key", ",", "*", "specs", ",", "*", "*", "kwargs", ")", ":", "# Note we don't verify the validity of the options. lcb does that for", "# us.", "sdflags", "=", "kwargs", ".", "pop", "(", "'_sd_doc_flags'", ",", "0", ")", "if", "kwargs", ".", "pop", "(", "'insert_doc'", ",", "False", ")", ":", "sdflags", "|=", "_P", ".", "CMDSUBDOC_F_INSERT_DOC", "if", "kwargs", ".", "pop", "(", "'upsert_doc'", ",", "False", ")", ":", "sdflags", "|=", "_P", ".", "CMDSUBDOC_F_UPSERT_DOC", "kwargs", "[", "'_sd_doc_flags'", "]", "=", "sdflags", "return", "super", "(", "Bucket", ",", "self", ")", ".", "mutate_in", "(", "key", ",", "specs", ",", "*", "*", "kwargs", ")" ]
Perform multiple atomic modifications within a document. :param key: The key of the document to modify :param specs: A list of specs (See :mod:`.couchbase.subdocument`) :param bool create_doc: Whether the document should be create if it doesn't exist :param bool insert_doc: If the document should be created anew, and the operations performed *only* if it does not exist. :param bool upsert_doc: If the document should be created anew if it does not exist. If it does exist the commands are still executed. :param kwargs: CAS, etc. :return: A :class:`~.couchbase.result.SubdocResult` object. Here's an example of adding a new tag to a "user" document and incrementing a modification counter:: import couchbase.subdocument as SD # .... cb.mutate_in('user', SD.array_addunique('tags', 'dog'), SD.counter('updates', 1)) .. note:: The `insert_doc` and `upsert_doc` options are mutually exclusive. Use `insert_doc` when you wish to create a new document with extended attributes (xattrs). .. seealso:: :mod:`.couchbase.subdocument`
[ "Perform", "multiple", "atomic", "modifications", "within", "a", "document", "." ]
a7bada167785bf79a29c39f820d932a433a6a535
https://github.com/couchbase/couchbase-python-client/blob/a7bada167785bf79a29c39f820d932a433a6a535/couchbase/bucket.py#L786-L828
16,692
couchbase/couchbase-python-client
couchbase/bucket.py
Bucket.lookup_in
def lookup_in(self, key, *specs, **kwargs): """Atomically retrieve one or more paths from a document. :param key: The key of the document to lookup :param spec: A list of specs (see :mod:`.couchbase.subdocument`) :return: A :class:`.couchbase.result.SubdocResult` object. This object contains the results and any errors of the operation. Example:: import couchbase.subdocument as SD rv = cb.lookup_in('user', SD.get('email'), SD.get('name'), SD.exists('friends.therock')) email = rv[0] name = rv[1] friend_exists = rv.exists(2) .. seealso:: :meth:`retrieve_in` which acts as a convenience wrapper """ return super(Bucket, self).lookup_in({key: specs}, **kwargs)
python
def lookup_in(self, key, *specs, **kwargs): """Atomically retrieve one or more paths from a document. :param key: The key of the document to lookup :param spec: A list of specs (see :mod:`.couchbase.subdocument`) :return: A :class:`.couchbase.result.SubdocResult` object. This object contains the results and any errors of the operation. Example:: import couchbase.subdocument as SD rv = cb.lookup_in('user', SD.get('email'), SD.get('name'), SD.exists('friends.therock')) email = rv[0] name = rv[1] friend_exists = rv.exists(2) .. seealso:: :meth:`retrieve_in` which acts as a convenience wrapper """ return super(Bucket, self).lookup_in({key: specs}, **kwargs)
[ "def", "lookup_in", "(", "self", ",", "key", ",", "*", "specs", ",", "*", "*", "kwargs", ")", ":", "return", "super", "(", "Bucket", ",", "self", ")", ".", "lookup_in", "(", "{", "key", ":", "specs", "}", ",", "*", "*", "kwargs", ")" ]
Atomically retrieve one or more paths from a document. :param key: The key of the document to lookup :param spec: A list of specs (see :mod:`.couchbase.subdocument`) :return: A :class:`.couchbase.result.SubdocResult` object. This object contains the results and any errors of the operation. Example:: import couchbase.subdocument as SD rv = cb.lookup_in('user', SD.get('email'), SD.get('name'), SD.exists('friends.therock')) email = rv[0] name = rv[1] friend_exists = rv.exists(2) .. seealso:: :meth:`retrieve_in` which acts as a convenience wrapper
[ "Atomically", "retrieve", "one", "or", "more", "paths", "from", "a", "document", "." ]
a7bada167785bf79a29c39f820d932a433a6a535
https://github.com/couchbase/couchbase-python-client/blob/a7bada167785bf79a29c39f820d932a433a6a535/couchbase/bucket.py#L830-L853
16,693
couchbase/couchbase-python-client
couchbase/bucket.py
Bucket.retrieve_in
def retrieve_in(self, key, *paths, **kwargs): """Atomically fetch one or more paths from a document. Convenience method for retrieval operations. This functions identically to :meth:`lookup_in`. As such, the following two forms are equivalent: .. code-block:: python import couchbase.subdocument as SD rv = cb.lookup_in(key, SD.get('email'), SD.get('name'), SD.get('friends.therock') email, name, friend = rv .. code-block:: python rv = cb.retrieve_in(key, 'email', 'name', 'friends.therock') email, name, friend = rv .. seealso:: :meth:`lookup_in` """ import couchbase.subdocument as SD return self.lookup_in(key, *tuple(SD.get(x) for x in paths), **kwargs)
python
def retrieve_in(self, key, *paths, **kwargs): """Atomically fetch one or more paths from a document. Convenience method for retrieval operations. This functions identically to :meth:`lookup_in`. As such, the following two forms are equivalent: .. code-block:: python import couchbase.subdocument as SD rv = cb.lookup_in(key, SD.get('email'), SD.get('name'), SD.get('friends.therock') email, name, friend = rv .. code-block:: python rv = cb.retrieve_in(key, 'email', 'name', 'friends.therock') email, name, friend = rv .. seealso:: :meth:`lookup_in` """ import couchbase.subdocument as SD return self.lookup_in(key, *tuple(SD.get(x) for x in paths), **kwargs)
[ "def", "retrieve_in", "(", "self", ",", "key", ",", "*", "paths", ",", "*", "*", "kwargs", ")", ":", "import", "couchbase", ".", "subdocument", "as", "SD", "return", "self", ".", "lookup_in", "(", "key", ",", "*", "tuple", "(", "SD", ".", "get", "(", "x", ")", "for", "x", "in", "paths", ")", ",", "*", "*", "kwargs", ")" ]
Atomically fetch one or more paths from a document. Convenience method for retrieval operations. This functions identically to :meth:`lookup_in`. As such, the following two forms are equivalent: .. code-block:: python import couchbase.subdocument as SD rv = cb.lookup_in(key, SD.get('email'), SD.get('name'), SD.get('friends.therock') email, name, friend = rv .. code-block:: python rv = cb.retrieve_in(key, 'email', 'name', 'friends.therock') email, name, friend = rv .. seealso:: :meth:`lookup_in`
[ "Atomically", "fetch", "one", "or", "more", "paths", "from", "a", "document", "." ]
a7bada167785bf79a29c39f820d932a433a6a535
https://github.com/couchbase/couchbase-python-client/blob/a7bada167785bf79a29c39f820d932a433a6a535/couchbase/bucket.py#L855-L880
16,694
couchbase/couchbase-python-client
couchbase/bucket.py
Bucket.stats
def stats(self, keys=None, keystats=False): """Request server statistics. Fetches stats from each node in the cluster. Without a key specified the server will respond with a default set of statistical information. It returns the a `dict` with stats keys and node-value pairs as a value. :param keys: One or several stats to query :type keys: string or list of string :raise: :exc:`.CouchbaseNetworkError` :return: `dict` where keys are stat keys and values are host-value pairs Find out how many items are in the bucket:: total = 0 for key, value in cb.stats()['total_items'].items(): total += value Get memory stats (works on couchbase buckets):: cb.stats('memory') # {'mem_used': {...}, ...} """ if keys and not isinstance(keys, (tuple, list)): keys = (keys,) return self._stats(keys, keystats=keystats)
python
def stats(self, keys=None, keystats=False): """Request server statistics. Fetches stats from each node in the cluster. Without a key specified the server will respond with a default set of statistical information. It returns the a `dict` with stats keys and node-value pairs as a value. :param keys: One or several stats to query :type keys: string or list of string :raise: :exc:`.CouchbaseNetworkError` :return: `dict` where keys are stat keys and values are host-value pairs Find out how many items are in the bucket:: total = 0 for key, value in cb.stats()['total_items'].items(): total += value Get memory stats (works on couchbase buckets):: cb.stats('memory') # {'mem_used': {...}, ...} """ if keys and not isinstance(keys, (tuple, list)): keys = (keys,) return self._stats(keys, keystats=keystats)
[ "def", "stats", "(", "self", ",", "keys", "=", "None", ",", "keystats", "=", "False", ")", ":", "if", "keys", "and", "not", "isinstance", "(", "keys", ",", "(", "tuple", ",", "list", ")", ")", ":", "keys", "=", "(", "keys", ",", ")", "return", "self", ".", "_stats", "(", "keys", ",", "keystats", "=", "keystats", ")" ]
Request server statistics. Fetches stats from each node in the cluster. Without a key specified the server will respond with a default set of statistical information. It returns the a `dict` with stats keys and node-value pairs as a value. :param keys: One or several stats to query :type keys: string or list of string :raise: :exc:`.CouchbaseNetworkError` :return: `dict` where keys are stat keys and values are host-value pairs Find out how many items are in the bucket:: total = 0 for key, value in cb.stats()['total_items'].items(): total += value Get memory stats (works on couchbase buckets):: cb.stats('memory') # {'mem_used': {...}, ...}
[ "Request", "server", "statistics", "." ]
a7bada167785bf79a29c39f820d932a433a6a535
https://github.com/couchbase/couchbase-python-client/blob/a7bada167785bf79a29c39f820d932a433a6a535/couchbase/bucket.py#L898-L925
16,695
couchbase/couchbase-python-client
couchbase/bucket.py
Bucket.observe
def observe(self, key, master_only=False): """Return storage information for a key. It returns a :class:`.ValueResult` object with the ``value`` field set to a list of :class:`~.ObserveInfo` objects. Each element in the list responds to the storage status for the key on the given node. The length of the list (and thus the number of :class:`~.ObserveInfo` objects) are equal to the number of online replicas plus the master for the given key. :param string key: The key to inspect :param bool master_only: Whether to only retrieve information from the master node. .. seealso:: :ref:`observe_info` """ return _Base.observe(self, key, master_only=master_only)
python
def observe(self, key, master_only=False): """Return storage information for a key. It returns a :class:`.ValueResult` object with the ``value`` field set to a list of :class:`~.ObserveInfo` objects. Each element in the list responds to the storage status for the key on the given node. The length of the list (and thus the number of :class:`~.ObserveInfo` objects) are equal to the number of online replicas plus the master for the given key. :param string key: The key to inspect :param bool master_only: Whether to only retrieve information from the master node. .. seealso:: :ref:`observe_info` """ return _Base.observe(self, key, master_only=master_only)
[ "def", "observe", "(", "self", ",", "key", ",", "master_only", "=", "False", ")", ":", "return", "_Base", ".", "observe", "(", "self", ",", "key", ",", "master_only", "=", "master_only", ")" ]
Return storage information for a key. It returns a :class:`.ValueResult` object with the ``value`` field set to a list of :class:`~.ObserveInfo` objects. Each element in the list responds to the storage status for the key on the given node. The length of the list (and thus the number of :class:`~.ObserveInfo` objects) are equal to the number of online replicas plus the master for the given key. :param string key: The key to inspect :param bool master_only: Whether to only retrieve information from the master node. .. seealso:: :ref:`observe_info`
[ "Return", "storage", "information", "for", "a", "key", "." ]
a7bada167785bf79a29c39f820d932a433a6a535
https://github.com/couchbase/couchbase-python-client/blob/a7bada167785bf79a29c39f820d932a433a6a535/couchbase/bucket.py#L977-L993
16,696
couchbase/couchbase-python-client
couchbase/bucket.py
Bucket.endure
def endure(self, key, persist_to=-1, replicate_to=-1, cas=0, check_removed=False, timeout=5.0, interval=0.010): """Wait until a key has been distributed to one or more nodes By default, when items are stored to Couchbase, the operation is considered successful if the vBucket master (i.e. the "primary" node) for the key has successfully stored the item in its memory. In most situations, this is sufficient to assume that the item has successfully been stored. However the possibility remains that the "master" server will go offline as soon as it sends back the successful response and the data is lost. The ``endure`` function allows you to provide stricter criteria for success. The criteria may be expressed in terms of number of nodes for which the item must exist in that node's RAM and/or on that node's disk. Ensuring that an item exists in more than one place is a safer way to guarantee against possible data loss. We call these requirements `Durability Constraints`, and thus the method is called `endure`. :param string key: The key to endure. :param int persist_to: The minimum number of nodes which must contain this item on their disk before this function returns. Ensure that you do not specify too many nodes; otherwise this function will fail. Use the :attr:`server_nodes` to determine how many nodes exist in the cluster. The maximum number of nodes an item can reside on is currently fixed to 4 (i.e. the "master" node, and up to three "replica" nodes). This limitation is current as of Couchbase Server version 2.1.0. If this parameter is set to a negative value, the maximum number of possible nodes the key can reside on will be used. :param int replicate_to: The minimum number of replicas which must contain this item in their memory for this method to succeed. As with ``persist_to``, you may specify a negative value in which case the requirement will be set to the maximum number possible. :param float timeout: A timeout value in seconds before this function fails with an exception. Typically it should take no longer than several milliseconds on a functioning cluster for durability requirements to be satisfied (unless something has gone wrong). :param float interval: The polling interval in seconds to use for checking the key status on the respective nodes. Internally, ``endure`` is implemented by polling each server individually to see if the key exists on that server's disk and memory. Once the status request is sent to all servers, the client will check if their replies are satisfactory; if they are then this function succeeds, otherwise the client will wait a short amount of time and try again. This parameter sets this "wait time". :param bool check_removed: This flag inverts the check. Instead of checking that a given key *exists* on the nodes, this changes the behavior to check that the key is *removed* from the nodes. :param long cas: The CAS value to check against. It is possible for an item to exist on a node but have a CAS value from a prior operation. Passing the CAS ensures that only replies from servers with a CAS matching this parameter are accepted. :return: A :class:`~.OperationResult` :raise: see :meth:`upsert` and :meth:`get` for possible errors .. seealso:: :meth:`upsert`, :meth:`endure_multi` """ # We really just wrap 'endure_multi' kv = {key: cas} rvs = self.endure_multi(keys=kv, persist_to=persist_to, replicate_to=replicate_to, check_removed=check_removed, timeout=timeout, interval=interval) return rvs[key]
python
def endure(self, key, persist_to=-1, replicate_to=-1, cas=0, check_removed=False, timeout=5.0, interval=0.010): """Wait until a key has been distributed to one or more nodes By default, when items are stored to Couchbase, the operation is considered successful if the vBucket master (i.e. the "primary" node) for the key has successfully stored the item in its memory. In most situations, this is sufficient to assume that the item has successfully been stored. However the possibility remains that the "master" server will go offline as soon as it sends back the successful response and the data is lost. The ``endure`` function allows you to provide stricter criteria for success. The criteria may be expressed in terms of number of nodes for which the item must exist in that node's RAM and/or on that node's disk. Ensuring that an item exists in more than one place is a safer way to guarantee against possible data loss. We call these requirements `Durability Constraints`, and thus the method is called `endure`. :param string key: The key to endure. :param int persist_to: The minimum number of nodes which must contain this item on their disk before this function returns. Ensure that you do not specify too many nodes; otherwise this function will fail. Use the :attr:`server_nodes` to determine how many nodes exist in the cluster. The maximum number of nodes an item can reside on is currently fixed to 4 (i.e. the "master" node, and up to three "replica" nodes). This limitation is current as of Couchbase Server version 2.1.0. If this parameter is set to a negative value, the maximum number of possible nodes the key can reside on will be used. :param int replicate_to: The minimum number of replicas which must contain this item in their memory for this method to succeed. As with ``persist_to``, you may specify a negative value in which case the requirement will be set to the maximum number possible. :param float timeout: A timeout value in seconds before this function fails with an exception. Typically it should take no longer than several milliseconds on a functioning cluster for durability requirements to be satisfied (unless something has gone wrong). :param float interval: The polling interval in seconds to use for checking the key status on the respective nodes. Internally, ``endure`` is implemented by polling each server individually to see if the key exists on that server's disk and memory. Once the status request is sent to all servers, the client will check if their replies are satisfactory; if they are then this function succeeds, otherwise the client will wait a short amount of time and try again. This parameter sets this "wait time". :param bool check_removed: This flag inverts the check. Instead of checking that a given key *exists* on the nodes, this changes the behavior to check that the key is *removed* from the nodes. :param long cas: The CAS value to check against. It is possible for an item to exist on a node but have a CAS value from a prior operation. Passing the CAS ensures that only replies from servers with a CAS matching this parameter are accepted. :return: A :class:`~.OperationResult` :raise: see :meth:`upsert` and :meth:`get` for possible errors .. seealso:: :meth:`upsert`, :meth:`endure_multi` """ # We really just wrap 'endure_multi' kv = {key: cas} rvs = self.endure_multi(keys=kv, persist_to=persist_to, replicate_to=replicate_to, check_removed=check_removed, timeout=timeout, interval=interval) return rvs[key]
[ "def", "endure", "(", "self", ",", "key", ",", "persist_to", "=", "-", "1", ",", "replicate_to", "=", "-", "1", ",", "cas", "=", "0", ",", "check_removed", "=", "False", ",", "timeout", "=", "5.0", ",", "interval", "=", "0.010", ")", ":", "# We really just wrap 'endure_multi'", "kv", "=", "{", "key", ":", "cas", "}", "rvs", "=", "self", ".", "endure_multi", "(", "keys", "=", "kv", ",", "persist_to", "=", "persist_to", ",", "replicate_to", "=", "replicate_to", ",", "check_removed", "=", "check_removed", ",", "timeout", "=", "timeout", ",", "interval", "=", "interval", ")", "return", "rvs", "[", "key", "]" ]
Wait until a key has been distributed to one or more nodes By default, when items are stored to Couchbase, the operation is considered successful if the vBucket master (i.e. the "primary" node) for the key has successfully stored the item in its memory. In most situations, this is sufficient to assume that the item has successfully been stored. However the possibility remains that the "master" server will go offline as soon as it sends back the successful response and the data is lost. The ``endure`` function allows you to provide stricter criteria for success. The criteria may be expressed in terms of number of nodes for which the item must exist in that node's RAM and/or on that node's disk. Ensuring that an item exists in more than one place is a safer way to guarantee against possible data loss. We call these requirements `Durability Constraints`, and thus the method is called `endure`. :param string key: The key to endure. :param int persist_to: The minimum number of nodes which must contain this item on their disk before this function returns. Ensure that you do not specify too many nodes; otherwise this function will fail. Use the :attr:`server_nodes` to determine how many nodes exist in the cluster. The maximum number of nodes an item can reside on is currently fixed to 4 (i.e. the "master" node, and up to three "replica" nodes). This limitation is current as of Couchbase Server version 2.1.0. If this parameter is set to a negative value, the maximum number of possible nodes the key can reside on will be used. :param int replicate_to: The minimum number of replicas which must contain this item in their memory for this method to succeed. As with ``persist_to``, you may specify a negative value in which case the requirement will be set to the maximum number possible. :param float timeout: A timeout value in seconds before this function fails with an exception. Typically it should take no longer than several milliseconds on a functioning cluster for durability requirements to be satisfied (unless something has gone wrong). :param float interval: The polling interval in seconds to use for checking the key status on the respective nodes. Internally, ``endure`` is implemented by polling each server individually to see if the key exists on that server's disk and memory. Once the status request is sent to all servers, the client will check if their replies are satisfactory; if they are then this function succeeds, otherwise the client will wait a short amount of time and try again. This parameter sets this "wait time". :param bool check_removed: This flag inverts the check. Instead of checking that a given key *exists* on the nodes, this changes the behavior to check that the key is *removed* from the nodes. :param long cas: The CAS value to check against. It is possible for an item to exist on a node but have a CAS value from a prior operation. Passing the CAS ensures that only replies from servers with a CAS matching this parameter are accepted. :return: A :class:`~.OperationResult` :raise: see :meth:`upsert` and :meth:`get` for possible errors .. seealso:: :meth:`upsert`, :meth:`endure_multi`
[ "Wait", "until", "a", "key", "has", "been", "distributed", "to", "one", "or", "more", "nodes" ]
a7bada167785bf79a29c39f820d932a433a6a535
https://github.com/couchbase/couchbase-python-client/blob/a7bada167785bf79a29c39f820d932a433a6a535/couchbase/bucket.py#L995-L1077
16,697
couchbase/couchbase-python-client
couchbase/bucket.py
Bucket.endure_multi
def endure_multi(self, keys, persist_to=-1, replicate_to=-1, timeout=5.0, interval=0.010, check_removed=False): """Check durability requirements for multiple keys :param keys: The keys to check The type of keys may be one of the following: * Sequence of keys * A :class:`~couchbase.result.MultiResult` object * A ``dict`` with CAS values as the dictionary value * A sequence of :class:`~couchbase.result.Result` objects :return: A :class:`~.MultiResult` object of :class:`~.OperationResult` items. .. seealso:: :meth:`endure` """ return _Base.endure_multi(self, keys, persist_to=persist_to, replicate_to=replicate_to, timeout=timeout, interval=interval, check_removed=check_removed)
python
def endure_multi(self, keys, persist_to=-1, replicate_to=-1, timeout=5.0, interval=0.010, check_removed=False): """Check durability requirements for multiple keys :param keys: The keys to check The type of keys may be one of the following: * Sequence of keys * A :class:`~couchbase.result.MultiResult` object * A ``dict`` with CAS values as the dictionary value * A sequence of :class:`~couchbase.result.Result` objects :return: A :class:`~.MultiResult` object of :class:`~.OperationResult` items. .. seealso:: :meth:`endure` """ return _Base.endure_multi(self, keys, persist_to=persist_to, replicate_to=replicate_to, timeout=timeout, interval=interval, check_removed=check_removed)
[ "def", "endure_multi", "(", "self", ",", "keys", ",", "persist_to", "=", "-", "1", ",", "replicate_to", "=", "-", "1", ",", "timeout", "=", "5.0", ",", "interval", "=", "0.010", ",", "check_removed", "=", "False", ")", ":", "return", "_Base", ".", "endure_multi", "(", "self", ",", "keys", ",", "persist_to", "=", "persist_to", ",", "replicate_to", "=", "replicate_to", ",", "timeout", "=", "timeout", ",", "interval", "=", "interval", ",", "check_removed", "=", "check_removed", ")" ]
Check durability requirements for multiple keys :param keys: The keys to check The type of keys may be one of the following: * Sequence of keys * A :class:`~couchbase.result.MultiResult` object * A ``dict`` with CAS values as the dictionary value * A sequence of :class:`~couchbase.result.Result` objects :return: A :class:`~.MultiResult` object of :class:`~.OperationResult` items. .. seealso:: :meth:`endure`
[ "Check", "durability", "requirements", "for", "multiple", "keys" ]
a7bada167785bf79a29c39f820d932a433a6a535
https://github.com/couchbase/couchbase-python-client/blob/a7bada167785bf79a29c39f820d932a433a6a535/couchbase/bucket.py#L1274-L1294
16,698
couchbase/couchbase-python-client
couchbase/bucket.py
Bucket.remove_multi
def remove_multi(self, kvs, quiet=None): """Remove multiple items from the cluster :param kvs: Iterable of keys to delete from the cluster. If you wish to specify a CAS for each item, then you may pass a dictionary of keys mapping to cas, like `remove_multi({k1:cas1, k2:cas2}`) :param quiet: Whether an exception should be raised if one or more items were not found :return: A :class:`~.MultiResult` containing :class:`~.OperationResult` values. """ return _Base.remove_multi(self, kvs, quiet=quiet)
python
def remove_multi(self, kvs, quiet=None): """Remove multiple items from the cluster :param kvs: Iterable of keys to delete from the cluster. If you wish to specify a CAS for each item, then you may pass a dictionary of keys mapping to cas, like `remove_multi({k1:cas1, k2:cas2}`) :param quiet: Whether an exception should be raised if one or more items were not found :return: A :class:`~.MultiResult` containing :class:`~.OperationResult` values. """ return _Base.remove_multi(self, kvs, quiet=quiet)
[ "def", "remove_multi", "(", "self", ",", "kvs", ",", "quiet", "=", "None", ")", ":", "return", "_Base", ".", "remove_multi", "(", "self", ",", "kvs", ",", "quiet", "=", "quiet", ")" ]
Remove multiple items from the cluster :param kvs: Iterable of keys to delete from the cluster. If you wish to specify a CAS for each item, then you may pass a dictionary of keys mapping to cas, like `remove_multi({k1:cas1, k2:cas2}`) :param quiet: Whether an exception should be raised if one or more items were not found :return: A :class:`~.MultiResult` containing :class:`~.OperationResult` values.
[ "Remove", "multiple", "items", "from", "the", "cluster" ]
a7bada167785bf79a29c39f820d932a433a6a535
https://github.com/couchbase/couchbase-python-client/blob/a7bada167785bf79a29c39f820d932a433a6a535/couchbase/bucket.py#L1296-L1307
16,699
couchbase/couchbase-python-client
couchbase/bucket.py
Bucket.counter_multi
def counter_multi(self, kvs, initial=None, delta=1, ttl=0): """Perform counter operations on multiple items :param kvs: Keys to operate on. See below for more options :param initial: Initial value to use for all keys. :param delta: Delta value for all keys. :param ttl: Expiration value to use for all keys :return: A :class:`~.MultiResult` containing :class:`~.ValueResult` values The `kvs` can be a: - Iterable of keys .. code-block:: python cb.counter_multi((k1, k2)) - A dictionary mapping a key to its delta .. code-block:: python cb.counter_multi({ k1: 42, k2: 99 }) - A dictionary mapping a key to its additional options .. code-block:: python cb.counter_multi({ k1: {'delta': 42, 'initial': 9, 'ttl': 300}, k2: {'delta': 99, 'initial': 4, 'ttl': 700} }) When using a dictionary, you can override settings for each key on a per-key basis (for example, the initial value). Global settings (global here means something passed as a parameter to the method) will take effect for those values which do not have a given option specified. """ return _Base.counter_multi(self, kvs, initial=initial, delta=delta, ttl=ttl)
python
def counter_multi(self, kvs, initial=None, delta=1, ttl=0): """Perform counter operations on multiple items :param kvs: Keys to operate on. See below for more options :param initial: Initial value to use for all keys. :param delta: Delta value for all keys. :param ttl: Expiration value to use for all keys :return: A :class:`~.MultiResult` containing :class:`~.ValueResult` values The `kvs` can be a: - Iterable of keys .. code-block:: python cb.counter_multi((k1, k2)) - A dictionary mapping a key to its delta .. code-block:: python cb.counter_multi({ k1: 42, k2: 99 }) - A dictionary mapping a key to its additional options .. code-block:: python cb.counter_multi({ k1: {'delta': 42, 'initial': 9, 'ttl': 300}, k2: {'delta': 99, 'initial': 4, 'ttl': 700} }) When using a dictionary, you can override settings for each key on a per-key basis (for example, the initial value). Global settings (global here means something passed as a parameter to the method) will take effect for those values which do not have a given option specified. """ return _Base.counter_multi(self, kvs, initial=initial, delta=delta, ttl=ttl)
[ "def", "counter_multi", "(", "self", ",", "kvs", ",", "initial", "=", "None", ",", "delta", "=", "1", ",", "ttl", "=", "0", ")", ":", "return", "_Base", ".", "counter_multi", "(", "self", ",", "kvs", ",", "initial", "=", "initial", ",", "delta", "=", "delta", ",", "ttl", "=", "ttl", ")" ]
Perform counter operations on multiple items :param kvs: Keys to operate on. See below for more options :param initial: Initial value to use for all keys. :param delta: Delta value for all keys. :param ttl: Expiration value to use for all keys :return: A :class:`~.MultiResult` containing :class:`~.ValueResult` values The `kvs` can be a: - Iterable of keys .. code-block:: python cb.counter_multi((k1, k2)) - A dictionary mapping a key to its delta .. code-block:: python cb.counter_multi({ k1: 42, k2: 99 }) - A dictionary mapping a key to its additional options .. code-block:: python cb.counter_multi({ k1: {'delta': 42, 'initial': 9, 'ttl': 300}, k2: {'delta': 99, 'initial': 4, 'ttl': 700} }) When using a dictionary, you can override settings for each key on a per-key basis (for example, the initial value). Global settings (global here means something passed as a parameter to the method) will take effect for those values which do not have a given option specified.
[ "Perform", "counter", "operations", "on", "multiple", "items" ]
a7bada167785bf79a29c39f820d932a433a6a535
https://github.com/couchbase/couchbase-python-client/blob/a7bada167785bf79a29c39f820d932a433a6a535/couchbase/bucket.py#L1309-L1352