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
51
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
234,300
abseil/abseil-py
absl/flags/_helpers.py
get_help_width
def get_help_width(): """Returns the integer width of help lines that is used in TextWrap.""" if not sys.stdout.isatty() or termios is None or fcntl is None: return _DEFAULT_HELP_WIDTH try: data = fcntl.ioctl(sys.stdout, termios.TIOCGWINSZ, '1234') columns = struct.unpack('hh', data)[1] # Emacs mode returns 0. # Here we assume that any value below 40 is unreasonable. if columns >= _MIN_HELP_WIDTH: return columns # Returning an int as default is fine, int(int) just return the int. return int(os.getenv('COLUMNS', _DEFAULT_HELP_WIDTH)) except (TypeError, IOError, struct.error): return _DEFAULT_HELP_WIDTH
python
def get_help_width(): if not sys.stdout.isatty() or termios is None or fcntl is None: return _DEFAULT_HELP_WIDTH try: data = fcntl.ioctl(sys.stdout, termios.TIOCGWINSZ, '1234') columns = struct.unpack('hh', data)[1] # Emacs mode returns 0. # Here we assume that any value below 40 is unreasonable. if columns >= _MIN_HELP_WIDTH: return columns # Returning an int as default is fine, int(int) just return the int. return int(os.getenv('COLUMNS', _DEFAULT_HELP_WIDTH)) except (TypeError, IOError, struct.error): return _DEFAULT_HELP_WIDTH
[ "def", "get_help_width", "(", ")", ":", "if", "not", "sys", ".", "stdout", ".", "isatty", "(", ")", "or", "termios", "is", "None", "or", "fcntl", "is", "None", ":", "return", "_DEFAULT_HELP_WIDTH", "try", ":", "data", "=", "fcntl", ".", "ioctl", "(", ...
Returns the integer width of help lines that is used in TextWrap.
[ "Returns", "the", "integer", "width", "of", "help", "lines", "that", "is", "used", "in", "TextWrap", "." ]
9d73fdaa23a6b6726aa5731390f388c0c6250ee5
https://github.com/abseil/abseil-py/blob/9d73fdaa23a6b6726aa5731390f388c0c6250ee5/absl/flags/_helpers.py#L189-L204
234,301
abseil/abseil-py
absl/flags/_helpers.py
get_flag_suggestions
def get_flag_suggestions(attempt, longopt_list): """Returns helpful similar matches for an invalid flag.""" # Don't suggest on very short strings, or if no longopts are specified. if len(attempt) <= 2 or not longopt_list: return [] option_names = [v.split('=')[0] for v in longopt_list] # Find close approximations in flag prefixes. # This also handles the case where the flag is spelled right but ambiguous. distances = [(_damerau_levenshtein(attempt, option[0:len(attempt)]), option) for option in option_names] # t[0] is distance, and sorting by t[1] allows us to have stable output. distances.sort() least_errors, _ = distances[0] # Don't suggest excessively bad matches. if least_errors >= _SUGGESTION_ERROR_RATE_THRESHOLD * len(attempt): return [] suggestions = [] for errors, name in distances: if errors == least_errors: suggestions.append(name) else: break return suggestions
python
def get_flag_suggestions(attempt, longopt_list): # Don't suggest on very short strings, or if no longopts are specified. if len(attempt) <= 2 or not longopt_list: return [] option_names = [v.split('=')[0] for v in longopt_list] # Find close approximations in flag prefixes. # This also handles the case where the flag is spelled right but ambiguous. distances = [(_damerau_levenshtein(attempt, option[0:len(attempt)]), option) for option in option_names] # t[0] is distance, and sorting by t[1] allows us to have stable output. distances.sort() least_errors, _ = distances[0] # Don't suggest excessively bad matches. if least_errors >= _SUGGESTION_ERROR_RATE_THRESHOLD * len(attempt): return [] suggestions = [] for errors, name in distances: if errors == least_errors: suggestions.append(name) else: break return suggestions
[ "def", "get_flag_suggestions", "(", "attempt", ",", "longopt_list", ")", ":", "# Don't suggest on very short strings, or if no longopts are specified.", "if", "len", "(", "attempt", ")", "<=", "2", "or", "not", "longopt_list", ":", "return", "[", "]", "option_names", ...
Returns helpful similar matches for an invalid flag.
[ "Returns", "helpful", "similar", "matches", "for", "an", "invalid", "flag", "." ]
9d73fdaa23a6b6726aa5731390f388c0c6250ee5
https://github.com/abseil/abseil-py/blob/9d73fdaa23a6b6726aa5731390f388c0c6250ee5/absl/flags/_helpers.py#L207-L233
234,302
abseil/abseil-py
absl/flags/_helpers.py
_damerau_levenshtein
def _damerau_levenshtein(a, b): """Returns Damerau-Levenshtein edit distance from a to b.""" memo = {} def distance(x, y): """Recursively defined string distance with memoization.""" if (x, y) in memo: return memo[x, y] if not x: d = len(y) elif not y: d = len(x) else: d = min( distance(x[1:], y) + 1, # correct an insertion error distance(x, y[1:]) + 1, # correct a deletion error distance(x[1:], y[1:]) + (x[0] != y[0])) # correct a wrong character if len(x) >= 2 and len(y) >= 2 and x[0] == y[1] and x[1] == y[0]: # Correct a transposition. t = distance(x[2:], y[2:]) + 1 if d > t: d = t memo[x, y] = d return d return distance(a, b)
python
def _damerau_levenshtein(a, b): memo = {} def distance(x, y): """Recursively defined string distance with memoization.""" if (x, y) in memo: return memo[x, y] if not x: d = len(y) elif not y: d = len(x) else: d = min( distance(x[1:], y) + 1, # correct an insertion error distance(x, y[1:]) + 1, # correct a deletion error distance(x[1:], y[1:]) + (x[0] != y[0])) # correct a wrong character if len(x) >= 2 and len(y) >= 2 and x[0] == y[1] and x[1] == y[0]: # Correct a transposition. t = distance(x[2:], y[2:]) + 1 if d > t: d = t memo[x, y] = d return d return distance(a, b)
[ "def", "_damerau_levenshtein", "(", "a", ",", "b", ")", ":", "memo", "=", "{", "}", "def", "distance", "(", "x", ",", "y", ")", ":", "\"\"\"Recursively defined string distance with memoization.\"\"\"", "if", "(", "x", ",", "y", ")", "in", "memo", ":", "ret...
Returns Damerau-Levenshtein edit distance from a to b.
[ "Returns", "Damerau", "-", "Levenshtein", "edit", "distance", "from", "a", "to", "b", "." ]
9d73fdaa23a6b6726aa5731390f388c0c6250ee5
https://github.com/abseil/abseil-py/blob/9d73fdaa23a6b6726aa5731390f388c0c6250ee5/absl/flags/_helpers.py#L236-L261
234,303
abseil/abseil-py
absl/flags/_helpers.py
text_wrap
def text_wrap(text, length=None, indent='', firstline_indent=None): """Wraps a given text to a maximum line length and returns it. It turns lines that only contain whitespace into empty lines, keeps new lines, and expands tabs using 4 spaces. Args: text: str, text to wrap. length: int, maximum length of a line, includes indentation. If this is None then use get_help_width() indent: str, indent for all but first line. firstline_indent: str, indent for first line; if None, fall back to indent. Returns: str, the wrapped text. Raises: ValueError: Raised if indent or firstline_indent not shorter than length. """ # Get defaults where callee used None if length is None: length = get_help_width() if indent is None: indent = '' if firstline_indent is None: firstline_indent = indent if len(indent) >= length: raise ValueError('Length of indent exceeds length') if len(firstline_indent) >= length: raise ValueError('Length of first line indent exceeds length') text = text.expandtabs(4) result = [] # Create one wrapper for the first paragraph and one for subsequent # paragraphs that does not have the initial wrapping. wrapper = textwrap.TextWrapper( width=length, initial_indent=firstline_indent, subsequent_indent=indent) subsequent_wrapper = textwrap.TextWrapper( width=length, initial_indent=indent, subsequent_indent=indent) # textwrap does not have any special treatment for newlines. From the docs: # "...newlines may appear in the middle of a line and cause strange output. # For this reason, text should be split into paragraphs (using # str.splitlines() or similar) which are wrapped separately." for paragraph in (p.strip() for p in text.splitlines()): if paragraph: result.extend(wrapper.wrap(paragraph)) else: result.append('') # Keep empty lines. # Replace initial wrapper with wrapper for subsequent paragraphs. wrapper = subsequent_wrapper return '\n'.join(result)
python
def text_wrap(text, length=None, indent='', firstline_indent=None): # Get defaults where callee used None if length is None: length = get_help_width() if indent is None: indent = '' if firstline_indent is None: firstline_indent = indent if len(indent) >= length: raise ValueError('Length of indent exceeds length') if len(firstline_indent) >= length: raise ValueError('Length of first line indent exceeds length') text = text.expandtabs(4) result = [] # Create one wrapper for the first paragraph and one for subsequent # paragraphs that does not have the initial wrapping. wrapper = textwrap.TextWrapper( width=length, initial_indent=firstline_indent, subsequent_indent=indent) subsequent_wrapper = textwrap.TextWrapper( width=length, initial_indent=indent, subsequent_indent=indent) # textwrap does not have any special treatment for newlines. From the docs: # "...newlines may appear in the middle of a line and cause strange output. # For this reason, text should be split into paragraphs (using # str.splitlines() or similar) which are wrapped separately." for paragraph in (p.strip() for p in text.splitlines()): if paragraph: result.extend(wrapper.wrap(paragraph)) else: result.append('') # Keep empty lines. # Replace initial wrapper with wrapper for subsequent paragraphs. wrapper = subsequent_wrapper return '\n'.join(result)
[ "def", "text_wrap", "(", "text", ",", "length", "=", "None", ",", "indent", "=", "''", ",", "firstline_indent", "=", "None", ")", ":", "# Get defaults where callee used None", "if", "length", "is", "None", ":", "length", "=", "get_help_width", "(", ")", "if"...
Wraps a given text to a maximum line length and returns it. It turns lines that only contain whitespace into empty lines, keeps new lines, and expands tabs using 4 spaces. Args: text: str, text to wrap. length: int, maximum length of a line, includes indentation. If this is None then use get_help_width() indent: str, indent for all but first line. firstline_indent: str, indent for first line; if None, fall back to indent. Returns: str, the wrapped text. Raises: ValueError: Raised if indent or firstline_indent not shorter than length.
[ "Wraps", "a", "given", "text", "to", "a", "maximum", "line", "length", "and", "returns", "it", "." ]
9d73fdaa23a6b6726aa5731390f388c0c6250ee5
https://github.com/abseil/abseil-py/blob/9d73fdaa23a6b6726aa5731390f388c0c6250ee5/absl/flags/_helpers.py#L264-L318
234,304
abseil/abseil-py
absl/flags/_helpers.py
trim_docstring
def trim_docstring(docstring): """Removes indentation from triple-quoted strings. This is the function specified in PEP 257 to handle docstrings: https://www.python.org/dev/peps/pep-0257/. Args: docstring: str, a python docstring. Returns: str, docstring with indentation removed. """ if not docstring: return '' # If you've got a line longer than this you have other problems... max_indent = 1 << 29 # Convert tabs to spaces (following the normal Python rules) # and split into a list of lines: lines = docstring.expandtabs().splitlines() # Determine minimum indentation (first line doesn't count): indent = max_indent for line in lines[1:]: stripped = line.lstrip() if stripped: indent = min(indent, len(line) - len(stripped)) # Remove indentation (first line is special): trimmed = [lines[0].strip()] if indent < max_indent: for line in lines[1:]: trimmed.append(line[indent:].rstrip()) # Strip off trailing and leading blank lines: while trimmed and not trimmed[-1]: trimmed.pop() while trimmed and not trimmed[0]: trimmed.pop(0) # Return a single string: return '\n'.join(trimmed)
python
def trim_docstring(docstring): if not docstring: return '' # If you've got a line longer than this you have other problems... max_indent = 1 << 29 # Convert tabs to spaces (following the normal Python rules) # and split into a list of lines: lines = docstring.expandtabs().splitlines() # Determine minimum indentation (first line doesn't count): indent = max_indent for line in lines[1:]: stripped = line.lstrip() if stripped: indent = min(indent, len(line) - len(stripped)) # Remove indentation (first line is special): trimmed = [lines[0].strip()] if indent < max_indent: for line in lines[1:]: trimmed.append(line[indent:].rstrip()) # Strip off trailing and leading blank lines: while trimmed and not trimmed[-1]: trimmed.pop() while trimmed and not trimmed[0]: trimmed.pop(0) # Return a single string: return '\n'.join(trimmed)
[ "def", "trim_docstring", "(", "docstring", ")", ":", "if", "not", "docstring", ":", "return", "''", "# If you've got a line longer than this you have other problems...", "max_indent", "=", "1", "<<", "29", "# Convert tabs to spaces (following the normal Python rules)", "# and s...
Removes indentation from triple-quoted strings. This is the function specified in PEP 257 to handle docstrings: https://www.python.org/dev/peps/pep-0257/. Args: docstring: str, a python docstring. Returns: str, docstring with indentation removed.
[ "Removes", "indentation", "from", "triple", "-", "quoted", "strings", "." ]
9d73fdaa23a6b6726aa5731390f388c0c6250ee5
https://github.com/abseil/abseil-py/blob/9d73fdaa23a6b6726aa5731390f388c0c6250ee5/absl/flags/_helpers.py#L359-L398
234,305
alexa/alexa-skills-kit-sdk-for-python
ask-sdk-core/ask_sdk_core/skill.py
CustomSkill.invoke
def invoke(self, request_envelope, context): # type: (RequestEnvelope, Any) -> ResponseEnvelope """Invokes the dispatcher, to handle the request envelope and return a response envelope. :param request_envelope: Request Envelope instance containing request information :type request_envelope: RequestEnvelope :param context: Context passed during invocation :type context: Any :return: Response Envelope generated by handling the request :rtype: ResponseEnvelope """ if (self.skill_id is not None and request_envelope.context.system.application.application_id != self.skill_id): raise AskSdkException("Skill ID Verification failed!!") if self.api_client is not None: api_token = request_envelope.context.system.api_access_token api_endpoint = request_envelope.context.system.api_endpoint api_configuration = ApiConfiguration( serializer=self.serializer, api_client=self.api_client, authorization_value=api_token, api_endpoint=api_endpoint) factory = ServiceClientFactory(api_configuration=api_configuration) else: factory = None attributes_manager = AttributesManager( request_envelope=request_envelope, persistence_adapter=self.persistence_adapter) handler_input = HandlerInput( request_envelope=request_envelope, attributes_manager=attributes_manager, context=context, service_client_factory=factory) response = self.request_dispatcher.dispatch( handler_input=handler_input) session_attributes = None if request_envelope.session is not None: session_attributes = ( handler_input.attributes_manager.session_attributes) return ResponseEnvelope( response=response, version=RESPONSE_FORMAT_VERSION, session_attributes=session_attributes, user_agent=user_agent_info( sdk_version=__version__, custom_user_agent=self.custom_user_agent))
python
def invoke(self, request_envelope, context): # type: (RequestEnvelope, Any) -> ResponseEnvelope if (self.skill_id is not None and request_envelope.context.system.application.application_id != self.skill_id): raise AskSdkException("Skill ID Verification failed!!") if self.api_client is not None: api_token = request_envelope.context.system.api_access_token api_endpoint = request_envelope.context.system.api_endpoint api_configuration = ApiConfiguration( serializer=self.serializer, api_client=self.api_client, authorization_value=api_token, api_endpoint=api_endpoint) factory = ServiceClientFactory(api_configuration=api_configuration) else: factory = None attributes_manager = AttributesManager( request_envelope=request_envelope, persistence_adapter=self.persistence_adapter) handler_input = HandlerInput( request_envelope=request_envelope, attributes_manager=attributes_manager, context=context, service_client_factory=factory) response = self.request_dispatcher.dispatch( handler_input=handler_input) session_attributes = None if request_envelope.session is not None: session_attributes = ( handler_input.attributes_manager.session_attributes) return ResponseEnvelope( response=response, version=RESPONSE_FORMAT_VERSION, session_attributes=session_attributes, user_agent=user_agent_info( sdk_version=__version__, custom_user_agent=self.custom_user_agent))
[ "def", "invoke", "(", "self", ",", "request_envelope", ",", "context", ")", ":", "# type: (RequestEnvelope, Any) -> ResponseEnvelope", "if", "(", "self", ".", "skill_id", "is", "not", "None", "and", "request_envelope", ".", "context", ".", "system", ".", "applicat...
Invokes the dispatcher, to handle the request envelope and return a response envelope. :param request_envelope: Request Envelope instance containing request information :type request_envelope: RequestEnvelope :param context: Context passed during invocation :type context: Any :return: Response Envelope generated by handling the request :rtype: ResponseEnvelope
[ "Invokes", "the", "dispatcher", "to", "handle", "the", "request", "envelope", "and", "return", "a", "response", "envelope", "." ]
097b6406aa12d5ca0b825b00c936861b530cbf39
https://github.com/alexa/alexa-skills-kit-sdk-for-python/blob/097b6406aa12d5ca0b825b00c936861b530cbf39/ask-sdk-core/ask_sdk_core/skill.py#L159-L211
234,306
alexa/alexa-skills-kit-sdk-for-python
django-ask-sdk/django_ask_sdk/skill_adapter.py
SkillAdapter.dispatch
def dispatch(self, request, *args, **kwargs): # type: (HttpRequest, object, object) -> HttpResponse """Inspect the HTTP method and delegate to the view method. This is the default implementation of the :py:class:`django.views.View` method, which will inspect the HTTP method in the input request and delegate it to the corresponding method in the view. The only allowed method on this view is ``post``. :param request: The input request sent to the view :type request: django.http.HttpRequest :return: The response from the view :rtype: django.http.HttpResponse :raises: :py:class:`django.http.HttpResponseNotAllowed` if the method is invoked for other than HTTP POST request. :py:class:`django.http.HttpResponseBadRequest` if the request verification fails. :py:class:`django.http.HttpResponseServerError` for any internal exception. """ return super(SkillAdapter, self).dispatch(request)
python
def dispatch(self, request, *args, **kwargs): # type: (HttpRequest, object, object) -> HttpResponse return super(SkillAdapter, self).dispatch(request)
[ "def", "dispatch", "(", "self", ",", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# type: (HttpRequest, object, object) -> HttpResponse", "return", "super", "(", "SkillAdapter", ",", "self", ")", ".", "dispatch", "(", "request", ")" ]
Inspect the HTTP method and delegate to the view method. This is the default implementation of the :py:class:`django.views.View` method, which will inspect the HTTP method in the input request and delegate it to the corresponding method in the view. The only allowed method on this view is ``post``. :param request: The input request sent to the view :type request: django.http.HttpRequest :return: The response from the view :rtype: django.http.HttpResponse :raises: :py:class:`django.http.HttpResponseNotAllowed` if the method is invoked for other than HTTP POST request. :py:class:`django.http.HttpResponseBadRequest` if the request verification fails. :py:class:`django.http.HttpResponseServerError` for any internal exception.
[ "Inspect", "the", "HTTP", "method", "and", "delegate", "to", "the", "view", "method", "." ]
097b6406aa12d5ca0b825b00c936861b530cbf39
https://github.com/alexa/alexa-skills-kit-sdk-for-python/blob/097b6406aa12d5ca0b825b00c936861b530cbf39/django-ask-sdk/django_ask_sdk/skill_adapter.py#L152-L173
234,307
alexa/alexa-skills-kit-sdk-for-python
django-ask-sdk/django_ask_sdk/skill_adapter.py
SkillAdapter.post
def post(self, request, *args, **kwargs): # type: (HttpRequest, object, object) -> HttpResponse """The method that handles HTTP POST request on the view. This method is called when the view receives a HTTP POST request, which is generally the request sent from Alexa during skill invocation. The request is verified through the registered list of verifiers, before invoking the request handlers. The method returns a :py:class:`django.http.JsonResponse` in case of successful skill invocation. :param request: The input request sent by Alexa to the skill :type request: django.http.HttpRequest :return: The response from the skill to Alexa :rtype: django.http.JsonResponse :raises: :py:class:`django.http.HttpResponseBadRequest` if the request verification fails. :py:class:`django.http.HttpResponseServerError` for any internal exception. """ try: content = request.body.decode( verifier_constants.CHARACTER_ENCODING) response = self._webservice_handler.verify_request_and_dispatch( http_request_headers=request.META, http_request_body=content) return JsonResponse( data=response, safe=False) except VerificationException: logger.exception(msg="Request verification failed") return HttpResponseBadRequest( content="Incoming request failed verification") except AskSdkException: logger.exception(msg="Skill dispatch exception") return HttpResponseServerError( content="Exception occurred during skill dispatch")
python
def post(self, request, *args, **kwargs): # type: (HttpRequest, object, object) -> HttpResponse try: content = request.body.decode( verifier_constants.CHARACTER_ENCODING) response = self._webservice_handler.verify_request_and_dispatch( http_request_headers=request.META, http_request_body=content) return JsonResponse( data=response, safe=False) except VerificationException: logger.exception(msg="Request verification failed") return HttpResponseBadRequest( content="Incoming request failed verification") except AskSdkException: logger.exception(msg="Skill dispatch exception") return HttpResponseServerError( content="Exception occurred during skill dispatch")
[ "def", "post", "(", "self", ",", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# type: (HttpRequest, object, object) -> HttpResponse", "try", ":", "content", "=", "request", ".", "body", ".", "decode", "(", "verifier_constants", ".", "CHARAC...
The method that handles HTTP POST request on the view. This method is called when the view receives a HTTP POST request, which is generally the request sent from Alexa during skill invocation. The request is verified through the registered list of verifiers, before invoking the request handlers. The method returns a :py:class:`django.http.JsonResponse` in case of successful skill invocation. :param request: The input request sent by Alexa to the skill :type request: django.http.HttpRequest :return: The response from the skill to Alexa :rtype: django.http.JsonResponse :raises: :py:class:`django.http.HttpResponseBadRequest` if the request verification fails. :py:class:`django.http.HttpResponseServerError` for any internal exception.
[ "The", "method", "that", "handles", "HTTP", "POST", "request", "on", "the", "view", "." ]
097b6406aa12d5ca0b825b00c936861b530cbf39
https://github.com/alexa/alexa-skills-kit-sdk-for-python/blob/097b6406aa12d5ca0b825b00c936861b530cbf39/django-ask-sdk/django_ask_sdk/skill_adapter.py#L175-L211
234,308
alexa/alexa-skills-kit-sdk-for-python
ask-sdk-core/ask_sdk_core/utils/viewport.py
get_orientation
def get_orientation(width, height): # type: (int, int) -> Orientation """Get viewport orientation from given width and height. :type width: int :type height: int :return: viewport orientation enum :rtype: Orientation """ if width > height: return Orientation.LANDSCAPE elif width < height: return Orientation.PORTRAIT else: return Orientation.EQUAL
python
def get_orientation(width, height): # type: (int, int) -> Orientation if width > height: return Orientation.LANDSCAPE elif width < height: return Orientation.PORTRAIT else: return Orientation.EQUAL
[ "def", "get_orientation", "(", "width", ",", "height", ")", ":", "# type: (int, int) -> Orientation", "if", "width", ">", "height", ":", "return", "Orientation", ".", "LANDSCAPE", "elif", "width", "<", "height", ":", "return", "Orientation", ".", "PORTRAIT", "el...
Get viewport orientation from given width and height. :type width: int :type height: int :return: viewport orientation enum :rtype: Orientation
[ "Get", "viewport", "orientation", "from", "given", "width", "and", "height", "." ]
097b6406aa12d5ca0b825b00c936861b530cbf39
https://github.com/alexa/alexa-skills-kit-sdk-for-python/blob/097b6406aa12d5ca0b825b00c936861b530cbf39/ask-sdk-core/ask_sdk_core/utils/viewport.py#L84-L98
234,309
alexa/alexa-skills-kit-sdk-for-python
ask-sdk-core/ask_sdk_core/utils/viewport.py
get_size
def get_size(size): # type: (int) -> Size """Get viewport size from given size. :type size: int :return: viewport size enum :rtype: Size """ if size in range(0, 600): return Size.XSMALL elif size in range(600, 960): return Size.SMALL elif size in range(960, 1280): return Size.MEDIUM elif size in range(1280, 1920): return Size.LARGE elif size >= 1920: return Size.XLARGE raise AskSdkException("Unknown size group value: {}".format(size))
python
def get_size(size): # type: (int) -> Size if size in range(0, 600): return Size.XSMALL elif size in range(600, 960): return Size.SMALL elif size in range(960, 1280): return Size.MEDIUM elif size in range(1280, 1920): return Size.LARGE elif size >= 1920: return Size.XLARGE raise AskSdkException("Unknown size group value: {}".format(size))
[ "def", "get_size", "(", "size", ")", ":", "# type: (int) -> Size", "if", "size", "in", "range", "(", "0", ",", "600", ")", ":", "return", "Size", ".", "XSMALL", "elif", "size", "in", "range", "(", "600", ",", "960", ")", ":", "return", "Size", ".", ...
Get viewport size from given size. :type size: int :return: viewport size enum :rtype: Size
[ "Get", "viewport", "size", "from", "given", "size", "." ]
097b6406aa12d5ca0b825b00c936861b530cbf39
https://github.com/alexa/alexa-skills-kit-sdk-for-python/blob/097b6406aa12d5ca0b825b00c936861b530cbf39/ask-sdk-core/ask_sdk_core/utils/viewport.py#L101-L120
234,310
alexa/alexa-skills-kit-sdk-for-python
ask-sdk-core/ask_sdk_core/utils/viewport.py
get_dpi_group
def get_dpi_group(dpi): # type: (int) -> Density """Get viewport density group from given dpi. :type dpi: int :return: viewport density group enum :rtype: Density """ if dpi in range(0, 121): return Density.XLOW elif dpi in range(121, 161): return Density.LOW elif dpi in range(161, 241): return Density.MEDIUM elif dpi in range(241, 321): return Density.HIGH elif dpi in range(321, 481): return Density.XHIGH elif dpi >= 481: return Density.XXHIGH raise AskSdkException("Unknown dpi group value: {}".format(dpi))
python
def get_dpi_group(dpi): # type: (int) -> Density if dpi in range(0, 121): return Density.XLOW elif dpi in range(121, 161): return Density.LOW elif dpi in range(161, 241): return Density.MEDIUM elif dpi in range(241, 321): return Density.HIGH elif dpi in range(321, 481): return Density.XHIGH elif dpi >= 481: return Density.XXHIGH raise AskSdkException("Unknown dpi group value: {}".format(dpi))
[ "def", "get_dpi_group", "(", "dpi", ")", ":", "# type: (int) -> Density", "if", "dpi", "in", "range", "(", "0", ",", "121", ")", ":", "return", "Density", ".", "XLOW", "elif", "dpi", "in", "range", "(", "121", ",", "161", ")", ":", "return", "Density",...
Get viewport density group from given dpi. :type dpi: int :return: viewport density group enum :rtype: Density
[ "Get", "viewport", "density", "group", "from", "given", "dpi", "." ]
097b6406aa12d5ca0b825b00c936861b530cbf39
https://github.com/alexa/alexa-skills-kit-sdk-for-python/blob/097b6406aa12d5ca0b825b00c936861b530cbf39/ask-sdk-core/ask_sdk_core/utils/viewport.py#L123-L144
234,311
alexa/alexa-skills-kit-sdk-for-python
ask-sdk-core/ask_sdk_core/utils/viewport.py
get_viewport_profile
def get_viewport_profile(request_envelope): # type: (RequestEnvelope) -> ViewportProfile """Utility method, to get viewport profile. The viewport profile is calculated using the shape, current pixel width and height, along with the dpi. If there is no `viewport` value in `request_envelope.context`, then an `ViewportProfile.UNKNOWN_VIEWPORT_PROFILE` is returned. :param request_envelope: The alexa request envelope object :type request_envelope: ask_sdk_model.request_envelope.RequestEnvelope :return: Calculated Viewport Profile enum :rtype: ViewportProfile """ viewport_state = request_envelope.context.viewport if viewport_state: shape = viewport_state.shape current_pixel_width = int(viewport_state.current_pixel_width) current_pixel_height = int(viewport_state.current_pixel_height) dpi = int(viewport_state.dpi) orientation = get_orientation( width=current_pixel_width, height=current_pixel_height) dpi_group = get_dpi_group(dpi=dpi) pixel_width_size_group = get_size(size=current_pixel_width) pixel_height_size_group = get_size(size=current_pixel_height) if (shape is Shape.ROUND and orientation is Orientation.EQUAL and dpi_group is Density.LOW and pixel_width_size_group is Size.XSMALL and pixel_height_size_group is Size.XSMALL): return ViewportProfile.HUB_ROUND_SMALL elif (shape is Shape.RECTANGLE and orientation is Orientation.LANDSCAPE and dpi_group is Density.LOW and pixel_width_size_group <= Size.MEDIUM and pixel_height_size_group <= Size.SMALL): return ViewportProfile.HUB_LANDSCAPE_MEDIUM elif (shape is Shape.RECTANGLE and orientation is Orientation.LANDSCAPE and dpi_group is Density.LOW and pixel_width_size_group >= Size.LARGE and pixel_height_size_group >= Size.SMALL): return ViewportProfile.HUB_LANDSCAPE_LARGE elif (shape is Shape.RECTANGLE and orientation is Orientation.LANDSCAPE and dpi_group is Density.MEDIUM and pixel_width_size_group >= Size.MEDIUM and pixel_height_size_group >= Size.SMALL): return ViewportProfile.MOBILE_LANDSCAPE_MEDIUM elif (shape is Shape.RECTANGLE and orientation is Orientation.PORTRAIT and dpi_group is Density.MEDIUM and pixel_width_size_group >= Size.SMALL and pixel_height_size_group >= Size.MEDIUM): return ViewportProfile.MOBILE_PORTRAIT_MEDIUM elif (shape is Shape.RECTANGLE and orientation is Orientation.LANDSCAPE and dpi_group is Density.MEDIUM and pixel_width_size_group >= Size.SMALL and pixel_height_size_group >= Size.XSMALL): return ViewportProfile.MOBILE_LANDSCAPE_SMALL elif (shape is Shape.RECTANGLE and orientation is Orientation.PORTRAIT and dpi_group is Density.MEDIUM and pixel_width_size_group >= Size.XSMALL and pixel_height_size_group >= Size.SMALL): return ViewportProfile.MOBILE_PORTRAIT_SMALL elif (shape is Shape.RECTANGLE and orientation is Orientation.LANDSCAPE and dpi_group >= Density.HIGH and pixel_width_size_group >= Size.XLARGE and pixel_height_size_group >= Size.MEDIUM): return ViewportProfile.TV_LANDSCAPE_XLARGE elif (shape is Shape.RECTANGLE and orientation is Orientation.PORTRAIT and dpi_group >= Density.HIGH and pixel_width_size_group is Size.XSMALL and pixel_height_size_group is Size.XLARGE): return ViewportProfile.TV_PORTRAIT_MEDIUM elif (shape is Shape.RECTANGLE and orientation is Orientation.LANDSCAPE and dpi_group >= Density.HIGH and pixel_width_size_group is Size.MEDIUM and pixel_height_size_group is Size.SMALL): return ViewportProfile.TV_LANDSCAPE_MEDIUM return ViewportProfile.UNKNOWN_VIEWPORT_PROFILE
python
def get_viewport_profile(request_envelope): # type: (RequestEnvelope) -> ViewportProfile viewport_state = request_envelope.context.viewport if viewport_state: shape = viewport_state.shape current_pixel_width = int(viewport_state.current_pixel_width) current_pixel_height = int(viewport_state.current_pixel_height) dpi = int(viewport_state.dpi) orientation = get_orientation( width=current_pixel_width, height=current_pixel_height) dpi_group = get_dpi_group(dpi=dpi) pixel_width_size_group = get_size(size=current_pixel_width) pixel_height_size_group = get_size(size=current_pixel_height) if (shape is Shape.ROUND and orientation is Orientation.EQUAL and dpi_group is Density.LOW and pixel_width_size_group is Size.XSMALL and pixel_height_size_group is Size.XSMALL): return ViewportProfile.HUB_ROUND_SMALL elif (shape is Shape.RECTANGLE and orientation is Orientation.LANDSCAPE and dpi_group is Density.LOW and pixel_width_size_group <= Size.MEDIUM and pixel_height_size_group <= Size.SMALL): return ViewportProfile.HUB_LANDSCAPE_MEDIUM elif (shape is Shape.RECTANGLE and orientation is Orientation.LANDSCAPE and dpi_group is Density.LOW and pixel_width_size_group >= Size.LARGE and pixel_height_size_group >= Size.SMALL): return ViewportProfile.HUB_LANDSCAPE_LARGE elif (shape is Shape.RECTANGLE and orientation is Orientation.LANDSCAPE and dpi_group is Density.MEDIUM and pixel_width_size_group >= Size.MEDIUM and pixel_height_size_group >= Size.SMALL): return ViewportProfile.MOBILE_LANDSCAPE_MEDIUM elif (shape is Shape.RECTANGLE and orientation is Orientation.PORTRAIT and dpi_group is Density.MEDIUM and pixel_width_size_group >= Size.SMALL and pixel_height_size_group >= Size.MEDIUM): return ViewportProfile.MOBILE_PORTRAIT_MEDIUM elif (shape is Shape.RECTANGLE and orientation is Orientation.LANDSCAPE and dpi_group is Density.MEDIUM and pixel_width_size_group >= Size.SMALL and pixel_height_size_group >= Size.XSMALL): return ViewportProfile.MOBILE_LANDSCAPE_SMALL elif (shape is Shape.RECTANGLE and orientation is Orientation.PORTRAIT and dpi_group is Density.MEDIUM and pixel_width_size_group >= Size.XSMALL and pixel_height_size_group >= Size.SMALL): return ViewportProfile.MOBILE_PORTRAIT_SMALL elif (shape is Shape.RECTANGLE and orientation is Orientation.LANDSCAPE and dpi_group >= Density.HIGH and pixel_width_size_group >= Size.XLARGE and pixel_height_size_group >= Size.MEDIUM): return ViewportProfile.TV_LANDSCAPE_XLARGE elif (shape is Shape.RECTANGLE and orientation is Orientation.PORTRAIT and dpi_group >= Density.HIGH and pixel_width_size_group is Size.XSMALL and pixel_height_size_group is Size.XLARGE): return ViewportProfile.TV_PORTRAIT_MEDIUM elif (shape is Shape.RECTANGLE and orientation is Orientation.LANDSCAPE and dpi_group >= Density.HIGH and pixel_width_size_group is Size.MEDIUM and pixel_height_size_group is Size.SMALL): return ViewportProfile.TV_LANDSCAPE_MEDIUM return ViewportProfile.UNKNOWN_VIEWPORT_PROFILE
[ "def", "get_viewport_profile", "(", "request_envelope", ")", ":", "# type: (RequestEnvelope) -> ViewportProfile", "viewport_state", "=", "request_envelope", ".", "context", ".", "viewport", "if", "viewport_state", ":", "shape", "=", "viewport_state", ".", "shape", "curren...
Utility method, to get viewport profile. The viewport profile is calculated using the shape, current pixel width and height, along with the dpi. If there is no `viewport` value in `request_envelope.context`, then an `ViewportProfile.UNKNOWN_VIEWPORT_PROFILE` is returned. :param request_envelope: The alexa request envelope object :type request_envelope: ask_sdk_model.request_envelope.RequestEnvelope :return: Calculated Viewport Profile enum :rtype: ViewportProfile
[ "Utility", "method", "to", "get", "viewport", "profile", "." ]
097b6406aa12d5ca0b825b00c936861b530cbf39
https://github.com/alexa/alexa-skills-kit-sdk-for-python/blob/097b6406aa12d5ca0b825b00c936861b530cbf39/ask-sdk-core/ask_sdk_core/utils/viewport.py#L147-L246
234,312
alexa/alexa-skills-kit-sdk-for-python
ask-sdk-runtime/ask_sdk_runtime/skill_builder.py
AbstractSkillBuilder.request_handler
def request_handler(self, can_handle_func): # type: (Callable[[Input], bool]) -> Callable """Decorator that can be used to add request handlers easily to the builder. The can_handle_func has to be a Callable instance, which takes a single parameter and no varargs or kwargs. This is because of the RequestHandler class signature restrictions. The returned wrapper function can be applied as a decorator on any function that returns a response object by the skill. The function should follow the signature of the handle function in :py:class:`ask_sdk_runtime.dispatch_components.request_components.AbstractRequestHandler` class. :param can_handle_func: The function that validates if the request can be handled. :type can_handle_func: Callable[[Input], bool] :return: Wrapper function that can be decorated on a handle function. """ def wrapper(handle_func): if not callable(can_handle_func) or not callable(handle_func): raise SkillBuilderException( "Request Handler can_handle_func and handle_func " "input parameters should be callable") class_attributes = { "can_handle": lambda self, handler_input: can_handle_func( handler_input), "handle": lambda self, handler_input: handle_func( handler_input) } request_handler_class = type( "RequestHandler{}".format( handle_func.__name__.title().replace("_", "")), (AbstractRequestHandler,), class_attributes) self.add_request_handler(request_handler=request_handler_class()) return wrapper
python
def request_handler(self, can_handle_func): # type: (Callable[[Input], bool]) -> Callable def wrapper(handle_func): if not callable(can_handle_func) or not callable(handle_func): raise SkillBuilderException( "Request Handler can_handle_func and handle_func " "input parameters should be callable") class_attributes = { "can_handle": lambda self, handler_input: can_handle_func( handler_input), "handle": lambda self, handler_input: handle_func( handler_input) } request_handler_class = type( "RequestHandler{}".format( handle_func.__name__.title().replace("_", "")), (AbstractRequestHandler,), class_attributes) self.add_request_handler(request_handler=request_handler_class()) return wrapper
[ "def", "request_handler", "(", "self", ",", "can_handle_func", ")", ":", "# type: (Callable[[Input], bool]) -> Callable", "def", "wrapper", "(", "handle_func", ")", ":", "if", "not", "callable", "(", "can_handle_func", ")", "or", "not", "callable", "(", "handle_func...
Decorator that can be used to add request handlers easily to the builder. The can_handle_func has to be a Callable instance, which takes a single parameter and no varargs or kwargs. This is because of the RequestHandler class signature restrictions. The returned wrapper function can be applied as a decorator on any function that returns a response object by the skill. The function should follow the signature of the handle function in :py:class:`ask_sdk_runtime.dispatch_components.request_components.AbstractRequestHandler` class. :param can_handle_func: The function that validates if the request can be handled. :type can_handle_func: Callable[[Input], bool] :return: Wrapper function that can be decorated on a handle function.
[ "Decorator", "that", "can", "be", "used", "to", "add", "request", "handlers", "easily", "to", "the", "builder", "." ]
097b6406aa12d5ca0b825b00c936861b530cbf39
https://github.com/alexa/alexa-skills-kit-sdk-for-python/blob/097b6406aa12d5ca0b825b00c936861b530cbf39/ask-sdk-runtime/ask_sdk_runtime/skill_builder.py#L97-L136
234,313
alexa/alexa-skills-kit-sdk-for-python
ask-sdk-runtime/ask_sdk_runtime/skill_builder.py
AbstractSkillBuilder.exception_handler
def exception_handler(self, can_handle_func): # type: (Callable[[Input, Exception], bool]) -> Callable """Decorator that can be used to add exception handlers easily to the builder. The can_handle_func has to be a Callable instance, which takes two parameters and no varargs or kwargs. This is because of the ExceptionHandler class signature restrictions. The returned wrapper function can be applied as a decorator on any function that processes the exception raised during dispatcher and returns a response object by the skill. The function should follow the signature of the handle function in :py:class:`ask_sdk_runtime.dispatch_components.exception_components.AbstractExceptionHandler` class. :param can_handle_func: The function that validates if the exception can be handled. :type can_handle_func: Callable[[Input, Exception], bool] :return: Wrapper function that can be decorated on a handle function. """ def wrapper(handle_func): if not callable(can_handle_func) or not callable(handle_func): raise SkillBuilderException( "Exception Handler can_handle_func and handle_func input " "parameters should be callable") class_attributes = { "can_handle": ( lambda self, handler_input, exception: can_handle_func( handler_input, exception)), "handle": lambda self, handler_input, exception: handle_func( handler_input, exception) } exception_handler_class = type( "ExceptionHandler{}".format( handle_func.__name__.title().replace("_", "")), (AbstractExceptionHandler,), class_attributes) self.add_exception_handler( exception_handler=exception_handler_class()) return wrapper
python
def exception_handler(self, can_handle_func): # type: (Callable[[Input, Exception], bool]) -> Callable def wrapper(handle_func): if not callable(can_handle_func) or not callable(handle_func): raise SkillBuilderException( "Exception Handler can_handle_func and handle_func input " "parameters should be callable") class_attributes = { "can_handle": ( lambda self, handler_input, exception: can_handle_func( handler_input, exception)), "handle": lambda self, handler_input, exception: handle_func( handler_input, exception) } exception_handler_class = type( "ExceptionHandler{}".format( handle_func.__name__.title().replace("_", "")), (AbstractExceptionHandler,), class_attributes) self.add_exception_handler( exception_handler=exception_handler_class()) return wrapper
[ "def", "exception_handler", "(", "self", ",", "can_handle_func", ")", ":", "# type: (Callable[[Input, Exception], bool]) -> Callable", "def", "wrapper", "(", "handle_func", ")", ":", "if", "not", "callable", "(", "can_handle_func", ")", "or", "not", "callable", "(", ...
Decorator that can be used to add exception handlers easily to the builder. The can_handle_func has to be a Callable instance, which takes two parameters and no varargs or kwargs. This is because of the ExceptionHandler class signature restrictions. The returned wrapper function can be applied as a decorator on any function that processes the exception raised during dispatcher and returns a response object by the skill. The function should follow the signature of the handle function in :py:class:`ask_sdk_runtime.dispatch_components.exception_components.AbstractExceptionHandler` class. :param can_handle_func: The function that validates if the exception can be handled. :type can_handle_func: Callable[[Input, Exception], bool] :return: Wrapper function that can be decorated on a handle function.
[ "Decorator", "that", "can", "be", "used", "to", "add", "exception", "handlers", "easily", "to", "the", "builder", "." ]
097b6406aa12d5ca0b825b00c936861b530cbf39
https://github.com/alexa/alexa-skills-kit-sdk-for-python/blob/097b6406aa12d5ca0b825b00c936861b530cbf39/ask-sdk-runtime/ask_sdk_runtime/skill_builder.py#L138-L180
234,314
alexa/alexa-skills-kit-sdk-for-python
ask-sdk-runtime/ask_sdk_runtime/skill_builder.py
AbstractSkillBuilder.global_request_interceptor
def global_request_interceptor(self): # type: () -> Callable """Decorator that can be used to add global request interceptors easily to the builder. The returned wrapper function can be applied as a decorator on any function that processes the input. The function should follow the signature of the process function in :py:class:`ask_sdk_runtime.dispatch_components.request_components.AbstractRequestInterceptor` class. :return: Wrapper function that can be decorated on a interceptor process function. """ def wrapper(process_func): if not callable(process_func): raise SkillBuilderException( "Global Request Interceptor process_func input parameter " "should be callable") class_attributes = { "process": lambda self, handler_input: process_func( handler_input) } request_interceptor = type( "RequestInterceptor{}".format( process_func.__name__.title().replace("_", "")), (AbstractRequestInterceptor,), class_attributes) self.add_global_request_interceptor( request_interceptor=request_interceptor()) return wrapper
python
def global_request_interceptor(self): # type: () -> Callable def wrapper(process_func): if not callable(process_func): raise SkillBuilderException( "Global Request Interceptor process_func input parameter " "should be callable") class_attributes = { "process": lambda self, handler_input: process_func( handler_input) } request_interceptor = type( "RequestInterceptor{}".format( process_func.__name__.title().replace("_", "")), (AbstractRequestInterceptor,), class_attributes) self.add_global_request_interceptor( request_interceptor=request_interceptor()) return wrapper
[ "def", "global_request_interceptor", "(", "self", ")", ":", "# type: () -> Callable", "def", "wrapper", "(", "process_func", ")", ":", "if", "not", "callable", "(", "process_func", ")", ":", "raise", "SkillBuilderException", "(", "\"Global Request Interceptor process_fu...
Decorator that can be used to add global request interceptors easily to the builder. The returned wrapper function can be applied as a decorator on any function that processes the input. The function should follow the signature of the process function in :py:class:`ask_sdk_runtime.dispatch_components.request_components.AbstractRequestInterceptor` class. :return: Wrapper function that can be decorated on a interceptor process function.
[ "Decorator", "that", "can", "be", "used", "to", "add", "global", "request", "interceptors", "easily", "to", "the", "builder", "." ]
097b6406aa12d5ca0b825b00c936861b530cbf39
https://github.com/alexa/alexa-skills-kit-sdk-for-python/blob/097b6406aa12d5ca0b825b00c936861b530cbf39/ask-sdk-runtime/ask_sdk_runtime/skill_builder.py#L182-L214
234,315
alexa/alexa-skills-kit-sdk-for-python
ask-sdk-runtime/ask_sdk_runtime/skill_builder.py
AbstractSkillBuilder.global_response_interceptor
def global_response_interceptor(self): # type: () -> Callable """Decorator that can be used to add global response interceptors easily to the builder. The returned wrapper function can be applied as a decorator on any function that processes the input and the response generated by the request handler. The function should follow the signature of the process function in :py:class:`ask_sdk_runtime.dispatch_components.request_components.AbstractResponseInterceptor` class. :return: Wrapper function that can be decorated on a interceptor process function. """ def wrapper(process_func): if not callable(process_func): raise SkillBuilderException( "Global Response Interceptor process_func input " "parameter should be callable") class_attributes = { "process": ( lambda self, handler_input, response: process_func( handler_input, response)) } response_interceptor = type( "ResponseInterceptor{}".format( process_func.__name__.title().replace("_", "")), (AbstractResponseInterceptor,), class_attributes) self.add_global_response_interceptor( response_interceptor=response_interceptor()) return wrapper
python
def global_response_interceptor(self): # type: () -> Callable def wrapper(process_func): if not callable(process_func): raise SkillBuilderException( "Global Response Interceptor process_func input " "parameter should be callable") class_attributes = { "process": ( lambda self, handler_input, response: process_func( handler_input, response)) } response_interceptor = type( "ResponseInterceptor{}".format( process_func.__name__.title().replace("_", "")), (AbstractResponseInterceptor,), class_attributes) self.add_global_response_interceptor( response_interceptor=response_interceptor()) return wrapper
[ "def", "global_response_interceptor", "(", "self", ")", ":", "# type: () -> Callable", "def", "wrapper", "(", "process_func", ")", ":", "if", "not", "callable", "(", "process_func", ")", ":", "raise", "SkillBuilderException", "(", "\"Global Response Interceptor process_...
Decorator that can be used to add global response interceptors easily to the builder. The returned wrapper function can be applied as a decorator on any function that processes the input and the response generated by the request handler. The function should follow the signature of the process function in :py:class:`ask_sdk_runtime.dispatch_components.request_components.AbstractResponseInterceptor` class. :return: Wrapper function that can be decorated on a interceptor process function.
[ "Decorator", "that", "can", "be", "used", "to", "add", "global", "response", "interceptors", "easily", "to", "the", "builder", "." ]
097b6406aa12d5ca0b825b00c936861b530cbf39
https://github.com/alexa/alexa-skills-kit-sdk-for-python/blob/097b6406aa12d5ca0b825b00c936861b530cbf39/ask-sdk-runtime/ask_sdk_runtime/skill_builder.py#L216-L250
234,316
alexa/alexa-skills-kit-sdk-for-python
ask-sdk-core/ask_sdk_core/utils/request_util.py
get_intent_name
def get_intent_name(handler_input): # type: (HandlerInput) -> AnyStr """Return the name of the intent request. The method retrieves the intent ``name`` from the input request, only if the input request is an :py:class:`ask_sdk_model.intent_request.IntentRequest`. If the input is not an IntentRequest, a :py:class:`TypeError` is raised. :param handler_input: The handler input instance that is generally passed in the sdk's request and exception components :type handler_input: ask_sdk_core.handler_input.HandlerInput :return: Name of the intent request :rtype: str :raises: TypeError """ request = handler_input.request_envelope.request if isinstance(request, IntentRequest): return request.intent.name raise TypeError("The provided request is not an IntentRequest")
python
def get_intent_name(handler_input): # type: (HandlerInput) -> AnyStr request = handler_input.request_envelope.request if isinstance(request, IntentRequest): return request.intent.name raise TypeError("The provided request is not an IntentRequest")
[ "def", "get_intent_name", "(", "handler_input", ")", ":", "# type: (HandlerInput) -> AnyStr", "request", "=", "handler_input", ".", "request_envelope", ".", "request", "if", "isinstance", "(", "request", ",", "IntentRequest", ")", ":", "return", "request", ".", "int...
Return the name of the intent request. The method retrieves the intent ``name`` from the input request, only if the input request is an :py:class:`ask_sdk_model.intent_request.IntentRequest`. If the input is not an IntentRequest, a :py:class:`TypeError` is raised. :param handler_input: The handler input instance that is generally passed in the sdk's request and exception components :type handler_input: ask_sdk_core.handler_input.HandlerInput :return: Name of the intent request :rtype: str :raises: TypeError
[ "Return", "the", "name", "of", "the", "intent", "request", "." ]
097b6406aa12d5ca0b825b00c936861b530cbf39
https://github.com/alexa/alexa-skills-kit-sdk-for-python/blob/097b6406aa12d5ca0b825b00c936861b530cbf39/ask-sdk-core/ask_sdk_core/utils/request_util.py#L65-L85
234,317
alexa/alexa-skills-kit-sdk-for-python
ask-sdk-core/ask_sdk_core/utils/request_util.py
get_device_id
def get_device_id(handler_input): # type: (HandlerInput) -> Optional[AnyStr] """Return the device id from the input request. The method retrieves the `deviceId` property from the input request. This value uniquely identifies the device and is generally used as input for some Alexa-specific API calls. More information about this can be found here : https://developer.amazon.com/docs/custom-skills/request-and-response-json-reference.html#system-object If there is no device information in the input request, then a ``None`` is returned. :param handler_input: The handler input instance that is generally passed in the sdk's request and exception components :type handler_input: ask_sdk_core.handler_input.HandlerInput :return: Unique device id of the device used to send the alexa request or `None` if device information is not present :rtype: Optional[str] """ device = handler_input.request_envelope.context.system.device if device: return device.device_id else: return None
python
def get_device_id(handler_input): # type: (HandlerInput) -> Optional[AnyStr] device = handler_input.request_envelope.context.system.device if device: return device.device_id else: return None
[ "def", "get_device_id", "(", "handler_input", ")", ":", "# type: (HandlerInput) -> Optional[AnyStr]", "device", "=", "handler_input", ".", "request_envelope", ".", "context", ".", "system", ".", "device", "if", "device", ":", "return", "device", ".", "device_id", "e...
Return the device id from the input request. The method retrieves the `deviceId` property from the input request. This value uniquely identifies the device and is generally used as input for some Alexa-specific API calls. More information about this can be found here : https://developer.amazon.com/docs/custom-skills/request-and-response-json-reference.html#system-object If there is no device information in the input request, then a ``None`` is returned. :param handler_input: The handler input instance that is generally passed in the sdk's request and exception components :type handler_input: ask_sdk_core.handler_input.HandlerInput :return: Unique device id of the device used to send the alexa request or `None` if device information is not present :rtype: Optional[str]
[ "Return", "the", "device", "id", "from", "the", "input", "request", "." ]
097b6406aa12d5ca0b825b00c936861b530cbf39
https://github.com/alexa/alexa-skills-kit-sdk-for-python/blob/097b6406aa12d5ca0b825b00c936861b530cbf39/ask-sdk-core/ask_sdk_core/utils/request_util.py#L133-L157
234,318
alexa/alexa-skills-kit-sdk-for-python
ask-sdk-core/ask_sdk_core/utils/request_util.py
get_dialog_state
def get_dialog_state(handler_input): # type: (HandlerInput) -> Optional[DialogState] """Return the dialog state enum from the intent request. The method retrieves the `dialogState` from the intent request, if the skill's interaction model includes a dialog model. This can be used to determine the current status of user conversation and return the appropriate dialog directives if the conversation is not yet complete. More information on dialog management can be found here : https://developer.amazon.com/docs/custom-skills/define-the-dialog-to-collect-and-confirm-required-information.html The method returns a ``None`` if there is no dialog model added or if the intent doesn't have dialog management. The method raises a :py:class:`TypeError` if the input is not an `IntentRequest`. :param handler_input: The handler input instance that is generally passed in the sdk's request and exception components. :type handler_input: ask_sdk_core.handler_input.HandlerInput :return: State of the dialog model from the intent request. :rtype: Optional[ask_sdk_model.dialog_state.DialogState] :raises: TypeError if the input is not an IntentRequest """ request = handler_input.request_envelope.request if isinstance(request, IntentRequest): return request.dialog_state raise TypeError("The provided request is not an IntentRequest")
python
def get_dialog_state(handler_input): # type: (HandlerInput) -> Optional[DialogState] request = handler_input.request_envelope.request if isinstance(request, IntentRequest): return request.dialog_state raise TypeError("The provided request is not an IntentRequest")
[ "def", "get_dialog_state", "(", "handler_input", ")", ":", "# type: (HandlerInput) -> Optional[DialogState]", "request", "=", "handler_input", ".", "request_envelope", ".", "request", "if", "isinstance", "(", "request", ",", "IntentRequest", ")", ":", "return", "request...
Return the dialog state enum from the intent request. The method retrieves the `dialogState` from the intent request, if the skill's interaction model includes a dialog model. This can be used to determine the current status of user conversation and return the appropriate dialog directives if the conversation is not yet complete. More information on dialog management can be found here : https://developer.amazon.com/docs/custom-skills/define-the-dialog-to-collect-and-confirm-required-information.html The method returns a ``None`` if there is no dialog model added or if the intent doesn't have dialog management. The method raises a :py:class:`TypeError` if the input is not an `IntentRequest`. :param handler_input: The handler input instance that is generally passed in the sdk's request and exception components. :type handler_input: ask_sdk_core.handler_input.HandlerInput :return: State of the dialog model from the intent request. :rtype: Optional[ask_sdk_model.dialog_state.DialogState] :raises: TypeError if the input is not an IntentRequest
[ "Return", "the", "dialog", "state", "enum", "from", "the", "intent", "request", "." ]
097b6406aa12d5ca0b825b00c936861b530cbf39
https://github.com/alexa/alexa-skills-kit-sdk-for-python/blob/097b6406aa12d5ca0b825b00c936861b530cbf39/ask-sdk-core/ask_sdk_core/utils/request_util.py#L160-L186
234,319
alexa/alexa-skills-kit-sdk-for-python
ask-sdk-core/ask_sdk_core/utils/request_util.py
get_slot
def get_slot(handler_input, slot_name): # type: (HandlerInput, str) -> Optional[Slot] """Return the slot information from intent request. The method retrieves the slot information :py:class:`ask_sdk_model.slot.Slot` from the input intent request for the given ``slot_name``. More information on the slots can be found here : https://developer.amazon.com/docs/custom-skills/request-types-reference.html#slot-object If there is no such slot, then a ``None`` is returned. If the input request is not an :py:class:`ask_sdk_model.intent_request.IntentRequest`, a :py:class:`TypeError` is raised. :param handler_input: The handler input instance that is generally passed in the sdk's request and exception components :type handler_input: ask_sdk_core.handler_input.HandlerInput :param slot_name: Name of the slot that needs to be retrieved :type slot_name: str :return: Slot information for the provided slot name if it exists, or a `None` value :rtype: Optional[ask_sdk_model.slot.Slot] :raises: TypeError if the input is not an IntentRequest """ request = handler_input.request_envelope.request if isinstance(request, IntentRequest): if request.intent.slots is not None: return request.intent.slots.get(slot_name, None) else: return None raise TypeError("The provided request is not an IntentRequest")
python
def get_slot(handler_input, slot_name): # type: (HandlerInput, str) -> Optional[Slot] request = handler_input.request_envelope.request if isinstance(request, IntentRequest): if request.intent.slots is not None: return request.intent.slots.get(slot_name, None) else: return None raise TypeError("The provided request is not an IntentRequest")
[ "def", "get_slot", "(", "handler_input", ",", "slot_name", ")", ":", "# type: (HandlerInput, str) -> Optional[Slot]", "request", "=", "handler_input", ".", "request_envelope", ".", "request", "if", "isinstance", "(", "request", ",", "IntentRequest", ")", ":", "if", ...
Return the slot information from intent request. The method retrieves the slot information :py:class:`ask_sdk_model.slot.Slot` from the input intent request for the given ``slot_name``. More information on the slots can be found here : https://developer.amazon.com/docs/custom-skills/request-types-reference.html#slot-object If there is no such slot, then a ``None`` is returned. If the input request is not an :py:class:`ask_sdk_model.intent_request.IntentRequest`, a :py:class:`TypeError` is raised. :param handler_input: The handler input instance that is generally passed in the sdk's request and exception components :type handler_input: ask_sdk_core.handler_input.HandlerInput :param slot_name: Name of the slot that needs to be retrieved :type slot_name: str :return: Slot information for the provided slot name if it exists, or a `None` value :rtype: Optional[ask_sdk_model.slot.Slot] :raises: TypeError if the input is not an IntentRequest
[ "Return", "the", "slot", "information", "from", "intent", "request", "." ]
097b6406aa12d5ca0b825b00c936861b530cbf39
https://github.com/alexa/alexa-skills-kit-sdk-for-python/blob/097b6406aa12d5ca0b825b00c936861b530cbf39/ask-sdk-core/ask_sdk_core/utils/request_util.py#L189-L221
234,320
alexa/alexa-skills-kit-sdk-for-python
ask-sdk-core/ask_sdk_core/utils/request_util.py
get_slot_value
def get_slot_value(handler_input, slot_name): # type: (HandlerInput, str) -> AnyStr """Return the slot value from intent request. The method retrieves the slot value from the input intent request for the given ``slot_name``. More information on the slots can be found here : https://developer.amazon.com/docs/custom-skills/request-types-reference.html#slot-object If there is no such slot, then a :py:class:`ValueError` is raised. If the input request is not an :py:class:`ask_sdk_model.intent_request.IntentRequest`, a :py:class:`TypeError` is raised. :param handler_input: The handler input instance that is generally passed in the sdk's request and exception components :type handler_input: ask_sdk_core.handler_input.HandlerInput :param slot_name: Name of the slot for which the value has to be retrieved :type slot_name: str :return: Slot value for the provided slot if it exists :rtype: str :raises: TypeError if the input is not an IntentRequest. ValueError is slot doesn't exist """ slot = get_slot(handler_input=handler_input, slot_name=slot_name) if slot is not None: return slot.value raise ValueError( "Provided slot {} doesn't exist in the input request".format( slot_name))
python
def get_slot_value(handler_input, slot_name): # type: (HandlerInput, str) -> AnyStr slot = get_slot(handler_input=handler_input, slot_name=slot_name) if slot is not None: return slot.value raise ValueError( "Provided slot {} doesn't exist in the input request".format( slot_name))
[ "def", "get_slot_value", "(", "handler_input", ",", "slot_name", ")", ":", "# type: (HandlerInput, str) -> AnyStr", "slot", "=", "get_slot", "(", "handler_input", "=", "handler_input", ",", "slot_name", "=", "slot_name", ")", "if", "slot", "is", "not", "None", ":"...
Return the slot value from intent request. The method retrieves the slot value from the input intent request for the given ``slot_name``. More information on the slots can be found here : https://developer.amazon.com/docs/custom-skills/request-types-reference.html#slot-object If there is no such slot, then a :py:class:`ValueError` is raised. If the input request is not an :py:class:`ask_sdk_model.intent_request.IntentRequest`, a :py:class:`TypeError` is raised. :param handler_input: The handler input instance that is generally passed in the sdk's request and exception components :type handler_input: ask_sdk_core.handler_input.HandlerInput :param slot_name: Name of the slot for which the value has to be retrieved :type slot_name: str :return: Slot value for the provided slot if it exists :rtype: str :raises: TypeError if the input is not an IntentRequest. ValueError is slot doesn't exist
[ "Return", "the", "slot", "value", "from", "intent", "request", "." ]
097b6406aa12d5ca0b825b00c936861b530cbf39
https://github.com/alexa/alexa-skills-kit-sdk-for-python/blob/097b6406aa12d5ca0b825b00c936861b530cbf39/ask-sdk-core/ask_sdk_core/utils/request_util.py#L224-L255
234,321
alexa/alexa-skills-kit-sdk-for-python
ask-sdk-core/ask_sdk_core/utils/request_util.py
is_new_session
def is_new_session(handler_input): # type: (HandlerInput) -> bool """Return if the session is new for the input request. The method retrieves the ``new`` value from the input request's session, which indicates if it's a new session or not. The :py:class:`ask_sdk_model.session.Session` is only included on all standard requests except ``AudioPlayer``, ``VideoApp`` and ``PlaybackController`` requests. More information can be found here : https://developer.amazon.com/docs/custom-skills/request-and-response-json-reference.html#session-object A :py:class:`TypeError` is raised if the input request doesn't have the ``session`` information. :param handler_input: The handler input instance that is generally passed in the sdk's request and exception components :type handler_input: ask_sdk_core.handler_input.HandlerInput :return: Boolean if the session is new for the input request :rtype: bool :raises: TypeError if the input request doesn't have a session """ session = handler_input.request_envelope.session if session is not None: return session.new raise TypeError("The provided request doesn't have a session")
python
def is_new_session(handler_input): # type: (HandlerInput) -> bool session = handler_input.request_envelope.session if session is not None: return session.new raise TypeError("The provided request doesn't have a session")
[ "def", "is_new_session", "(", "handler_input", ")", ":", "# type: (HandlerInput) -> bool", "session", "=", "handler_input", ".", "request_envelope", ".", "session", "if", "session", "is", "not", "None", ":", "return", "session", ".", "new", "raise", "TypeError", "...
Return if the session is new for the input request. The method retrieves the ``new`` value from the input request's session, which indicates if it's a new session or not. The :py:class:`ask_sdk_model.session.Session` is only included on all standard requests except ``AudioPlayer``, ``VideoApp`` and ``PlaybackController`` requests. More information can be found here : https://developer.amazon.com/docs/custom-skills/request-and-response-json-reference.html#session-object A :py:class:`TypeError` is raised if the input request doesn't have the ``session`` information. :param handler_input: The handler input instance that is generally passed in the sdk's request and exception components :type handler_input: ask_sdk_core.handler_input.HandlerInput :return: Boolean if the session is new for the input request :rtype: bool :raises: TypeError if the input request doesn't have a session
[ "Return", "if", "the", "session", "is", "new", "for", "the", "input", "request", "." ]
097b6406aa12d5ca0b825b00c936861b530cbf39
https://github.com/alexa/alexa-skills-kit-sdk-for-python/blob/097b6406aa12d5ca0b825b00c936861b530cbf39/ask-sdk-core/ask_sdk_core/utils/request_util.py#L284-L310
234,322
alexa/alexa-skills-kit-sdk-for-python
ask-sdk-core/ask_sdk_core/response_helper.py
__set_text_field
def __set_text_field(text, text_type): # type: (str, str) -> Union[None, PlainText, RichText] """Helper method to create text field according to text type. :type text: str :param text_type: Type of the primary text field. Allowed values are `PlainText` and `RichText`. :type text_type: str :return: Object of type :py:class:`ask_sdk_model.interfaces.display.PlainText` or :py:class:`ask_sdk_model.interfaces.display.RichText` depending on text_type :rtype: object :raises: ValueError """ if text: if text_type not in [PLAIN_TEXT_TYPE, RICH_TEXT_TYPE]: raise ValueError("Invalid type provided: {}".format(text_type)) if text_type == PLAIN_TEXT_TYPE: return PlainText(text=text) else: return RichText(text=text) else: return None
python
def __set_text_field(text, text_type): # type: (str, str) -> Union[None, PlainText, RichText] if text: if text_type not in [PLAIN_TEXT_TYPE, RICH_TEXT_TYPE]: raise ValueError("Invalid type provided: {}".format(text_type)) if text_type == PLAIN_TEXT_TYPE: return PlainText(text=text) else: return RichText(text=text) else: return None
[ "def", "__set_text_field", "(", "text", ",", "text_type", ")", ":", "# type: (str, str) -> Union[None, PlainText, RichText]", "if", "text", ":", "if", "text_type", "not", "in", "[", "PLAIN_TEXT_TYPE", ",", "RICH_TEXT_TYPE", "]", ":", "raise", "ValueError", "(", "\"I...
Helper method to create text field according to text type. :type text: str :param text_type: Type of the primary text field. Allowed values are `PlainText` and `RichText`. :type text_type: str :return: Object of type :py:class:`ask_sdk_model.interfaces.display.PlainText` or :py:class:`ask_sdk_model.interfaces.display.RichText` depending on text_type :rtype: object :raises: ValueError
[ "Helper", "method", "to", "create", "text", "field", "according", "to", "text", "type", "." ]
097b6406aa12d5ca0b825b00c936861b530cbf39
https://github.com/alexa/alexa-skills-kit-sdk-for-python/blob/097b6406aa12d5ca0b825b00c936861b530cbf39/ask-sdk-core/ask_sdk_core/response_helper.py#L290-L314
234,323
alexa/alexa-skills-kit-sdk-for-python
ask-sdk-core/ask_sdk_core/response_helper.py
ResponseFactory.speak
def speak(self, speech, play_behavior=None): # type: (str, PlayBehavior) -> 'ResponseFactory' """Say the provided speech to the user. :param speech: the output speech sent back to the user. :type speech: str :param play_behavior: attribute to control alexa's speech interruption :type play_behavior: ask_sdk_model.ui.play_behavior.PlayBehavior :return: response factory with partial response being built and access from self.response. :rtype: ResponseFactory """ ssml = "<speak>{}</speak>".format(self.__trim_outputspeech( speech_output=speech)) self.response.output_speech = SsmlOutputSpeech( ssml=ssml, play_behavior=play_behavior) return self
python
def speak(self, speech, play_behavior=None): # type: (str, PlayBehavior) -> 'ResponseFactory' ssml = "<speak>{}</speak>".format(self.__trim_outputspeech( speech_output=speech)) self.response.output_speech = SsmlOutputSpeech( ssml=ssml, play_behavior=play_behavior) return self
[ "def", "speak", "(", "self", ",", "speech", ",", "play_behavior", "=", "None", ")", ":", "# type: (str, PlayBehavior) -> 'ResponseFactory'", "ssml", "=", "\"<speak>{}</speak>\"", ".", "format", "(", "self", ".", "__trim_outputspeech", "(", "speech_output", "=", "spe...
Say the provided speech to the user. :param speech: the output speech sent back to the user. :type speech: str :param play_behavior: attribute to control alexa's speech interruption :type play_behavior: ask_sdk_model.ui.play_behavior.PlayBehavior :return: response factory with partial response being built and access from self.response. :rtype: ResponseFactory
[ "Say", "the", "provided", "speech", "to", "the", "user", "." ]
097b6406aa12d5ca0b825b00c936861b530cbf39
https://github.com/alexa/alexa-skills-kit-sdk-for-python/blob/097b6406aa12d5ca0b825b00c936861b530cbf39/ask-sdk-core/ask_sdk_core/response_helper.py#L55-L72
234,324
alexa/alexa-skills-kit-sdk-for-python
ask-sdk-core/ask_sdk_core/response_helper.py
ResponseFactory.ask
def ask(self, reprompt, play_behavior=None): # type: (str, PlayBehavior) -> 'ResponseFactory' """Provide reprompt speech to the user, if no response for 8 seconds. The should_end_session value will be set to false except when the video app launch directive is present in directives. :param reprompt: the output speech to reprompt. :type reprompt: str :param play_behavior: attribute to control alexa's speech interruption :type play_behavior: ask_sdk_model.ui.play_behavior.PlayBehavior :return: response factory with partial response being built and access from self.response. :rtype: ResponseFactory """ ssml = "<speak>{}</speak>".format(self.__trim_outputspeech( speech_output=reprompt)) output_speech = SsmlOutputSpeech( ssml=ssml, play_behavior=play_behavior) self.response.reprompt = Reprompt(output_speech=output_speech) if not self.__is_video_app_launch_directive_present(): self.response.should_end_session = False return self
python
def ask(self, reprompt, play_behavior=None): # type: (str, PlayBehavior) -> 'ResponseFactory' ssml = "<speak>{}</speak>".format(self.__trim_outputspeech( speech_output=reprompt)) output_speech = SsmlOutputSpeech( ssml=ssml, play_behavior=play_behavior) self.response.reprompt = Reprompt(output_speech=output_speech) if not self.__is_video_app_launch_directive_present(): self.response.should_end_session = False return self
[ "def", "ask", "(", "self", ",", "reprompt", ",", "play_behavior", "=", "None", ")", ":", "# type: (str, PlayBehavior) -> 'ResponseFactory'", "ssml", "=", "\"<speak>{}</speak>\"", ".", "format", "(", "self", ".", "__trim_outputspeech", "(", "speech_output", "=", "rep...
Provide reprompt speech to the user, if no response for 8 seconds. The should_end_session value will be set to false except when the video app launch directive is present in directives. :param reprompt: the output speech to reprompt. :type reprompt: str :param play_behavior: attribute to control alexa's speech interruption :type play_behavior: ask_sdk_model.ui.play_behavior.PlayBehavior :return: response factory with partial response being built and access from self.response. :rtype: ResponseFactory
[ "Provide", "reprompt", "speech", "to", "the", "user", "if", "no", "response", "for", "8", "seconds", "." ]
097b6406aa12d5ca0b825b00c936861b530cbf39
https://github.com/alexa/alexa-skills-kit-sdk-for-python/blob/097b6406aa12d5ca0b825b00c936861b530cbf39/ask-sdk-core/ask_sdk_core/response_helper.py#L74-L98
234,325
alexa/alexa-skills-kit-sdk-for-python
ask-sdk-core/ask_sdk_core/response_helper.py
ResponseFactory.add_directive
def add_directive(self, directive): # type: (Directive) -> 'ResponseFactory' """Adds directive to response. :param directive: the directive sent back to Alexa device. :type directive: ask_sdk_model.directive.Directive :return: response factory with partial response being built and access from self.response. :rtype: ResponseFactory """ if self.response.directives is None: self.response.directives = [] if (directive is not None and directive.object_type == "VideoApp.Launch"): self.response.should_end_session = None self.response.directives.append(directive) return self
python
def add_directive(self, directive): # type: (Directive) -> 'ResponseFactory' if self.response.directives is None: self.response.directives = [] if (directive is not None and directive.object_type == "VideoApp.Launch"): self.response.should_end_session = None self.response.directives.append(directive) return self
[ "def", "add_directive", "(", "self", ",", "directive", ")", ":", "# type: (Directive) -> 'ResponseFactory'", "if", "self", ".", "response", ".", "directives", "is", "None", ":", "self", ".", "response", ".", "directives", "=", "[", "]", "if", "(", "directive",...
Adds directive to response. :param directive: the directive sent back to Alexa device. :type directive: ask_sdk_model.directive.Directive :return: response factory with partial response being built and access from self.response. :rtype: ResponseFactory
[ "Adds", "directive", "to", "response", "." ]
097b6406aa12d5ca0b825b00c936861b530cbf39
https://github.com/alexa/alexa-skills-kit-sdk-for-python/blob/097b6406aa12d5ca0b825b00c936861b530cbf39/ask-sdk-core/ask_sdk_core/response_helper.py#L116-L133
234,326
alexa/alexa-skills-kit-sdk-for-python
ask-sdk-core/ask_sdk_core/response_helper.py
ResponseFactory.__is_video_app_launch_directive_present
def __is_video_app_launch_directive_present(self): # type: () -> bool """Checks if the video app launch directive is present or not. :return: boolean to show if video app launch directive is present or not. :rtype: bool """ if self.response.directives is None: return False for directive in self.response.directives: if (directive is not None and directive.object_type == "VideoApp.Launch"): return True return False
python
def __is_video_app_launch_directive_present(self): # type: () -> bool if self.response.directives is None: return False for directive in self.response.directives: if (directive is not None and directive.object_type == "VideoApp.Launch"): return True return False
[ "def", "__is_video_app_launch_directive_present", "(", "self", ")", ":", "# type: () -> bool", "if", "self", ".", "response", ".", "directives", "is", "None", ":", "return", "False", "for", "directive", "in", "self", ".", "response", ".", "directives", ":", "if"...
Checks if the video app launch directive is present or not. :return: boolean to show if video app launch directive is present or not. :rtype: bool
[ "Checks", "if", "the", "video", "app", "launch", "directive", "is", "present", "or", "not", "." ]
097b6406aa12d5ca0b825b00c936861b530cbf39
https://github.com/alexa/alexa-skills-kit-sdk-for-python/blob/097b6406aa12d5ca0b825b00c936861b530cbf39/ask-sdk-core/ask_sdk_core/response_helper.py#L183-L198
234,327
alexa/alexa-skills-kit-sdk-for-python
ask-sdk-runtime/ask_sdk_runtime/dispatch.py
GenericRequestDispatcher.dispatch
def dispatch(self, handler_input): # type: (Input) -> Union[Output, None] """Dispatches an incoming request to the appropriate request handler and returns the output. Before running the request on the appropriate request handler, dispatcher runs any predefined global request interceptors. On successful response returned from request handler, dispatcher runs predefined global response interceptors, before returning the response. :param handler_input: generic input to the dispatcher :type handler_input: Input :return: generic output handled by the handler, optionally containing a response :rtype: Union[None, Output] :raises: :py:class:`ask_sdk_runtime.exceptions.DispatchException` """ try: for request_interceptor in self.request_interceptors: request_interceptor.process(handler_input=handler_input) output = self.__dispatch_request(handler_input) # type: Union[Output, None] for response_interceptor in self.response_interceptors: response_interceptor.process( handler_input=handler_input, dispatch_output=output) return output except Exception as e: if self.exception_mapper is not None: exception_handler = self.exception_mapper.get_handler( handler_input, e) if exception_handler is None: raise e return exception_handler.handle(handler_input, e) else: raise e
python
def dispatch(self, handler_input): # type: (Input) -> Union[Output, None] try: for request_interceptor in self.request_interceptors: request_interceptor.process(handler_input=handler_input) output = self.__dispatch_request(handler_input) # type: Union[Output, None] for response_interceptor in self.response_interceptors: response_interceptor.process( handler_input=handler_input, dispatch_output=output) return output except Exception as e: if self.exception_mapper is not None: exception_handler = self.exception_mapper.get_handler( handler_input, e) if exception_handler is None: raise e return exception_handler.handle(handler_input, e) else: raise e
[ "def", "dispatch", "(", "self", ",", "handler_input", ")", ":", "# type: (Input) -> Union[Output, None]", "try", ":", "for", "request_interceptor", "in", "self", ".", "request_interceptors", ":", "request_interceptor", ".", "process", "(", "handler_input", "=", "handl...
Dispatches an incoming request to the appropriate request handler and returns the output. Before running the request on the appropriate request handler, dispatcher runs any predefined global request interceptors. On successful response returned from request handler, dispatcher runs predefined global response interceptors, before returning the response. :param handler_input: generic input to the dispatcher :type handler_input: Input :return: generic output handled by the handler, optionally containing a response :rtype: Union[None, Output] :raises: :py:class:`ask_sdk_runtime.exceptions.DispatchException`
[ "Dispatches", "an", "incoming", "request", "to", "the", "appropriate", "request", "handler", "and", "returns", "the", "output", "." ]
097b6406aa12d5ca0b825b00c936861b530cbf39
https://github.com/alexa/alexa-skills-kit-sdk-for-python/blob/097b6406aa12d5ca0b825b00c936861b530cbf39/ask-sdk-runtime/ask_sdk_runtime/dispatch.py#L96-L133
234,328
alexa/alexa-skills-kit-sdk-for-python
ask-sdk-runtime/ask_sdk_runtime/dispatch.py
GenericRequestDispatcher.__dispatch_request
def __dispatch_request(self, handler_input): # type: (Input) -> Union[Output, None] """Process the request and return handler output. When the method is invoked, using the registered list of :py:class:`RequestMapper`, a Handler Chain is found that can handle the request. The handler invocation is delegated to the supported :py:class:`HandlerAdapter`. The registered request interceptors in the handler chain are processed before executing the handler. The registered response interceptors in the handler chain are processed after executing the handler. :param handler_input: generic input to the dispatcher containing incoming request and other context. :type handler_input: Input :return: Output from the 'handle' method execution of the supporting handler. :rtype: Union[None, Output] :raises DispatchException if there is no supporting handler chain or adapter """ request_handler_chain = None for mapper in self.request_mappers: request_handler_chain = mapper.get_request_handler_chain( handler_input) if request_handler_chain is not None: break if request_handler_chain is None: raise DispatchException( "Unable to find a suitable request handler") request_handler = request_handler_chain.request_handler supported_handler_adapter = None for adapter in self.handler_adapters: if adapter.supports(request_handler): supported_handler_adapter = adapter break if supported_handler_adapter is None: raise DispatchException( "Unable to find a suitable request adapter") local_request_interceptors = request_handler_chain.request_interceptors for interceptor in local_request_interceptors: interceptor.process(handler_input=handler_input) output = supported_handler_adapter.execute( handler_input=handler_input, handler=request_handler) # type: Union[Output, None] local_response_interceptors = ( request_handler_chain.response_interceptors) for response_interceptor in local_response_interceptors: response_interceptor.process( handler_input=handler_input, dispatch_output=output) return output
python
def __dispatch_request(self, handler_input): # type: (Input) -> Union[Output, None] request_handler_chain = None for mapper in self.request_mappers: request_handler_chain = mapper.get_request_handler_chain( handler_input) if request_handler_chain is not None: break if request_handler_chain is None: raise DispatchException( "Unable to find a suitable request handler") request_handler = request_handler_chain.request_handler supported_handler_adapter = None for adapter in self.handler_adapters: if adapter.supports(request_handler): supported_handler_adapter = adapter break if supported_handler_adapter is None: raise DispatchException( "Unable to find a suitable request adapter") local_request_interceptors = request_handler_chain.request_interceptors for interceptor in local_request_interceptors: interceptor.process(handler_input=handler_input) output = supported_handler_adapter.execute( handler_input=handler_input, handler=request_handler) # type: Union[Output, None] local_response_interceptors = ( request_handler_chain.response_interceptors) for response_interceptor in local_response_interceptors: response_interceptor.process( handler_input=handler_input, dispatch_output=output) return output
[ "def", "__dispatch_request", "(", "self", ",", "handler_input", ")", ":", "# type: (Input) -> Union[Output, None]", "request_handler_chain", "=", "None", "for", "mapper", "in", "self", ".", "request_mappers", ":", "request_handler_chain", "=", "mapper", ".", "get_reques...
Process the request and return handler output. When the method is invoked, using the registered list of :py:class:`RequestMapper`, a Handler Chain is found that can handle the request. The handler invocation is delegated to the supported :py:class:`HandlerAdapter`. The registered request interceptors in the handler chain are processed before executing the handler. The registered response interceptors in the handler chain are processed after executing the handler. :param handler_input: generic input to the dispatcher containing incoming request and other context. :type handler_input: Input :return: Output from the 'handle' method execution of the supporting handler. :rtype: Union[None, Output] :raises DispatchException if there is no supporting handler chain or adapter
[ "Process", "the", "request", "and", "return", "handler", "output", "." ]
097b6406aa12d5ca0b825b00c936861b530cbf39
https://github.com/alexa/alexa-skills-kit-sdk-for-python/blob/097b6406aa12d5ca0b825b00c936861b530cbf39/ask-sdk-runtime/ask_sdk_runtime/dispatch.py#L135-L191
234,329
alexa/alexa-skills-kit-sdk-for-python
ask-sdk-core/ask_sdk_core/skill_builder.py
SkillBuilder.lambda_handler
def lambda_handler(self): # type: () -> Callable[[RequestEnvelope, T], Dict[str, T]] """Create a handler function that can be used as handler in AWS Lambda console. The lambda handler provides a handler function, that acts as an entry point to the AWS Lambda console. Users can set the lambda_handler output to a variable and set the variable as AWS Lambda Handler on the console. :return: Handler function to tag on AWS Lambda console. """ def wrapper(event, context): # type: (RequestEnvelope, T) -> Dict[str, T] skill = CustomSkill(skill_configuration=self.skill_configuration) request_envelope = skill.serializer.deserialize( payload=json.dumps(event), obj_type=RequestEnvelope) response_envelope = skill.invoke( request_envelope=request_envelope, context=context) return skill.serializer.serialize(response_envelope) # type:ignore return wrapper
python
def lambda_handler(self): # type: () -> Callable[[RequestEnvelope, T], Dict[str, T]] def wrapper(event, context): # type: (RequestEnvelope, T) -> Dict[str, T] skill = CustomSkill(skill_configuration=self.skill_configuration) request_envelope = skill.serializer.deserialize( payload=json.dumps(event), obj_type=RequestEnvelope) response_envelope = skill.invoke( request_envelope=request_envelope, context=context) return skill.serializer.serialize(response_envelope) # type:ignore return wrapper
[ "def", "lambda_handler", "(", "self", ")", ":", "# type: () -> Callable[[RequestEnvelope, T], Dict[str, T]]", "def", "wrapper", "(", "event", ",", "context", ")", ":", "# type: (RequestEnvelope, T) -> Dict[str, T]", "skill", "=", "CustomSkill", "(", "skill_configuration", "...
Create a handler function that can be used as handler in AWS Lambda console. The lambda handler provides a handler function, that acts as an entry point to the AWS Lambda console. Users can set the lambda_handler output to a variable and set the variable as AWS Lambda Handler on the console. :return: Handler function to tag on AWS Lambda console.
[ "Create", "a", "handler", "function", "that", "can", "be", "used", "as", "handler", "in", "AWS", "Lambda", "console", "." ]
097b6406aa12d5ca0b825b00c936861b530cbf39
https://github.com/alexa/alexa-skills-kit-sdk-for-python/blob/097b6406aa12d5ca0b825b00c936861b530cbf39/ask-sdk-core/ask_sdk_core/skill_builder.py#L80-L100
234,330
alexa/alexa-skills-kit-sdk-for-python
ask-sdk-webservice-support/ask_sdk_webservice_support/webservice_handler.py
WebserviceSkillHandler.verify_request_and_dispatch
def verify_request_and_dispatch( self, http_request_headers, http_request_body): # type: (Dict[str, Any], str) -> str """Entry point for webservice skill invocation. This method takes in the input request headers and request body, handles the deserialization of the input request to the :py:class:`ask_sdk_model.request_envelope.RequestEnvelope` object, run the input through registered verifiers, invoke the skill and return the serialized response from the skill invocation. :param http_request_headers: Request headers of the input request to the webservice :type http_request_headers: Dict[str, Any] :param http_request_body: Raw request body of the input request to the webservice :type http_request_body: str :return: Serialized response object returned by the skill instance, when invoked with the input request :rtype: str :raises: :py:class:`ask_sdk_core.exceptions.AskSdkException` when skill deserialization, verification, invocation or serialization fails """ request_envelope = self._skill.serializer.deserialize( payload=http_request_body, obj_type=RequestEnvelope) for verifier in self._verifiers: verifier.verify( headers=http_request_headers, serialized_request_env=http_request_body, deserialized_request_env=request_envelope) response_envelope = self._skill.invoke( request_envelope=request_envelope, context=None) return self._skill.serializer.serialize(response_envelope)
python
def verify_request_and_dispatch( self, http_request_headers, http_request_body): # type: (Dict[str, Any], str) -> str request_envelope = self._skill.serializer.deserialize( payload=http_request_body, obj_type=RequestEnvelope) for verifier in self._verifiers: verifier.verify( headers=http_request_headers, serialized_request_env=http_request_body, deserialized_request_env=request_envelope) response_envelope = self._skill.invoke( request_envelope=request_envelope, context=None) return self._skill.serializer.serialize(response_envelope)
[ "def", "verify_request_and_dispatch", "(", "self", ",", "http_request_headers", ",", "http_request_body", ")", ":", "# type: (Dict[str, Any], str) -> str", "request_envelope", "=", "self", ".", "_skill", ".", "serializer", ".", "deserialize", "(", "payload", "=", "http_...
Entry point for webservice skill invocation. This method takes in the input request headers and request body, handles the deserialization of the input request to the :py:class:`ask_sdk_model.request_envelope.RequestEnvelope` object, run the input through registered verifiers, invoke the skill and return the serialized response from the skill invocation. :param http_request_headers: Request headers of the input request to the webservice :type http_request_headers: Dict[str, Any] :param http_request_body: Raw request body of the input request to the webservice :type http_request_body: str :return: Serialized response object returned by the skill instance, when invoked with the input request :rtype: str :raises: :py:class:`ask_sdk_core.exceptions.AskSdkException` when skill deserialization, verification, invocation or serialization fails
[ "Entry", "point", "for", "webservice", "skill", "invocation", "." ]
097b6406aa12d5ca0b825b00c936861b530cbf39
https://github.com/alexa/alexa-skills-kit-sdk-for-python/blob/097b6406aa12d5ca0b825b00c936861b530cbf39/ask-sdk-webservice-support/ask_sdk_webservice_support/webservice_handler.py#L99-L136
234,331
alexa/alexa-skills-kit-sdk-for-python
flask-ask-sdk/flask_ask_sdk/skill_adapter.py
SkillAdapter.init_app
def init_app(self, app): # type: (Flask) -> None """Register the extension on the given Flask application. Use this function only when no Flask application was provided in the ``app`` keyword argument to the constructor of this class. The function sets ``True`` defaults for :py:const:`VERIFY_SIGNATURE_APP_CONFIG` and :py:const:`VERIFY_TIMESTAMP_APP_CONFIG` configurations. It adds the skill id: self instance mapping to the application extensions, and creates a :py:class:`ask_sdk_webservice_support.webservice_handler.WebserviceHandler` instance, for request verification and dispatch. :param app: A :py:class:`flask.Flask` application instance :type app: flask.Flask :rtype: None """ app.config.setdefault(VERIFY_SIGNATURE_APP_CONFIG, True) app.config.setdefault(VERIFY_TIMESTAMP_APP_CONFIG, True) if EXTENSION_NAME not in app.extensions: app.extensions[EXTENSION_NAME] = {} app.extensions[EXTENSION_NAME][self._skill_id] = self with app.app_context(): self._create_webservice_handler(self._skill, self._verifiers)
python
def init_app(self, app): # type: (Flask) -> None app.config.setdefault(VERIFY_SIGNATURE_APP_CONFIG, True) app.config.setdefault(VERIFY_TIMESTAMP_APP_CONFIG, True) if EXTENSION_NAME not in app.extensions: app.extensions[EXTENSION_NAME] = {} app.extensions[EXTENSION_NAME][self._skill_id] = self with app.app_context(): self._create_webservice_handler(self._skill, self._verifiers)
[ "def", "init_app", "(", "self", ",", "app", ")", ":", "# type: (Flask) -> None", "app", ".", "config", ".", "setdefault", "(", "VERIFY_SIGNATURE_APP_CONFIG", ",", "True", ")", "app", ".", "config", ".", "setdefault", "(", "VERIFY_TIMESTAMP_APP_CONFIG", ",", "Tru...
Register the extension on the given Flask application. Use this function only when no Flask application was provided in the ``app`` keyword argument to the constructor of this class. The function sets ``True`` defaults for :py:const:`VERIFY_SIGNATURE_APP_CONFIG` and :py:const:`VERIFY_TIMESTAMP_APP_CONFIG` configurations. It adds the skill id: self instance mapping to the application extensions, and creates a :py:class:`ask_sdk_webservice_support.webservice_handler.WebserviceHandler` instance, for request verification and dispatch. :param app: A :py:class:`flask.Flask` application instance :type app: flask.Flask :rtype: None
[ "Register", "the", "extension", "on", "the", "given", "Flask", "application", "." ]
097b6406aa12d5ca0b825b00c936861b530cbf39
https://github.com/alexa/alexa-skills-kit-sdk-for-python/blob/097b6406aa12d5ca0b825b00c936861b530cbf39/flask-ask-sdk/flask_ask_sdk/skill_adapter.py#L156-L184
234,332
alexa/alexa-skills-kit-sdk-for-python
flask-ask-sdk/flask_ask_sdk/skill_adapter.py
SkillAdapter._create_webservice_handler
def _create_webservice_handler(self, skill, verifiers): # type: (CustomSkill, List[AbstractVerifier]) -> None """Create the handler for request verification and dispatch. :param skill: A :py:class:`ask_sdk_core.skill.CustomSkill` instance. If you are using the skill builder from ask-sdk, then you can use the ``create`` method under it, to create a skill instance :type skill: ask_sdk_core.skill.CustomSkill :param verifiers: A list of verifiers, that needs to be applied on the input request, before invoking the request handlers. :type verifiers: list[ask_sdk_webservice_support.verifier.AbstractVerifier] :rtype: None """ if verifiers is None: verifiers = [] self._webservice_handler = WebserviceSkillHandler( skill=skill, verify_signature=current_app.config.get( VERIFY_SIGNATURE_APP_CONFIG, True), verify_timestamp=current_app.config.get( VERIFY_TIMESTAMP_APP_CONFIG, True), verifiers=verifiers)
python
def _create_webservice_handler(self, skill, verifiers): # type: (CustomSkill, List[AbstractVerifier]) -> None if verifiers is None: verifiers = [] self._webservice_handler = WebserviceSkillHandler( skill=skill, verify_signature=current_app.config.get( VERIFY_SIGNATURE_APP_CONFIG, True), verify_timestamp=current_app.config.get( VERIFY_TIMESTAMP_APP_CONFIG, True), verifiers=verifiers)
[ "def", "_create_webservice_handler", "(", "self", ",", "skill", ",", "verifiers", ")", ":", "# type: (CustomSkill, List[AbstractVerifier]) -> None", "if", "verifiers", "is", "None", ":", "verifiers", "=", "[", "]", "self", ".", "_webservice_handler", "=", "WebserviceS...
Create the handler for request verification and dispatch. :param skill: A :py:class:`ask_sdk_core.skill.CustomSkill` instance. If you are using the skill builder from ask-sdk, then you can use the ``create`` method under it, to create a skill instance :type skill: ask_sdk_core.skill.CustomSkill :param verifiers: A list of verifiers, that needs to be applied on the input request, before invoking the request handlers. :type verifiers: list[ask_sdk_webservice_support.verifier.AbstractVerifier] :rtype: None
[ "Create", "the", "handler", "for", "request", "verification", "and", "dispatch", "." ]
097b6406aa12d5ca0b825b00c936861b530cbf39
https://github.com/alexa/alexa-skills-kit-sdk-for-python/blob/097b6406aa12d5ca0b825b00c936861b530cbf39/flask-ask-sdk/flask_ask_sdk/skill_adapter.py#L186-L211
234,333
alexa/alexa-skills-kit-sdk-for-python
flask-ask-sdk/flask_ask_sdk/skill_adapter.py
SkillAdapter.dispatch_request
def dispatch_request(self): # type: () -> Response """Method that handles request verification and routing. This method can be used as a function to register on the URL rule. The request is verified through the registered list of verifiers, before invoking the request handlers. The method returns a JSON response for the Alexa service to respond to the request. :return: The skill response for the input request :rtype: flask.Response :raises: :py:class:`werkzeug.exceptions.MethodNotAllowed` if the method is invoked for other than HTTP POST request. :py:class:`werkzeug.exceptions.BadRequest` if the verification fails. :py:class:`werkzeug.exceptions.InternalServerError` for any internal exception. """ if flask_request.method != "POST": raise exceptions.MethodNotAllowed() try: content = flask_request.data.decode( verifier_constants.CHARACTER_ENCODING) response = self._webservice_handler.verify_request_and_dispatch( http_request_headers=flask_request.headers, http_request_body=content) return jsonify(response) except VerificationException: current_app.logger.error( "Request verification failed", exc_info=True) raise exceptions.BadRequest( description="Incoming request failed verification") except AskSdkException: current_app.logger.error( "Skill dispatch exception", exc_info=True) raise exceptions.InternalServerError( description="Exception occurred during skill dispatch")
python
def dispatch_request(self): # type: () -> Response if flask_request.method != "POST": raise exceptions.MethodNotAllowed() try: content = flask_request.data.decode( verifier_constants.CHARACTER_ENCODING) response = self._webservice_handler.verify_request_and_dispatch( http_request_headers=flask_request.headers, http_request_body=content) return jsonify(response) except VerificationException: current_app.logger.error( "Request verification failed", exc_info=True) raise exceptions.BadRequest( description="Incoming request failed verification") except AskSdkException: current_app.logger.error( "Skill dispatch exception", exc_info=True) raise exceptions.InternalServerError( description="Exception occurred during skill dispatch")
[ "def", "dispatch_request", "(", "self", ")", ":", "# type: () -> Response", "if", "flask_request", ".", "method", "!=", "\"POST\"", ":", "raise", "exceptions", ".", "MethodNotAllowed", "(", ")", "try", ":", "content", "=", "flask_request", ".", "data", ".", "d...
Method that handles request verification and routing. This method can be used as a function to register on the URL rule. The request is verified through the registered list of verifiers, before invoking the request handlers. The method returns a JSON response for the Alexa service to respond to the request. :return: The skill response for the input request :rtype: flask.Response :raises: :py:class:`werkzeug.exceptions.MethodNotAllowed` if the method is invoked for other than HTTP POST request. :py:class:`werkzeug.exceptions.BadRequest` if the verification fails. :py:class:`werkzeug.exceptions.InternalServerError` for any internal exception.
[ "Method", "that", "handles", "request", "verification", "and", "routing", "." ]
097b6406aa12d5ca0b825b00c936861b530cbf39
https://github.com/alexa/alexa-skills-kit-sdk-for-python/blob/097b6406aa12d5ca0b825b00c936861b530cbf39/flask-ask-sdk/flask_ask_sdk/skill_adapter.py#L213-L252
234,334
alexa/alexa-skills-kit-sdk-for-python
flask-ask-sdk/flask_ask_sdk/skill_adapter.py
SkillAdapter.register
def register(self, app, route, endpoint=None): # type: (Flask, str, str) -> None """Method to register the routing on the app at provided route. This is a utility method, that can be used for registering the ``dispatch_request`` on the provided :py:class:`flask.Flask` application at the provided URL ``route``. :param app: A :py:class:`flask.Flask` application instance :type app: flask.Flask :param route: The URL rule where the skill dispatch has to be registered :type route: str :param endpoint: The endpoint for the registered URL rule. This can be used to set multiple skill endpoints on same app. :type endpoint: str :rtype: None :raises: :py:class:`TypeError` if ``app`` or `route`` is not provided or is of an invalid type """ if app is None or not isinstance(app, Flask): raise TypeError("Expected a valid Flask instance") if route is None or not isinstance(route, str): raise TypeError("Expected a valid URL rule string") app.add_url_rule( route, view_func=self.dispatch_request, methods=["POST"], endpoint=endpoint)
python
def register(self, app, route, endpoint=None): # type: (Flask, str, str) -> None if app is None or not isinstance(app, Flask): raise TypeError("Expected a valid Flask instance") if route is None or not isinstance(route, str): raise TypeError("Expected a valid URL rule string") app.add_url_rule( route, view_func=self.dispatch_request, methods=["POST"], endpoint=endpoint)
[ "def", "register", "(", "self", ",", "app", ",", "route", ",", "endpoint", "=", "None", ")", ":", "# type: (Flask, str, str) -> None", "if", "app", "is", "None", "or", "not", "isinstance", "(", "app", ",", "Flask", ")", ":", "raise", "TypeError", "(", "\...
Method to register the routing on the app at provided route. This is a utility method, that can be used for registering the ``dispatch_request`` on the provided :py:class:`flask.Flask` application at the provided URL ``route``. :param app: A :py:class:`flask.Flask` application instance :type app: flask.Flask :param route: The URL rule where the skill dispatch has to be registered :type route: str :param endpoint: The endpoint for the registered URL rule. This can be used to set multiple skill endpoints on same app. :type endpoint: str :rtype: None :raises: :py:class:`TypeError` if ``app`` or `route`` is not provided or is of an invalid type
[ "Method", "to", "register", "the", "routing", "on", "the", "app", "at", "provided", "route", "." ]
097b6406aa12d5ca0b825b00c936861b530cbf39
https://github.com/alexa/alexa-skills-kit-sdk-for-python/blob/097b6406aa12d5ca0b825b00c936861b530cbf39/flask-ask-sdk/flask_ask_sdk/skill_adapter.py#L254-L282
234,335
alexa/alexa-skills-kit-sdk-for-python
ask-sdk-core/ask_sdk_core/serialize.py
DefaultSerializer.serialize
def serialize(self, obj): # type: ignore # type: (Any) -> Union[Dict[str, Any], List, Tuple, str, int, float, None] """Builds a serialized object. * If obj is None, return None. * If obj is str, int, long, float, bool, return directly. * If obj is datetime.datetime, datetime.date convert to string in iso8601 format. * If obj is list, serialize each element in the list. * If obj is dict, return the dict with serialized values. * If obj is ask sdk model, return the dict with keys resolved from the union of model's ``attribute_map`` and ``deserialized_types`` and values serialized based on ``deserialized_types``. * If obj is a generic class instance, return the dict with keys from instance's ``deserialized_types`` and values serialized based on ``deserialized_types``. :param obj: The data to serialize. :type obj: object :return: The serialized form of data. :rtype: Union[Dict[str, Any], List, Tuple, str, int, float, None] """ if obj is None: return None elif isinstance(obj, self.PRIMITIVE_TYPES): return obj elif isinstance(obj, list): return [self.serialize(sub_obj) for sub_obj in obj] elif isinstance(obj, tuple): return tuple(self.serialize(sub_obj) for sub_obj in obj) elif isinstance(obj, (datetime, date)): return obj.isoformat() elif isinstance(obj, Enum): return obj.value elif isinstance(obj, decimal.Decimal): if obj % 1 == 0: return int(obj) else: return float(obj) if isinstance(obj, dict): obj_dict = obj else: # Convert model obj to dict # All the non null attributes under `deserialized_types` # map are considered for serialization. # The `attribute_map` provides the key names to be used # in the dict. In case of missing `attribute_map` mapping, # the original attribute name is retained as the key name. class_attribute_map = getattr(obj, 'attribute_map', {}) class_attribute_map.update( { k: k for k in obj.deserialized_types.keys() if k not in class_attribute_map } ) obj_dict = { class_attribute_map[attr]: getattr(obj, attr) for attr, _ in iteritems(obj.deserialized_types) if getattr(obj, attr) is not None } return {key: self.serialize(val) for key, val in iteritems(obj_dict)}
python
def serialize(self, obj): # type: ignore # type: (Any) -> Union[Dict[str, Any], List, Tuple, str, int, float, None] if obj is None: return None elif isinstance(obj, self.PRIMITIVE_TYPES): return obj elif isinstance(obj, list): return [self.serialize(sub_obj) for sub_obj in obj] elif isinstance(obj, tuple): return tuple(self.serialize(sub_obj) for sub_obj in obj) elif isinstance(obj, (datetime, date)): return obj.isoformat() elif isinstance(obj, Enum): return obj.value elif isinstance(obj, decimal.Decimal): if obj % 1 == 0: return int(obj) else: return float(obj) if isinstance(obj, dict): obj_dict = obj else: # Convert model obj to dict # All the non null attributes under `deserialized_types` # map are considered for serialization. # The `attribute_map` provides the key names to be used # in the dict. In case of missing `attribute_map` mapping, # the original attribute name is retained as the key name. class_attribute_map = getattr(obj, 'attribute_map', {}) class_attribute_map.update( { k: k for k in obj.deserialized_types.keys() if k not in class_attribute_map } ) obj_dict = { class_attribute_map[attr]: getattr(obj, attr) for attr, _ in iteritems(obj.deserialized_types) if getattr(obj, attr) is not None } return {key: self.serialize(val) for key, val in iteritems(obj_dict)}
[ "def", "serialize", "(", "self", ",", "obj", ")", ":", "# type: ignore", "# type: (Any) -> Union[Dict[str, Any], List, Tuple, str, int, float, None]", "if", "obj", "is", "None", ":", "return", "None", "elif", "isinstance", "(", "obj", ",", "self", ".", "PRIMITIVE_TYPE...
Builds a serialized object. * If obj is None, return None. * If obj is str, int, long, float, bool, return directly. * If obj is datetime.datetime, datetime.date convert to string in iso8601 format. * If obj is list, serialize each element in the list. * If obj is dict, return the dict with serialized values. * If obj is ask sdk model, return the dict with keys resolved from the union of model's ``attribute_map`` and ``deserialized_types`` and values serialized based on ``deserialized_types``. * If obj is a generic class instance, return the dict with keys from instance's ``deserialized_types`` and values serialized based on ``deserialized_types``. :param obj: The data to serialize. :type obj: object :return: The serialized form of data. :rtype: Union[Dict[str, Any], List, Tuple, str, int, float, None]
[ "Builds", "a", "serialized", "object", "." ]
097b6406aa12d5ca0b825b00c936861b530cbf39
https://github.com/alexa/alexa-skills-kit-sdk-for-python/blob/097b6406aa12d5ca0b825b00c936861b530cbf39/ask-sdk-core/ask_sdk_core/serialize.py#L61-L125
234,336
alexa/alexa-skills-kit-sdk-for-python
ask-sdk-core/ask_sdk_core/serialize.py
DefaultSerializer.deserialize
def deserialize(self, payload, obj_type): # type: (str, Union[T, str]) -> Any """Deserializes payload into an instance of provided ``obj_type``. The ``obj_type`` parameter can be a primitive type, a generic model object or a list / dict of model objects. The list or dict object type has to be provided as a string format. For eg: * ``'list[a.b.C]'`` if the payload is a list of instances of class ``a.b.C``. * ``'dict(str, a.b.C)'`` if the payload is a dict containing mappings of ``str : a.b.C`` class instance types. The method looks for a ``deserialized_types`` dict in the model class, that mentions which payload values has to be deserialized. In case the payload key names are different than the model attribute names, the corresponding mapping can be provided in another special dict ``attribute_map``. The model class should also have the ``__init__`` method with default values for arguments. Check :py:class:`ask_sdk_model.request_envelope.RequestEnvelope` source code for an example implementation. :param payload: data to be deserialized. :type payload: str :param obj_type: resolved class name for deserialized object :type obj_type: Union[object, str] :return: deserialized object :rtype: object :raises: :py:class:`ask_sdk_core.exceptions.SerializationException` """ if payload is None: return None try: payload = json.loads(payload) except Exception: raise SerializationException( "Couldn't parse response body: {}".format(payload)) return self.__deserialize(payload, obj_type)
python
def deserialize(self, payload, obj_type): # type: (str, Union[T, str]) -> Any if payload is None: return None try: payload = json.loads(payload) except Exception: raise SerializationException( "Couldn't parse response body: {}".format(payload)) return self.__deserialize(payload, obj_type)
[ "def", "deserialize", "(", "self", ",", "payload", ",", "obj_type", ")", ":", "# type: (str, Union[T, str]) -> Any", "if", "payload", "is", "None", ":", "return", "None", "try", ":", "payload", "=", "json", ".", "loads", "(", "payload", ")", "except", "Excep...
Deserializes payload into an instance of provided ``obj_type``. The ``obj_type`` parameter can be a primitive type, a generic model object or a list / dict of model objects. The list or dict object type has to be provided as a string format. For eg: * ``'list[a.b.C]'`` if the payload is a list of instances of class ``a.b.C``. * ``'dict(str, a.b.C)'`` if the payload is a dict containing mappings of ``str : a.b.C`` class instance types. The method looks for a ``deserialized_types`` dict in the model class, that mentions which payload values has to be deserialized. In case the payload key names are different than the model attribute names, the corresponding mapping can be provided in another special dict ``attribute_map``. The model class should also have the ``__init__`` method with default values for arguments. Check :py:class:`ask_sdk_model.request_envelope.RequestEnvelope` source code for an example implementation. :param payload: data to be deserialized. :type payload: str :param obj_type: resolved class name for deserialized object :type obj_type: Union[object, str] :return: deserialized object :rtype: object :raises: :py:class:`ask_sdk_core.exceptions.SerializationException`
[ "Deserializes", "payload", "into", "an", "instance", "of", "provided", "obj_type", "." ]
097b6406aa12d5ca0b825b00c936861b530cbf39
https://github.com/alexa/alexa-skills-kit-sdk-for-python/blob/097b6406aa12d5ca0b825b00c936861b530cbf39/ask-sdk-core/ask_sdk_core/serialize.py#L127-L169
234,337
alexa/alexa-skills-kit-sdk-for-python
ask-sdk-core/ask_sdk_core/serialize.py
DefaultSerializer.__deserialize
def __deserialize(self, payload, obj_type): # type: (str, Union[T, str]) -> Any """Deserializes payload into a model object. :param payload: data to be deserialized. :type payload: str :param obj_type: resolved class name for deserialized object :type obj_type: Union[object, str] :return: deserialized object :rtype: object """ if payload is None: return None if isinstance(obj_type, str): if obj_type.startswith('list['): # Get object type for each item in the list # Deserialize each item using the object type. sub_obj_type = re.match( 'list\[(.*)\]', obj_type) if sub_obj_type is None: return [] sub_obj_types = sub_obj_type.group(1) deserialized_list = [] # type: List if "," in sub_obj_types: # list contains objects of different types for sub_payload, sub_obj_types in zip( payload, sub_obj_types.split(",")): deserialized_list.append(self.__deserialize( sub_payload, sub_obj_types.strip())) else: for sub_payload in payload: deserialized_list.append(self.__deserialize( sub_payload, sub_obj_types.strip())) return deserialized_list if obj_type.startswith('dict('): # Get object type for each k,v pair in the dict # Deserialize each value using the object type of v. sub_obj_type = re.match( 'dict\(([^,]*), (.*)\)', obj_type) if sub_obj_type is None: return {} sub_obj_types = sub_obj_type.group(2) return { k: self.__deserialize(v, sub_obj_types) for k, v in iteritems(cast(Any, payload)) } # convert str to class if obj_type in self.NATIVE_TYPES_MAPPING: obj_type = self.NATIVE_TYPES_MAPPING[obj_type] # type: ignore else: # deserialize models obj_type = self.__load_class_from_name(obj_type) if obj_type in self.PRIMITIVE_TYPES: return self.__deserialize_primitive(payload, obj_type) elif obj_type == object: return payload elif obj_type == date: return self.__deserialize_datetime(payload, obj_type) elif obj_type == datetime: return self.__deserialize_datetime(payload, obj_type) else: return self.__deserialize_model(payload, obj_type)
python
def __deserialize(self, payload, obj_type): # type: (str, Union[T, str]) -> Any if payload is None: return None if isinstance(obj_type, str): if obj_type.startswith('list['): # Get object type for each item in the list # Deserialize each item using the object type. sub_obj_type = re.match( 'list\[(.*)\]', obj_type) if sub_obj_type is None: return [] sub_obj_types = sub_obj_type.group(1) deserialized_list = [] # type: List if "," in sub_obj_types: # list contains objects of different types for sub_payload, sub_obj_types in zip( payload, sub_obj_types.split(",")): deserialized_list.append(self.__deserialize( sub_payload, sub_obj_types.strip())) else: for sub_payload in payload: deserialized_list.append(self.__deserialize( sub_payload, sub_obj_types.strip())) return deserialized_list if obj_type.startswith('dict('): # Get object type for each k,v pair in the dict # Deserialize each value using the object type of v. sub_obj_type = re.match( 'dict\(([^,]*), (.*)\)', obj_type) if sub_obj_type is None: return {} sub_obj_types = sub_obj_type.group(2) return { k: self.__deserialize(v, sub_obj_types) for k, v in iteritems(cast(Any, payload)) } # convert str to class if obj_type in self.NATIVE_TYPES_MAPPING: obj_type = self.NATIVE_TYPES_MAPPING[obj_type] # type: ignore else: # deserialize models obj_type = self.__load_class_from_name(obj_type) if obj_type in self.PRIMITIVE_TYPES: return self.__deserialize_primitive(payload, obj_type) elif obj_type == object: return payload elif obj_type == date: return self.__deserialize_datetime(payload, obj_type) elif obj_type == datetime: return self.__deserialize_datetime(payload, obj_type) else: return self.__deserialize_model(payload, obj_type)
[ "def", "__deserialize", "(", "self", ",", "payload", ",", "obj_type", ")", ":", "# type: (str, Union[T, str]) -> Any", "if", "payload", "is", "None", ":", "return", "None", "if", "isinstance", "(", "obj_type", ",", "str", ")", ":", "if", "obj_type", ".", "st...
Deserializes payload into a model object. :param payload: data to be deserialized. :type payload: str :param obj_type: resolved class name for deserialized object :type obj_type: Union[object, str] :return: deserialized object :rtype: object
[ "Deserializes", "payload", "into", "a", "model", "object", "." ]
097b6406aa12d5ca0b825b00c936861b530cbf39
https://github.com/alexa/alexa-skills-kit-sdk-for-python/blob/097b6406aa12d5ca0b825b00c936861b530cbf39/ask-sdk-core/ask_sdk_core/serialize.py#L171-L235
234,338
alexa/alexa-skills-kit-sdk-for-python
ask-sdk-core/ask_sdk_core/serialize.py
DefaultSerializer.__load_class_from_name
def __load_class_from_name(self, class_name): # type: (str) -> T """Load the class from the ``class_name`` provided. Resolve the class name from the ``class_name`` provided, load the class on path and return the resolved class. If the module information is not provided in the ``class_name``, then look for the class on sys ``modules``. :param class_name: absolute class name to be loaded :type class_name: str :return: Resolved class reference :rtype: object :raises: :py:class:`ask_sdk_core.exceptions.SerializationException` """ try: module_class_list = class_name.rsplit(".", 1) if len(module_class_list) > 1: module_name = module_class_list[0] resolved_class_name = module_class_list[1] module = __import__( module_name, fromlist=[resolved_class_name]) resolved_class = getattr(module, resolved_class_name) else: resolved_class_name = module_class_list[0] resolved_class = getattr( sys.modules[__name__], resolved_class_name) return resolved_class except Exception as e: raise SerializationException( "Unable to resolve class {} from installed " "modules: {}".format(class_name, str(e)))
python
def __load_class_from_name(self, class_name): # type: (str) -> T try: module_class_list = class_name.rsplit(".", 1) if len(module_class_list) > 1: module_name = module_class_list[0] resolved_class_name = module_class_list[1] module = __import__( module_name, fromlist=[resolved_class_name]) resolved_class = getattr(module, resolved_class_name) else: resolved_class_name = module_class_list[0] resolved_class = getattr( sys.modules[__name__], resolved_class_name) return resolved_class except Exception as e: raise SerializationException( "Unable to resolve class {} from installed " "modules: {}".format(class_name, str(e)))
[ "def", "__load_class_from_name", "(", "self", ",", "class_name", ")", ":", "# type: (str) -> T", "try", ":", "module_class_list", "=", "class_name", ".", "rsplit", "(", "\".\"", ",", "1", ")", "if", "len", "(", "module_class_list", ")", ">", "1", ":", "modul...
Load the class from the ``class_name`` provided. Resolve the class name from the ``class_name`` provided, load the class on path and return the resolved class. If the module information is not provided in the ``class_name``, then look for the class on sys ``modules``. :param class_name: absolute class name to be loaded :type class_name: str :return: Resolved class reference :rtype: object :raises: :py:class:`ask_sdk_core.exceptions.SerializationException`
[ "Load", "the", "class", "from", "the", "class_name", "provided", "." ]
097b6406aa12d5ca0b825b00c936861b530cbf39
https://github.com/alexa/alexa-skills-kit-sdk-for-python/blob/097b6406aa12d5ca0b825b00c936861b530cbf39/ask-sdk-core/ask_sdk_core/serialize.py#L237-L268
234,339
alexa/alexa-skills-kit-sdk-for-python
ask-sdk-core/ask_sdk_core/serialize.py
DefaultSerializer.__deserialize_primitive
def __deserialize_primitive(self, payload, obj_type): # type: (str, Union[T, str]) -> Any """Deserialize primitive datatypes. :param payload: data to be deserialized :type payload: str :param obj_type: primitive datatype str :type obj_type: Union[object, str] :return: deserialized primitive datatype object :rtype: object :raises: :py:class:`ask_sdk_core.exceptions.SerializationException` """ obj_cast = cast(Any, obj_type) try: return obj_cast(payload) except UnicodeEncodeError: return unicode_type(payload) except TypeError: return payload except ValueError: raise SerializationException( "Failed to parse {} into '{}' object".format( payload, obj_cast.__name__))
python
def __deserialize_primitive(self, payload, obj_type): # type: (str, Union[T, str]) -> Any obj_cast = cast(Any, obj_type) try: return obj_cast(payload) except UnicodeEncodeError: return unicode_type(payload) except TypeError: return payload except ValueError: raise SerializationException( "Failed to parse {} into '{}' object".format( payload, obj_cast.__name__))
[ "def", "__deserialize_primitive", "(", "self", ",", "payload", ",", "obj_type", ")", ":", "# type: (str, Union[T, str]) -> Any", "obj_cast", "=", "cast", "(", "Any", ",", "obj_type", ")", "try", ":", "return", "obj_cast", "(", "payload", ")", "except", "UnicodeE...
Deserialize primitive datatypes. :param payload: data to be deserialized :type payload: str :param obj_type: primitive datatype str :type obj_type: Union[object, str] :return: deserialized primitive datatype object :rtype: object :raises: :py:class:`ask_sdk_core.exceptions.SerializationException`
[ "Deserialize", "primitive", "datatypes", "." ]
097b6406aa12d5ca0b825b00c936861b530cbf39
https://github.com/alexa/alexa-skills-kit-sdk-for-python/blob/097b6406aa12d5ca0b825b00c936861b530cbf39/ask-sdk-core/ask_sdk_core/serialize.py#L270-L292
234,340
alexa/alexa-skills-kit-sdk-for-python
ask-sdk-core/ask_sdk_core/serialize.py
DefaultSerializer.__deserialize_model
def __deserialize_model(self, payload, obj_type): # type: (str, Union[T, str]) -> Any """Deserialize instance to model object. :param payload: data to be deserialized :type payload: str :param obj_type: sdk model class :type obj_type: Union[object, str] :return: deserialized sdk model object :rtype: object :raises: :py:class:`ask_sdk_core.exceptions.SerializationException` """ try: obj_cast = cast(Any, obj_type) if issubclass(obj_cast, Enum): return obj_cast(payload) if hasattr(obj_cast, 'deserialized_types'): if hasattr(obj_cast, 'get_real_child_model'): obj_cast = self.__get_obj_by_discriminator( payload, obj_cast) class_deserialized_types = obj_cast.deserialized_types class_attribute_map = getattr(obj_cast, 'attribute_map', {}) class_attribute_map.update( { k: k for k in obj_cast.deserialized_types.keys() if k not in class_attribute_map } ) deserialized_model = obj_cast() for class_param_name, payload_param_name in iteritems( class_attribute_map): if payload_param_name in payload: setattr( deserialized_model, class_param_name, self.__deserialize( payload[payload_param_name], class_deserialized_types[class_param_name])) additional_params = [ param for param in payload if param not in class_attribute_map.values()] for add_param in additional_params: setattr(deserialized_model, add_param, payload[cast(Any,add_param)]) return deserialized_model else: return payload except Exception as e: raise SerializationException(str(e))
python
def __deserialize_model(self, payload, obj_type): # type: (str, Union[T, str]) -> Any try: obj_cast = cast(Any, obj_type) if issubclass(obj_cast, Enum): return obj_cast(payload) if hasattr(obj_cast, 'deserialized_types'): if hasattr(obj_cast, 'get_real_child_model'): obj_cast = self.__get_obj_by_discriminator( payload, obj_cast) class_deserialized_types = obj_cast.deserialized_types class_attribute_map = getattr(obj_cast, 'attribute_map', {}) class_attribute_map.update( { k: k for k in obj_cast.deserialized_types.keys() if k not in class_attribute_map } ) deserialized_model = obj_cast() for class_param_name, payload_param_name in iteritems( class_attribute_map): if payload_param_name in payload: setattr( deserialized_model, class_param_name, self.__deserialize( payload[payload_param_name], class_deserialized_types[class_param_name])) additional_params = [ param for param in payload if param not in class_attribute_map.values()] for add_param in additional_params: setattr(deserialized_model, add_param, payload[cast(Any,add_param)]) return deserialized_model else: return payload except Exception as e: raise SerializationException(str(e))
[ "def", "__deserialize_model", "(", "self", ",", "payload", ",", "obj_type", ")", ":", "# type: (str, Union[T, str]) -> Any", "try", ":", "obj_cast", "=", "cast", "(", "Any", ",", "obj_type", ")", "if", "issubclass", "(", "obj_cast", ",", "Enum", ")", ":", "r...
Deserialize instance to model object. :param payload: data to be deserialized :type payload: str :param obj_type: sdk model class :type obj_type: Union[object, str] :return: deserialized sdk model object :rtype: object :raises: :py:class:`ask_sdk_core.exceptions.SerializationException`
[ "Deserialize", "instance", "to", "model", "object", "." ]
097b6406aa12d5ca0b825b00c936861b530cbf39
https://github.com/alexa/alexa-skills-kit-sdk-for-python/blob/097b6406aa12d5ca0b825b00c936861b530cbf39/ask-sdk-core/ask_sdk_core/serialize.py#L322-L374
234,341
alexa/alexa-skills-kit-sdk-for-python
ask-sdk-core/ask_sdk_core/serialize.py
DefaultSerializer.__get_obj_by_discriminator
def __get_obj_by_discriminator(self, payload, obj_type): # type: (str, Union[T, str]) -> T """Get correct subclass instance using the discriminator in payload. :param payload: Payload for deserialization :type payload: str :param obj_type: parent class for deserializing payload into :type obj_type: Union[object, str] :return: Subclass of provided parent class, that resolves to the discriminator in payload. :rtype: object :raises: :py:class:`ask_sdk_core.exceptions.SerializationException` """ obj_cast = cast(Any, obj_type) namespaced_class_name = obj_cast.get_real_child_model(payload) if not namespaced_class_name: raise SerializationException( "Couldn't resolve object by discriminator type " "for {} class".format(obj_type)) return self.__load_class_from_name(namespaced_class_name)
python
def __get_obj_by_discriminator(self, payload, obj_type): # type: (str, Union[T, str]) -> T obj_cast = cast(Any, obj_type) namespaced_class_name = obj_cast.get_real_child_model(payload) if not namespaced_class_name: raise SerializationException( "Couldn't resolve object by discriminator type " "for {} class".format(obj_type)) return self.__load_class_from_name(namespaced_class_name)
[ "def", "__get_obj_by_discriminator", "(", "self", ",", "payload", ",", "obj_type", ")", ":", "# type: (str, Union[T, str]) -> T", "obj_cast", "=", "cast", "(", "Any", ",", "obj_type", ")", "namespaced_class_name", "=", "obj_cast", ".", "get_real_child_model", "(", "...
Get correct subclass instance using the discriminator in payload. :param payload: Payload for deserialization :type payload: str :param obj_type: parent class for deserializing payload into :type obj_type: Union[object, str] :return: Subclass of provided parent class, that resolves to the discriminator in payload. :rtype: object :raises: :py:class:`ask_sdk_core.exceptions.SerializationException`
[ "Get", "correct", "subclass", "instance", "using", "the", "discriminator", "in", "payload", "." ]
097b6406aa12d5ca0b825b00c936861b530cbf39
https://github.com/alexa/alexa-skills-kit-sdk-for-python/blob/097b6406aa12d5ca0b825b00c936861b530cbf39/ask-sdk-core/ask_sdk_core/serialize.py#L376-L397
234,342
alexa/alexa-skills-kit-sdk-for-python
ask-sdk-core/ask_sdk_core/attributes_manager.py
AttributesManager.persistent_attributes
def persistent_attributes(self): # type: () -> Dict[str, object] """Attributes stored at the Persistence level of the skill lifecycle. :return: persistent_attributes retrieved from persistence adapter :rtype: Dict[str, object] :raises: :py:class:`ask_sdk_core.exceptions.AttributesManagerException` if trying to get persistent attributes without persistence adapter """ if not self._persistence_adapter: raise AttributesManagerException( "Cannot get PersistentAttributes without Persistence adapter") if not self._persistent_attributes_set: self._persistence_attributes = ( self._persistence_adapter.get_attributes( request_envelope=self._request_envelope)) self._persistent_attributes_set = True return self._persistence_attributes
python
def persistent_attributes(self): # type: () -> Dict[str, object] if not self._persistence_adapter: raise AttributesManagerException( "Cannot get PersistentAttributes without Persistence adapter") if not self._persistent_attributes_set: self._persistence_attributes = ( self._persistence_adapter.get_attributes( request_envelope=self._request_envelope)) self._persistent_attributes_set = True return self._persistence_attributes
[ "def", "persistent_attributes", "(", "self", ")", ":", "# type: () -> Dict[str, object]", "if", "not", "self", ".", "_persistence_adapter", ":", "raise", "AttributesManagerException", "(", "\"Cannot get PersistentAttributes without Persistence adapter\"", ")", "if", "not", "s...
Attributes stored at the Persistence level of the skill lifecycle. :return: persistent_attributes retrieved from persistence adapter :rtype: Dict[str, object] :raises: :py:class:`ask_sdk_core.exceptions.AttributesManagerException` if trying to get persistent attributes without persistence adapter
[ "Attributes", "stored", "at", "the", "Persistence", "level", "of", "the", "skill", "lifecycle", "." ]
097b6406aa12d5ca0b825b00c936861b530cbf39
https://github.com/alexa/alexa-skills-kit-sdk-for-python/blob/097b6406aa12d5ca0b825b00c936861b530cbf39/ask-sdk-core/ask_sdk_core/attributes_manager.py#L165-L182
234,343
alexa/alexa-skills-kit-sdk-for-python
ask-sdk-core/ask_sdk_core/attributes_manager.py
AttributesManager.persistent_attributes
def persistent_attributes(self, persistent_attributes): # type: (Dict[str, object]) -> None """Overwrites and caches the persistent attributes value. Note that the persistent attributes will not be saved to persistence layer until the save_persistent_attributes method is called. :param persistent_attributes: attributes in persistence layer :type persistent_attributes: Dict[str, object] :raises: :py:class:`ask_sdk_core.exceptions.AttributesManagerException` if trying to set persistent attributes without persistence adapter """ if not self._persistence_adapter: raise AttributesManagerException( "Cannot set PersistentAttributes without persistence adapter!") self._persistence_attributes = persistent_attributes self._persistent_attributes_set = True
python
def persistent_attributes(self, persistent_attributes): # type: (Dict[str, object]) -> None if not self._persistence_adapter: raise AttributesManagerException( "Cannot set PersistentAttributes without persistence adapter!") self._persistence_attributes = persistent_attributes self._persistent_attributes_set = True
[ "def", "persistent_attributes", "(", "self", ",", "persistent_attributes", ")", ":", "# type: (Dict[str, object]) -> None", "if", "not", "self", ".", "_persistence_adapter", ":", "raise", "AttributesManagerException", "(", "\"Cannot set PersistentAttributes without persistence ad...
Overwrites and caches the persistent attributes value. Note that the persistent attributes will not be saved to persistence layer until the save_persistent_attributes method is called. :param persistent_attributes: attributes in persistence layer :type persistent_attributes: Dict[str, object] :raises: :py:class:`ask_sdk_core.exceptions.AttributesManagerException` if trying to set persistent attributes without persistence adapter
[ "Overwrites", "and", "caches", "the", "persistent", "attributes", "value", "." ]
097b6406aa12d5ca0b825b00c936861b530cbf39
https://github.com/alexa/alexa-skills-kit-sdk-for-python/blob/097b6406aa12d5ca0b825b00c936861b530cbf39/ask-sdk-core/ask_sdk_core/attributes_manager.py#L185-L202
234,344
alexa/alexa-skills-kit-sdk-for-python
ask-sdk-core/ask_sdk_core/attributes_manager.py
AttributesManager.save_persistent_attributes
def save_persistent_attributes(self): # type: () -> None """Save persistent attributes to the persistence layer if a persistence adapter is provided. :rtype: None :raises: :py:class:`ask_sdk_core.exceptions.AttributesManagerException` if trying to save persistence attributes without persistence adapter """ if not self._persistence_adapter: raise AttributesManagerException( "Cannot save PersistentAttributes without " "persistence adapter!") if self._persistent_attributes_set: self._persistence_adapter.save_attributes( request_envelope=self._request_envelope, attributes=self._persistence_attributes)
python
def save_persistent_attributes(self): # type: () -> None if not self._persistence_adapter: raise AttributesManagerException( "Cannot save PersistentAttributes without " "persistence adapter!") if self._persistent_attributes_set: self._persistence_adapter.save_attributes( request_envelope=self._request_envelope, attributes=self._persistence_attributes)
[ "def", "save_persistent_attributes", "(", "self", ")", ":", "# type: () -> None", "if", "not", "self", ".", "_persistence_adapter", ":", "raise", "AttributesManagerException", "(", "\"Cannot save PersistentAttributes without \"", "\"persistence adapter!\"", ")", "if", "self",...
Save persistent attributes to the persistence layer if a persistence adapter is provided. :rtype: None :raises: :py:class:`ask_sdk_core.exceptions.AttributesManagerException` if trying to save persistence attributes without persistence adapter
[ "Save", "persistent", "attributes", "to", "the", "persistence", "layer", "if", "a", "persistence", "adapter", "is", "provided", "." ]
097b6406aa12d5ca0b825b00c936861b530cbf39
https://github.com/alexa/alexa-skills-kit-sdk-for-python/blob/097b6406aa12d5ca0b825b00c936861b530cbf39/ask-sdk-core/ask_sdk_core/attributes_manager.py#L204-L220
234,345
alexa/alexa-skills-kit-sdk-for-python
ask-sdk-runtime/ask_sdk_runtime/utils.py
user_agent_info
def user_agent_info(sdk_version, custom_user_agent): # type: (str, str) -> str """Return the user agent info along with the SDK and Python Version information. :param sdk_version: Version of the SDK being used. :type sdk_version: str :param custom_user_agent: Custom User Agent string provided by the developer. :type custom_user_agent: str :return: User Agent Info string :rtype: str """ python_version = ".".join(str(x) for x in sys.version_info[0:3]) user_agent = "ask-python/{} Python/{}".format( sdk_version, python_version) if custom_user_agent is None: return user_agent else: return user_agent + " {}".format(custom_user_agent)
python
def user_agent_info(sdk_version, custom_user_agent): # type: (str, str) -> str python_version = ".".join(str(x) for x in sys.version_info[0:3]) user_agent = "ask-python/{} Python/{}".format( sdk_version, python_version) if custom_user_agent is None: return user_agent else: return user_agent + " {}".format(custom_user_agent)
[ "def", "user_agent_info", "(", "sdk_version", ",", "custom_user_agent", ")", ":", "# type: (str, str) -> str", "python_version", "=", "\".\"", ".", "join", "(", "str", "(", "x", ")", "for", "x", "in", "sys", ".", "version_info", "[", "0", ":", "3", "]", ")...
Return the user agent info along with the SDK and Python Version information. :param sdk_version: Version of the SDK being used. :type sdk_version: str :param custom_user_agent: Custom User Agent string provided by the developer. :type custom_user_agent: str :return: User Agent Info string :rtype: str
[ "Return", "the", "user", "agent", "info", "along", "with", "the", "SDK", "and", "Python", "Version", "information", "." ]
097b6406aa12d5ca0b825b00c936861b530cbf39
https://github.com/alexa/alexa-skills-kit-sdk-for-python/blob/097b6406aa12d5ca0b825b00c936861b530cbf39/ask-sdk-runtime/ask_sdk_runtime/utils.py#L20-L39
234,346
alexa/alexa-skills-kit-sdk-for-python
ask-sdk-dynamodb-persistence-adapter/ask_sdk_dynamodb/adapter.py
DynamoDbAdapter.get_attributes
def get_attributes(self, request_envelope): # type: (RequestEnvelope) -> Dict[str, object] """Get attributes from table in Dynamodb resource. Retrieves the attributes from Dynamodb table. If the table doesn't exist, returns an empty dict if the ``create_table`` variable is set as True, else it raises PersistenceException. Raises PersistenceException if `get_item` fails on the table. :param request_envelope: Request Envelope passed during skill invocation :type request_envelope: ask_sdk_model.RequestEnvelope :return: Attributes stored under the partition keygen mapping in the table :rtype: Dict[str, object] :raises: :py:class:`ask_sdk_core.exceptions.PersistenceException` """ try: table = self.dynamodb.Table(self.table_name) partition_key_val = self.partition_keygen(request_envelope) response = table.get_item( Key={self.partition_key_name: partition_key_val}, ConsistentRead=True) if "Item" in response: return response["Item"][self.attribute_name] else: return {} except ResourceNotExistsError: raise PersistenceException( "DynamoDb table {} doesn't exist or in the process of " "being created. Failed to get attributes from " "DynamoDb table.".format(self.table_name)) except Exception as e: raise PersistenceException( "Failed to retrieve attributes from DynamoDb table. " "Exception of type {} occurred: {}".format( type(e).__name__, str(e)))
python
def get_attributes(self, request_envelope): # type: (RequestEnvelope) -> Dict[str, object] try: table = self.dynamodb.Table(self.table_name) partition_key_val = self.partition_keygen(request_envelope) response = table.get_item( Key={self.partition_key_name: partition_key_val}, ConsistentRead=True) if "Item" in response: return response["Item"][self.attribute_name] else: return {} except ResourceNotExistsError: raise PersistenceException( "DynamoDb table {} doesn't exist or in the process of " "being created. Failed to get attributes from " "DynamoDb table.".format(self.table_name)) except Exception as e: raise PersistenceException( "Failed to retrieve attributes from DynamoDb table. " "Exception of type {} occurred: {}".format( type(e).__name__, str(e)))
[ "def", "get_attributes", "(", "self", ",", "request_envelope", ")", ":", "# type: (RequestEnvelope) -> Dict[str, object]", "try", ":", "table", "=", "self", ".", "dynamodb", ".", "Table", "(", "self", ".", "table_name", ")", "partition_key_val", "=", "self", ".", ...
Get attributes from table in Dynamodb resource. Retrieves the attributes from Dynamodb table. If the table doesn't exist, returns an empty dict if the ``create_table`` variable is set as True, else it raises PersistenceException. Raises PersistenceException if `get_item` fails on the table. :param request_envelope: Request Envelope passed during skill invocation :type request_envelope: ask_sdk_model.RequestEnvelope :return: Attributes stored under the partition keygen mapping in the table :rtype: Dict[str, object] :raises: :py:class:`ask_sdk_core.exceptions.PersistenceException`
[ "Get", "attributes", "from", "table", "in", "Dynamodb", "resource", "." ]
097b6406aa12d5ca0b825b00c936861b530cbf39
https://github.com/alexa/alexa-skills-kit-sdk-for-python/blob/097b6406aa12d5ca0b825b00c936861b530cbf39/ask-sdk-dynamodb-persistence-adapter/ask_sdk_dynamodb/adapter.py#L104-L141
234,347
alexa/alexa-skills-kit-sdk-for-python
ask-sdk-dynamodb-persistence-adapter/ask_sdk_dynamodb/adapter.py
DynamoDbAdapter.save_attributes
def save_attributes(self, request_envelope, attributes): # type: (RequestEnvelope, Dict[str, object]) -> None """Saves attributes to table in Dynamodb resource. Saves the attributes into Dynamodb table. Raises PersistenceException if table doesn't exist or ``put_item`` fails on the table. :param request_envelope: Request Envelope passed during skill invocation :type request_envelope: ask_sdk_model.RequestEnvelope :param attributes: Attributes stored under the partition keygen mapping in the table :type attributes: Dict[str, object] :rtype: None :raises: :py:class:`ask_sdk_core.exceptions.PersistenceException` """ try: table = self.dynamodb.Table(self.table_name) partition_key_val = self.partition_keygen(request_envelope) table.put_item( Item={self.partition_key_name: partition_key_val, self.attribute_name: attributes}) except ResourceNotExistsError: raise PersistenceException( "DynamoDb table {} doesn't exist. Failed to save attributes " "to DynamoDb table.".format( self.table_name)) except Exception as e: raise PersistenceException( "Failed to save attributes to DynamoDb table. Exception of " "type {} occurred: {}".format( type(e).__name__, str(e)))
python
def save_attributes(self, request_envelope, attributes): # type: (RequestEnvelope, Dict[str, object]) -> None try: table = self.dynamodb.Table(self.table_name) partition_key_val = self.partition_keygen(request_envelope) table.put_item( Item={self.partition_key_name: partition_key_val, self.attribute_name: attributes}) except ResourceNotExistsError: raise PersistenceException( "DynamoDb table {} doesn't exist. Failed to save attributes " "to DynamoDb table.".format( self.table_name)) except Exception as e: raise PersistenceException( "Failed to save attributes to DynamoDb table. Exception of " "type {} occurred: {}".format( type(e).__name__, str(e)))
[ "def", "save_attributes", "(", "self", ",", "request_envelope", ",", "attributes", ")", ":", "# type: (RequestEnvelope, Dict[str, object]) -> None", "try", ":", "table", "=", "self", ".", "dynamodb", ".", "Table", "(", "self", ".", "table_name", ")", "partition_key_...
Saves attributes to table in Dynamodb resource. Saves the attributes into Dynamodb table. Raises PersistenceException if table doesn't exist or ``put_item`` fails on the table. :param request_envelope: Request Envelope passed during skill invocation :type request_envelope: ask_sdk_model.RequestEnvelope :param attributes: Attributes stored under the partition keygen mapping in the table :type attributes: Dict[str, object] :rtype: None :raises: :py:class:`ask_sdk_core.exceptions.PersistenceException`
[ "Saves", "attributes", "to", "table", "in", "Dynamodb", "resource", "." ]
097b6406aa12d5ca0b825b00c936861b530cbf39
https://github.com/alexa/alexa-skills-kit-sdk-for-python/blob/097b6406aa12d5ca0b825b00c936861b530cbf39/ask-sdk-dynamodb-persistence-adapter/ask_sdk_dynamodb/adapter.py#L143-L175
234,348
alexa/alexa-skills-kit-sdk-for-python
ask-sdk-dynamodb-persistence-adapter/ask_sdk_dynamodb/adapter.py
DynamoDbAdapter.delete_attributes
def delete_attributes(self, request_envelope): # type: (RequestEnvelope) -> None """Deletes attributes from table in Dynamodb resource. Deletes the attributes from Dynamodb table. Raises PersistenceException if table doesn't exist or ``delete_item`` fails on the table. :param request_envelope: Request Envelope passed during skill invocation :type request_envelope: ask_sdk_model.RequestEnvelope :rtype: None :raises: :py:class:`ask_sdk_core.exceptions.PersistenceException` """ try: table = self.dynamodb.Table(self.table_name) partition_key_val = self.partition_keygen(request_envelope) table.delete_item( Key={self.partition_key_name: partition_key_val}) except ResourceNotExistsError: raise PersistenceException( "DynamoDb table {} doesn't exist. Failed to delete attributes " "from DynamoDb table.".format( self.table_name)) except Exception as e: raise PersistenceException( "Failed to delete attributes in DynamoDb table. Exception of " "type {} occurred: {}".format( type(e).__name__, str(e)))
python
def delete_attributes(self, request_envelope): # type: (RequestEnvelope) -> None try: table = self.dynamodb.Table(self.table_name) partition_key_val = self.partition_keygen(request_envelope) table.delete_item( Key={self.partition_key_name: partition_key_val}) except ResourceNotExistsError: raise PersistenceException( "DynamoDb table {} doesn't exist. Failed to delete attributes " "from DynamoDb table.".format( self.table_name)) except Exception as e: raise PersistenceException( "Failed to delete attributes in DynamoDb table. Exception of " "type {} occurred: {}".format( type(e).__name__, str(e)))
[ "def", "delete_attributes", "(", "self", ",", "request_envelope", ")", ":", "# type: (RequestEnvelope) -> None", "try", ":", "table", "=", "self", ".", "dynamodb", ".", "Table", "(", "self", ".", "table_name", ")", "partition_key_val", "=", "self", ".", "partiti...
Deletes attributes from table in Dynamodb resource. Deletes the attributes from Dynamodb table. Raises PersistenceException if table doesn't exist or ``delete_item`` fails on the table. :param request_envelope: Request Envelope passed during skill invocation :type request_envelope: ask_sdk_model.RequestEnvelope :rtype: None :raises: :py:class:`ask_sdk_core.exceptions.PersistenceException`
[ "Deletes", "attributes", "from", "table", "in", "Dynamodb", "resource", "." ]
097b6406aa12d5ca0b825b00c936861b530cbf39
https://github.com/alexa/alexa-skills-kit-sdk-for-python/blob/097b6406aa12d5ca0b825b00c936861b530cbf39/ask-sdk-dynamodb-persistence-adapter/ask_sdk_dynamodb/adapter.py#L177-L205
234,349
alexa/alexa-skills-kit-sdk-for-python
ask-sdk-dynamodb-persistence-adapter/ask_sdk_dynamodb/adapter.py
DynamoDbAdapter.__create_table_if_not_exists
def __create_table_if_not_exists(self): # type: () -> None """Creates table in Dynamodb resource if it doesn't exist and create_table is set as True. :rtype: None :raises: PersistenceException: When `create_table` fails on dynamodb resource. """ if self.create_table: try: self.dynamodb.create_table( TableName=self.table_name, KeySchema=[ { 'AttributeName': self.partition_key_name, 'KeyType': 'HASH' } ], AttributeDefinitions=[ { 'AttributeName': self.partition_key_name, 'AttributeType': 'S' } ], ProvisionedThroughput={ 'ReadCapacityUnits': 5, 'WriteCapacityUnits': 5 } ) except Exception as e: if e.__class__.__name__ != "ResourceInUseException": raise PersistenceException( "Create table if not exists request " "failed: Exception of type {} " "occurred: {}".format( type(e).__name__, str(e)))
python
def __create_table_if_not_exists(self): # type: () -> None if self.create_table: try: self.dynamodb.create_table( TableName=self.table_name, KeySchema=[ { 'AttributeName': self.partition_key_name, 'KeyType': 'HASH' } ], AttributeDefinitions=[ { 'AttributeName': self.partition_key_name, 'AttributeType': 'S' } ], ProvisionedThroughput={ 'ReadCapacityUnits': 5, 'WriteCapacityUnits': 5 } ) except Exception as e: if e.__class__.__name__ != "ResourceInUseException": raise PersistenceException( "Create table if not exists request " "failed: Exception of type {} " "occurred: {}".format( type(e).__name__, str(e)))
[ "def", "__create_table_if_not_exists", "(", "self", ")", ":", "# type: () -> None", "if", "self", ".", "create_table", ":", "try", ":", "self", ".", "dynamodb", ".", "create_table", "(", "TableName", "=", "self", ".", "table_name", ",", "KeySchema", "=", "[", ...
Creates table in Dynamodb resource if it doesn't exist and create_table is set as True. :rtype: None :raises: PersistenceException: When `create_table` fails on dynamodb resource.
[ "Creates", "table", "in", "Dynamodb", "resource", "if", "it", "doesn", "t", "exist", "and", "create_table", "is", "set", "as", "True", "." ]
097b6406aa12d5ca0b825b00c936861b530cbf39
https://github.com/alexa/alexa-skills-kit-sdk-for-python/blob/097b6406aa12d5ca0b825b00c936861b530cbf39/ask-sdk-dynamodb-persistence-adapter/ask_sdk_dynamodb/adapter.py#L207-L244
234,350
alexa/alexa-skills-kit-sdk-for-python
ask-sdk-runtime/ask_sdk_runtime/skill.py
RuntimeConfigurationBuilder.add_request_handler
def add_request_handler(self, request_handler): # type: (AbstractRequestHandler) -> None """Register input to the request handlers list. :param request_handler: Request Handler instance to be registered. :type request_handler: AbstractRequestHandler :return: None """ if request_handler is None: raise RuntimeConfigException( "Valid Request Handler instance to be provided") if not isinstance(request_handler, AbstractRequestHandler): raise RuntimeConfigException( "Input should be a RequestHandler instance") self.request_handler_chains.append(GenericRequestHandlerChain( request_handler=request_handler))
python
def add_request_handler(self, request_handler): # type: (AbstractRequestHandler) -> None if request_handler is None: raise RuntimeConfigException( "Valid Request Handler instance to be provided") if not isinstance(request_handler, AbstractRequestHandler): raise RuntimeConfigException( "Input should be a RequestHandler instance") self.request_handler_chains.append(GenericRequestHandlerChain( request_handler=request_handler))
[ "def", "add_request_handler", "(", "self", ",", "request_handler", ")", ":", "# type: (AbstractRequestHandler) -> None", "if", "request_handler", "is", "None", ":", "raise", "RuntimeConfigException", "(", "\"Valid Request Handler instance to be provided\"", ")", "if", "not", ...
Register input to the request handlers list. :param request_handler: Request Handler instance to be registered. :type request_handler: AbstractRequestHandler :return: None
[ "Register", "input", "to", "the", "request", "handlers", "list", "." ]
097b6406aa12d5ca0b825b00c936861b530cbf39
https://github.com/alexa/alexa-skills-kit-sdk-for-python/blob/097b6406aa12d5ca0b825b00c936861b530cbf39/ask-sdk-runtime/ask_sdk_runtime/skill.py#L108-L126
234,351
alexa/alexa-skills-kit-sdk-for-python
ask-sdk-runtime/ask_sdk_runtime/skill.py
RuntimeConfigurationBuilder.add_exception_handler
def add_exception_handler(self, exception_handler): # type: (AbstractExceptionHandler) -> None """Register input to the exception handlers list. :param exception_handler: Exception Handler instance to be registered. :type exception_handler: AbstractExceptionHandler :return: None """ if exception_handler is None: raise RuntimeConfigException( "Valid Exception Handler instance to be provided") if not isinstance(exception_handler, AbstractExceptionHandler): raise RuntimeConfigException( "Input should be an ExceptionHandler instance") self.exception_handlers.append(exception_handler)
python
def add_exception_handler(self, exception_handler): # type: (AbstractExceptionHandler) -> None if exception_handler is None: raise RuntimeConfigException( "Valid Exception Handler instance to be provided") if not isinstance(exception_handler, AbstractExceptionHandler): raise RuntimeConfigException( "Input should be an ExceptionHandler instance") self.exception_handlers.append(exception_handler)
[ "def", "add_exception_handler", "(", "self", ",", "exception_handler", ")", ":", "# type: (AbstractExceptionHandler) -> None", "if", "exception_handler", "is", "None", ":", "raise", "RuntimeConfigException", "(", "\"Valid Exception Handler instance to be provided\"", ")", "if",...
Register input to the exception handlers list. :param exception_handler: Exception Handler instance to be registered. :type exception_handler: AbstractExceptionHandler :return: None
[ "Register", "input", "to", "the", "exception", "handlers", "list", "." ]
097b6406aa12d5ca0b825b00c936861b530cbf39
https://github.com/alexa/alexa-skills-kit-sdk-for-python/blob/097b6406aa12d5ca0b825b00c936861b530cbf39/ask-sdk-runtime/ask_sdk_runtime/skill.py#L140-L157
234,352
alexa/alexa-skills-kit-sdk-for-python
ask-sdk-runtime/ask_sdk_runtime/skill.py
RuntimeConfigurationBuilder.add_global_request_interceptor
def add_global_request_interceptor(self, request_interceptor): # type: (AbstractRequestInterceptor) -> None """Register input to the global request interceptors list. :param request_interceptor: Request Interceptor instance to be registered. :type request_interceptor: AbstractRequestInterceptor :return: None """ if request_interceptor is None: raise RuntimeConfigException( "Valid Request Interceptor instance to be provided") if not isinstance(request_interceptor, AbstractRequestInterceptor): raise RuntimeConfigException( "Input should be a RequestInterceptor instance") self.global_request_interceptors.append(request_interceptor)
python
def add_global_request_interceptor(self, request_interceptor): # type: (AbstractRequestInterceptor) -> None if request_interceptor is None: raise RuntimeConfigException( "Valid Request Interceptor instance to be provided") if not isinstance(request_interceptor, AbstractRequestInterceptor): raise RuntimeConfigException( "Input should be a RequestInterceptor instance") self.global_request_interceptors.append(request_interceptor)
[ "def", "add_global_request_interceptor", "(", "self", ",", "request_interceptor", ")", ":", "# type: (AbstractRequestInterceptor) -> None", "if", "request_interceptor", "is", "None", ":", "raise", "RuntimeConfigException", "(", "\"Valid Request Interceptor instance to be provided\"...
Register input to the global request interceptors list. :param request_interceptor: Request Interceptor instance to be registered. :type request_interceptor: AbstractRequestInterceptor :return: None
[ "Register", "input", "to", "the", "global", "request", "interceptors", "list", "." ]
097b6406aa12d5ca0b825b00c936861b530cbf39
https://github.com/alexa/alexa-skills-kit-sdk-for-python/blob/097b6406aa12d5ca0b825b00c936861b530cbf39/ask-sdk-runtime/ask_sdk_runtime/skill.py#L159-L176
234,353
alexa/alexa-skills-kit-sdk-for-python
ask-sdk-runtime/ask_sdk_runtime/skill.py
RuntimeConfigurationBuilder.add_global_response_interceptor
def add_global_response_interceptor(self, response_interceptor): # type: (AbstractResponseInterceptor) -> None """Register input to the global response interceptors list. :param response_interceptor: Response Interceptor instance to be registered. :type response_interceptor: AbstractResponseInterceptor :return: None """ if response_interceptor is None: raise RuntimeConfigException( "Valid Response Interceptor instance to be provided") if not isinstance(response_interceptor, AbstractResponseInterceptor): raise RuntimeConfigException( "Input should be a ResponseInterceptor instance") self.global_response_interceptors.append(response_interceptor)
python
def add_global_response_interceptor(self, response_interceptor): # type: (AbstractResponseInterceptor) -> None if response_interceptor is None: raise RuntimeConfigException( "Valid Response Interceptor instance to be provided") if not isinstance(response_interceptor, AbstractResponseInterceptor): raise RuntimeConfigException( "Input should be a ResponseInterceptor instance") self.global_response_interceptors.append(response_interceptor)
[ "def", "add_global_response_interceptor", "(", "self", ",", "response_interceptor", ")", ":", "# type: (AbstractResponseInterceptor) -> None", "if", "response_interceptor", "is", "None", ":", "raise", "RuntimeConfigException", "(", "\"Valid Response Interceptor instance to be provi...
Register input to the global response interceptors list. :param response_interceptor: Response Interceptor instance to be registered. :type response_interceptor: AbstractResponseInterceptor :return: None
[ "Register", "input", "to", "the", "global", "response", "interceptors", "list", "." ]
097b6406aa12d5ca0b825b00c936861b530cbf39
https://github.com/alexa/alexa-skills-kit-sdk-for-python/blob/097b6406aa12d5ca0b825b00c936861b530cbf39/ask-sdk-runtime/ask_sdk_runtime/skill.py#L178-L195
234,354
alexa/alexa-skills-kit-sdk-for-python
ask-sdk-runtime/ask_sdk_runtime/skill.py
RuntimeConfigurationBuilder.get_runtime_configuration
def get_runtime_configuration(self): # type: () -> RuntimeConfiguration """Build the runtime configuration object from the registered components. :return: Runtime Configuration Object :rtype: RuntimeConfiguration """ request_mapper = GenericRequestMapper( request_handler_chains=self.request_handler_chains) exception_mapper = GenericExceptionMapper( exception_handlers=self.exception_handlers) handler_adapter = GenericHandlerAdapter() runtime_configuration = RuntimeConfiguration( request_mappers=[request_mapper], handler_adapters=[handler_adapter], exception_mapper=exception_mapper, request_interceptors=self.global_request_interceptors, response_interceptors=self.global_response_interceptors) return runtime_configuration
python
def get_runtime_configuration(self): # type: () -> RuntimeConfiguration request_mapper = GenericRequestMapper( request_handler_chains=self.request_handler_chains) exception_mapper = GenericExceptionMapper( exception_handlers=self.exception_handlers) handler_adapter = GenericHandlerAdapter() runtime_configuration = RuntimeConfiguration( request_mappers=[request_mapper], handler_adapters=[handler_adapter], exception_mapper=exception_mapper, request_interceptors=self.global_request_interceptors, response_interceptors=self.global_response_interceptors) return runtime_configuration
[ "def", "get_runtime_configuration", "(", "self", ")", ":", "# type: () -> RuntimeConfiguration", "request_mapper", "=", "GenericRequestMapper", "(", "request_handler_chains", "=", "self", ".", "request_handler_chains", ")", "exception_mapper", "=", "GenericExceptionMapper", "...
Build the runtime configuration object from the registered components. :return: Runtime Configuration Object :rtype: RuntimeConfiguration
[ "Build", "the", "runtime", "configuration", "object", "from", "the", "registered", "components", "." ]
097b6406aa12d5ca0b825b00c936861b530cbf39
https://github.com/alexa/alexa-skills-kit-sdk-for-python/blob/097b6406aa12d5ca0b825b00c936861b530cbf39/ask-sdk-runtime/ask_sdk_runtime/skill.py#L197-L218
234,355
alexa/alexa-skills-kit-sdk-for-python
ask-sdk-dynamodb-persistence-adapter/ask_sdk_dynamodb/partition_keygen.py
user_id_partition_keygen
def user_id_partition_keygen(request_envelope): # type: (RequestEnvelope) -> str """Retrieve user id from request envelope, to use as partition key. :param request_envelope: Request Envelope passed during skill invocation :type request_envelope: ask_sdk_model.RequestEnvelope :return: User Id retrieved from request envelope :rtype: str :raises: :py:class:`ask_sdk_core.exceptions.PersistenceException` """ try: user_id = request_envelope.context.system.user.user_id return user_id except AttributeError: raise PersistenceException("Couldn't retrieve user id from request " "envelope, for partition key use")
python
def user_id_partition_keygen(request_envelope): # type: (RequestEnvelope) -> str try: user_id = request_envelope.context.system.user.user_id return user_id except AttributeError: raise PersistenceException("Couldn't retrieve user id from request " "envelope, for partition key use")
[ "def", "user_id_partition_keygen", "(", "request_envelope", ")", ":", "# type: (RequestEnvelope) -> str", "try", ":", "user_id", "=", "request_envelope", ".", "context", ".", "system", ".", "user", ".", "user_id", "return", "user_id", "except", "AttributeError", ":", ...
Retrieve user id from request envelope, to use as partition key. :param request_envelope: Request Envelope passed during skill invocation :type request_envelope: ask_sdk_model.RequestEnvelope :return: User Id retrieved from request envelope :rtype: str :raises: :py:class:`ask_sdk_core.exceptions.PersistenceException`
[ "Retrieve", "user", "id", "from", "request", "envelope", "to", "use", "as", "partition", "key", "." ]
097b6406aa12d5ca0b825b00c936861b530cbf39
https://github.com/alexa/alexa-skills-kit-sdk-for-python/blob/097b6406aa12d5ca0b825b00c936861b530cbf39/ask-sdk-dynamodb-persistence-adapter/ask_sdk_dynamodb/partition_keygen.py#L26-L42
234,356
alexa/alexa-skills-kit-sdk-for-python
ask-sdk-dynamodb-persistence-adapter/ask_sdk_dynamodb/partition_keygen.py
device_id_partition_keygen
def device_id_partition_keygen(request_envelope): # type: (RequestEnvelope) -> str """Retrieve device id from request envelope, to use as partition key. :param request_envelope: Request Envelope passed during skill invocation :type request_envelope: ask_sdk_model.RequestEnvelope :return: Device Id retrieved from request envelope :rtype: str :raises: :py:class:`ask_sdk_core.exceptions.PersistenceException` """ try: device_id = request_envelope.context.system.device.device_id return device_id except AttributeError: raise PersistenceException("Couldn't retrieve device id from " "request envelope, for partition key use")
python
def device_id_partition_keygen(request_envelope): # type: (RequestEnvelope) -> str try: device_id = request_envelope.context.system.device.device_id return device_id except AttributeError: raise PersistenceException("Couldn't retrieve device id from " "request envelope, for partition key use")
[ "def", "device_id_partition_keygen", "(", "request_envelope", ")", ":", "# type: (RequestEnvelope) -> str", "try", ":", "device_id", "=", "request_envelope", ".", "context", ".", "system", ".", "device", ".", "device_id", "return", "device_id", "except", "AttributeError...
Retrieve device id from request envelope, to use as partition key. :param request_envelope: Request Envelope passed during skill invocation :type request_envelope: ask_sdk_model.RequestEnvelope :return: Device Id retrieved from request envelope :rtype: str :raises: :py:class:`ask_sdk_core.exceptions.PersistenceException`
[ "Retrieve", "device", "id", "from", "request", "envelope", "to", "use", "as", "partition", "key", "." ]
097b6406aa12d5ca0b825b00c936861b530cbf39
https://github.com/alexa/alexa-skills-kit-sdk-for-python/blob/097b6406aa12d5ca0b825b00c936861b530cbf39/ask-sdk-dynamodb-persistence-adapter/ask_sdk_dynamodb/partition_keygen.py#L45-L61
234,357
alexa/alexa-skills-kit-sdk-for-python
ask-sdk-core/ask_sdk_core/utils/predicate.py
is_canfulfill_intent_name
def is_canfulfill_intent_name(name): # type: (str) -> Callable[[HandlerInput], bool] """A predicate function returning a boolean, when name matches the intent name in a CanFulfill Intent Request. The function can be applied on a :py:class:`ask_sdk_core.handler_input.HandlerInput`, to check if the input is of :py:class:`ask_sdk_model.intent_request.CanFulfillIntentRequest` type and if the name of the request matches with the passed name. :param name: Name to be matched with the CanFulfill Intent Request Name :type name: str :return: Predicate function that can be used to check name of the request :rtype: Callable[[HandlerInput], bool] """ def can_handle_wrapper(handler_input): # type: (HandlerInput) -> bool return (isinstance( handler_input.request_envelope.request, CanFulfillIntentRequest) and handler_input.request_envelope.request.intent.name == name) return can_handle_wrapper
python
def is_canfulfill_intent_name(name): # type: (str) -> Callable[[HandlerInput], bool] def can_handle_wrapper(handler_input): # type: (HandlerInput) -> bool return (isinstance( handler_input.request_envelope.request, CanFulfillIntentRequest) and handler_input.request_envelope.request.intent.name == name) return can_handle_wrapper
[ "def", "is_canfulfill_intent_name", "(", "name", ")", ":", "# type: (str) -> Callable[[HandlerInput], bool]", "def", "can_handle_wrapper", "(", "handler_input", ")", ":", "# type: (HandlerInput) -> bool", "return", "(", "isinstance", "(", "handler_input", ".", "request_envelo...
A predicate function returning a boolean, when name matches the intent name in a CanFulfill Intent Request. The function can be applied on a :py:class:`ask_sdk_core.handler_input.HandlerInput`, to check if the input is of :py:class:`ask_sdk_model.intent_request.CanFulfillIntentRequest` type and if the name of the request matches with the passed name. :param name: Name to be matched with the CanFulfill Intent Request Name :type name: str :return: Predicate function that can be used to check name of the request :rtype: Callable[[HandlerInput], bool]
[ "A", "predicate", "function", "returning", "a", "boolean", "when", "name", "matches", "the", "intent", "name", "in", "a", "CanFulfill", "Intent", "Request", "." ]
097b6406aa12d5ca0b825b00c936861b530cbf39
https://github.com/alexa/alexa-skills-kit-sdk-for-python/blob/097b6406aa12d5ca0b825b00c936861b530cbf39/ask-sdk-core/ask_sdk_core/utils/predicate.py#L28-L50
234,358
alexa/alexa-skills-kit-sdk-for-python
ask-sdk-core/ask_sdk_core/utils/predicate.py
is_intent_name
def is_intent_name(name): # type: (str) -> Callable[[HandlerInput], bool] """A predicate function returning a boolean, when name matches the name in Intent Request. The function can be applied on a :py:class:`ask_sdk_core.handler_input.HandlerInput`, to check if the input is of :py:class:`ask_sdk_model.intent_request.IntentRequest` type and if the name of the request matches with the passed name. :param name: Name to be matched with the Intent Request Name :type name: str :return: Predicate function that can be used to check name of the request :rtype: Callable[[HandlerInput], bool] """ def can_handle_wrapper(handler_input): # type: (HandlerInput) -> bool return (isinstance( handler_input.request_envelope.request, IntentRequest) and handler_input.request_envelope.request.intent.name == name) return can_handle_wrapper
python
def is_intent_name(name): # type: (str) -> Callable[[HandlerInput], bool] def can_handle_wrapper(handler_input): # type: (HandlerInput) -> bool return (isinstance( handler_input.request_envelope.request, IntentRequest) and handler_input.request_envelope.request.intent.name == name) return can_handle_wrapper
[ "def", "is_intent_name", "(", "name", ")", ":", "# type: (str) -> Callable[[HandlerInput], bool]", "def", "can_handle_wrapper", "(", "handler_input", ")", ":", "# type: (HandlerInput) -> bool", "return", "(", "isinstance", "(", "handler_input", ".", "request_envelope", ".",...
A predicate function returning a boolean, when name matches the name in Intent Request. The function can be applied on a :py:class:`ask_sdk_core.handler_input.HandlerInput`, to check if the input is of :py:class:`ask_sdk_model.intent_request.IntentRequest` type and if the name of the request matches with the passed name. :param name: Name to be matched with the Intent Request Name :type name: str :return: Predicate function that can be used to check name of the request :rtype: Callable[[HandlerInput], bool]
[ "A", "predicate", "function", "returning", "a", "boolean", "when", "name", "matches", "the", "name", "in", "Intent", "Request", "." ]
097b6406aa12d5ca0b825b00c936861b530cbf39
https://github.com/alexa/alexa-skills-kit-sdk-for-python/blob/097b6406aa12d5ca0b825b00c936861b530cbf39/ask-sdk-core/ask_sdk_core/utils/predicate.py#L53-L75
234,359
alexa/alexa-skills-kit-sdk-for-python
ask-sdk-core/ask_sdk_core/utils/predicate.py
is_request_type
def is_request_type(request_type): # type: (str) -> Callable[[HandlerInput], bool] """A predicate function returning a boolean, when request type is the passed-in type. The function can be applied on a :py:class:`ask_sdk_core.handler_input.HandlerInput`, to check if the input request type is the passed in request type. :param request_type: request type to be matched with the input's request :type request_type: str :return: Predicate function that can be used to check the type of the request :rtype: Callable[[HandlerInput], bool] """ def can_handle_wrapper(handler_input): # type: (HandlerInput) -> bool return (handler_input.request_envelope.request.object_type == request_type) return can_handle_wrapper
python
def is_request_type(request_type): # type: (str) -> Callable[[HandlerInput], bool] def can_handle_wrapper(handler_input): # type: (HandlerInput) -> bool return (handler_input.request_envelope.request.object_type == request_type) return can_handle_wrapper
[ "def", "is_request_type", "(", "request_type", ")", ":", "# type: (str) -> Callable[[HandlerInput], bool]", "def", "can_handle_wrapper", "(", "handler_input", ")", ":", "# type: (HandlerInput) -> bool", "return", "(", "handler_input", ".", "request_envelope", ".", "request", ...
A predicate function returning a boolean, when request type is the passed-in type. The function can be applied on a :py:class:`ask_sdk_core.handler_input.HandlerInput`, to check if the input request type is the passed in request type. :param request_type: request type to be matched with the input's request :type request_type: str :return: Predicate function that can be used to check the type of the request :rtype: Callable[[HandlerInput], bool]
[ "A", "predicate", "function", "returning", "a", "boolean", "when", "request", "type", "is", "the", "passed", "-", "in", "type", "." ]
097b6406aa12d5ca0b825b00c936861b530cbf39
https://github.com/alexa/alexa-skills-kit-sdk-for-python/blob/097b6406aa12d5ca0b825b00c936861b530cbf39/ask-sdk-core/ask_sdk_core/utils/predicate.py#L78-L97
234,360
alexa/alexa-skills-kit-sdk-for-python
ask-sdk-core/ask_sdk_core/api_client.py
DefaultApiClient.invoke
def invoke(self, request): # type: (ApiClientRequest) -> ApiClientResponse """Dispatches a request to an API endpoint described in the request. Resolves the method from input request object, converts the list of header tuples to the required format (dict) for the `requests` lib call and invokes the method with corresponding parameters on `requests` library. The response from the call is wrapped under the `ApiClientResponse` object and the responsibility of translating a response code and response/ error lies with the caller. :param request: Request to dispatch to the ApiClient :type request: ApiClientRequest :return: Response from the client call :rtype: ApiClientResponse :raises: :py:class:`ask_sdk_core.exceptions.ApiClientException` """ try: http_method = self._resolve_method(request) http_headers = self._convert_list_tuples_to_dict( headers_list=request.headers) parsed_url = parse_url(request.url) if parsed_url.scheme is None or parsed_url.scheme != "https": raise ApiClientException( "Requests against non-HTTPS endpoints are not allowed.") if request.body: body_content_type = http_headers.get("Content-type", None) if (body_content_type is not None and "json" in body_content_type): raw_data = json.dumps(request.body) else: raw_data = request.body else: raw_data = None http_response = http_method( url=request.url, headers=http_headers, data=raw_data) return ApiClientResponse( headers=self._convert_dict_to_list_tuples( http_response.headers), status_code=http_response.status_code, body=http_response.text) except Exception as e: raise ApiClientException( "Error executing the request: {}".format(str(e)))
python
def invoke(self, request): # type: (ApiClientRequest) -> ApiClientResponse try: http_method = self._resolve_method(request) http_headers = self._convert_list_tuples_to_dict( headers_list=request.headers) parsed_url = parse_url(request.url) if parsed_url.scheme is None or parsed_url.scheme != "https": raise ApiClientException( "Requests against non-HTTPS endpoints are not allowed.") if request.body: body_content_type = http_headers.get("Content-type", None) if (body_content_type is not None and "json" in body_content_type): raw_data = json.dumps(request.body) else: raw_data = request.body else: raw_data = None http_response = http_method( url=request.url, headers=http_headers, data=raw_data) return ApiClientResponse( headers=self._convert_dict_to_list_tuples( http_response.headers), status_code=http_response.status_code, body=http_response.text) except Exception as e: raise ApiClientException( "Error executing the request: {}".format(str(e)))
[ "def", "invoke", "(", "self", ",", "request", ")", ":", "# type: (ApiClientRequest) -> ApiClientResponse", "try", ":", "http_method", "=", "self", ".", "_resolve_method", "(", "request", ")", "http_headers", "=", "self", ".", "_convert_list_tuples_to_dict", "(", "he...
Dispatches a request to an API endpoint described in the request. Resolves the method from input request object, converts the list of header tuples to the required format (dict) for the `requests` lib call and invokes the method with corresponding parameters on `requests` library. The response from the call is wrapped under the `ApiClientResponse` object and the responsibility of translating a response code and response/ error lies with the caller. :param request: Request to dispatch to the ApiClient :type request: ApiClientRequest :return: Response from the client call :rtype: ApiClientResponse :raises: :py:class:`ask_sdk_core.exceptions.ApiClientException`
[ "Dispatches", "a", "request", "to", "an", "API", "endpoint", "described", "in", "the", "request", "." ]
097b6406aa12d5ca0b825b00c936861b530cbf39
https://github.com/alexa/alexa-skills-kit-sdk-for-python/blob/097b6406aa12d5ca0b825b00c936861b530cbf39/ask-sdk-core/ask_sdk_core/api_client.py#L40-L89
234,361
alexa/alexa-skills-kit-sdk-for-python
ask-sdk-core/ask_sdk_core/api_client.py
DefaultApiClient._resolve_method
def _resolve_method(self, request): # type: (ApiClientRequest) -> Callable """Resolve the method from request object to `requests` http call. :param request: Request to dispatch to the ApiClient :type request: ApiClientRequest :return: The HTTP method that maps to the request call. :rtype: Callable :raises :py:class:`ask_sdk_core.exceptions.ApiClientException` if invalid http request method is being called """ try: return getattr(requests, request.method.lower()) except AttributeError: raise ApiClientException( "Invalid request method: {}".format(request.method))
python
def _resolve_method(self, request): # type: (ApiClientRequest) -> Callable try: return getattr(requests, request.method.lower()) except AttributeError: raise ApiClientException( "Invalid request method: {}".format(request.method))
[ "def", "_resolve_method", "(", "self", ",", "request", ")", ":", "# type: (ApiClientRequest) -> Callable", "try", ":", "return", "getattr", "(", "requests", ",", "request", ".", "method", ".", "lower", "(", ")", ")", "except", "AttributeError", ":", "raise", "...
Resolve the method from request object to `requests` http call. :param request: Request to dispatch to the ApiClient :type request: ApiClientRequest :return: The HTTP method that maps to the request call. :rtype: Callable :raises :py:class:`ask_sdk_core.exceptions.ApiClientException` if invalid http request method is being called
[ "Resolve", "the", "method", "from", "request", "object", "to", "requests", "http", "call", "." ]
097b6406aa12d5ca0b825b00c936861b530cbf39
https://github.com/alexa/alexa-skills-kit-sdk-for-python/blob/097b6406aa12d5ca0b825b00c936861b530cbf39/ask-sdk-core/ask_sdk_core/api_client.py#L91-L107
234,362
alexa/alexa-skills-kit-sdk-for-python
ask-sdk-core/ask_sdk_core/api_client.py
DefaultApiClient._convert_list_tuples_to_dict
def _convert_list_tuples_to_dict(self, headers_list): # type: (List[Tuple[str, str]]) -> Dict[str, str] """Convert list of tuples from headers of request object to dictionary format. :param headers_list: List of tuples made up of two element strings from `ApiClientRequest` headers variable :type headers_list: List[Tuple[str, str]] :return: Dictionary of headers in keys as strings and values as comma separated strings :rtype: Dict[str, str] """ headers_dict = {} # type: Dict if headers_list is not None: for header_tuple in headers_list: key, value = header_tuple[0], header_tuple[1] if key in headers_dict: headers_dict[key] = "{}, {}".format( headers_dict[key], value) else: headers_dict[header_tuple[0]] = value return headers_dict
python
def _convert_list_tuples_to_dict(self, headers_list): # type: (List[Tuple[str, str]]) -> Dict[str, str] headers_dict = {} # type: Dict if headers_list is not None: for header_tuple in headers_list: key, value = header_tuple[0], header_tuple[1] if key in headers_dict: headers_dict[key] = "{}, {}".format( headers_dict[key], value) else: headers_dict[header_tuple[0]] = value return headers_dict
[ "def", "_convert_list_tuples_to_dict", "(", "self", ",", "headers_list", ")", ":", "# type: (List[Tuple[str, str]]) -> Dict[str, str]", "headers_dict", "=", "{", "}", "# type: Dict", "if", "headers_list", "is", "not", "None", ":", "for", "header_tuple", "in", "headers_l...
Convert list of tuples from headers of request object to dictionary format. :param headers_list: List of tuples made up of two element strings from `ApiClientRequest` headers variable :type headers_list: List[Tuple[str, str]] :return: Dictionary of headers in keys as strings and values as comma separated strings :rtype: Dict[str, str]
[ "Convert", "list", "of", "tuples", "from", "headers", "of", "request", "object", "to", "dictionary", "format", "." ]
097b6406aa12d5ca0b825b00c936861b530cbf39
https://github.com/alexa/alexa-skills-kit-sdk-for-python/blob/097b6406aa12d5ca0b825b00c936861b530cbf39/ask-sdk-core/ask_sdk_core/api_client.py#L109-L130
234,363
alexa/alexa-skills-kit-sdk-for-python
ask-sdk-core/ask_sdk_core/api_client.py
DefaultApiClient._convert_dict_to_list_tuples
def _convert_dict_to_list_tuples(self, headers_dict): # type: (Dict[str, str]) -> List[Tuple[str, str]] """Convert headers dict to list of string tuples format for `ApiClientResponse` headers variable. :param headers_dict: Dictionary of headers in keys as strings and values as comma separated strings :type headers_dict: Dict[str, str] :return: List of tuples made up of two element strings from headers of client response :rtype: List[Tuple[str, str]] """ headers_list = [] if headers_dict is not None: for key, values in six.iteritems(headers_dict): for value in values.split(","): value = value.strip() if value is not None and value is not '': headers_list.append((key, value.strip())) return headers_list
python
def _convert_dict_to_list_tuples(self, headers_dict): # type: (Dict[str, str]) -> List[Tuple[str, str]] headers_list = [] if headers_dict is not None: for key, values in six.iteritems(headers_dict): for value in values.split(","): value = value.strip() if value is not None and value is not '': headers_list.append((key, value.strip())) return headers_list
[ "def", "_convert_dict_to_list_tuples", "(", "self", ",", "headers_dict", ")", ":", "# type: (Dict[str, str]) -> List[Tuple[str, str]]", "headers_list", "=", "[", "]", "if", "headers_dict", "is", "not", "None", ":", "for", "key", ",", "values", "in", "six", ".", "i...
Convert headers dict to list of string tuples format for `ApiClientResponse` headers variable. :param headers_dict: Dictionary of headers in keys as strings and values as comma separated strings :type headers_dict: Dict[str, str] :return: List of tuples made up of two element strings from headers of client response :rtype: List[Tuple[str, str]]
[ "Convert", "headers", "dict", "to", "list", "of", "string", "tuples", "format", "for", "ApiClientResponse", "headers", "variable", "." ]
097b6406aa12d5ca0b825b00c936861b530cbf39
https://github.com/alexa/alexa-skills-kit-sdk-for-python/blob/097b6406aa12d5ca0b825b00c936861b530cbf39/ask-sdk-core/ask_sdk_core/api_client.py#L132-L151
234,364
alexa/alexa-skills-kit-sdk-for-python
ask-sdk-runtime/ask_sdk_runtime/dispatch_components/request_components.py
GenericRequestMapper.add_request_handler_chain
def add_request_handler_chain(self, request_handler_chain): # type: (GenericRequestHandlerChain) -> None """Checks the type before adding it to the request_handler_chains instance variable. :param request_handler_chain: Request Handler Chain instance. :type request_handler_chain: RequestHandlerChain :raises: :py:class:`ask_sdk_runtime.exceptions.DispatchException` if a null input is provided or if the input is of invalid type """ if request_handler_chain is None or not isinstance( request_handler_chain, GenericRequestHandlerChain): raise DispatchException( "Request Handler Chain is not a GenericRequestHandlerChain " "instance") self._request_handler_chains.append(request_handler_chain)
python
def add_request_handler_chain(self, request_handler_chain): # type: (GenericRequestHandlerChain) -> None if request_handler_chain is None or not isinstance( request_handler_chain, GenericRequestHandlerChain): raise DispatchException( "Request Handler Chain is not a GenericRequestHandlerChain " "instance") self._request_handler_chains.append(request_handler_chain)
[ "def", "add_request_handler_chain", "(", "self", ",", "request_handler_chain", ")", ":", "# type: (GenericRequestHandlerChain) -> None", "if", "request_handler_chain", "is", "None", "or", "not", "isinstance", "(", "request_handler_chain", ",", "GenericRequestHandlerChain", ")...
Checks the type before adding it to the request_handler_chains instance variable. :param request_handler_chain: Request Handler Chain instance. :type request_handler_chain: RequestHandlerChain :raises: :py:class:`ask_sdk_runtime.exceptions.DispatchException` if a null input is provided or if the input is of invalid type
[ "Checks", "the", "type", "before", "adding", "it", "to", "the", "request_handler_chains", "instance", "variable", "." ]
097b6406aa12d5ca0b825b00c936861b530cbf39
https://github.com/alexa/alexa-skills-kit-sdk-for-python/blob/097b6406aa12d5ca0b825b00c936861b530cbf39/ask-sdk-runtime/ask_sdk_runtime/dispatch_components/request_components.py#L331-L346
234,365
alexa/alexa-skills-kit-sdk-for-python
ask-sdk-runtime/ask_sdk_runtime/dispatch_components/request_components.py
GenericRequestMapper.get_request_handler_chain
def get_request_handler_chain(self, handler_input): # type: (Input) -> Union[GenericRequestHandlerChain, None] """Get the request handler chain that can handle the dispatch input. :param handler_input: Generic input passed to the dispatcher. :type handler_input: Input :return: Handler Chain that can handle the input. :rtype: Union[None, GenericRequestHandlerChain] """ for chain in self.request_handler_chains: handler = chain.request_handler # type: AbstractRequestHandler if handler.can_handle(handler_input=handler_input): return chain return None
python
def get_request_handler_chain(self, handler_input): # type: (Input) -> Union[GenericRequestHandlerChain, None] for chain in self.request_handler_chains: handler = chain.request_handler # type: AbstractRequestHandler if handler.can_handle(handler_input=handler_input): return chain return None
[ "def", "get_request_handler_chain", "(", "self", ",", "handler_input", ")", ":", "# type: (Input) -> Union[GenericRequestHandlerChain, None]", "for", "chain", "in", "self", ".", "request_handler_chains", ":", "handler", "=", "chain", ".", "request_handler", "# type: Abstrac...
Get the request handler chain that can handle the dispatch input. :param handler_input: Generic input passed to the dispatcher. :type handler_input: Input :return: Handler Chain that can handle the input. :rtype: Union[None, GenericRequestHandlerChain]
[ "Get", "the", "request", "handler", "chain", "that", "can", "handle", "the", "dispatch", "input", "." ]
097b6406aa12d5ca0b825b00c936861b530cbf39
https://github.com/alexa/alexa-skills-kit-sdk-for-python/blob/097b6406aa12d5ca0b825b00c936861b530cbf39/ask-sdk-runtime/ask_sdk_runtime/dispatch_components/request_components.py#L348-L363
234,366
alexa/alexa-skills-kit-sdk-for-python
ask-sdk-runtime/ask_sdk_runtime/dispatch_components/exception_components.py
GenericExceptionMapper.add_exception_handler
def add_exception_handler(self, exception_handler): # type: (AbstractExceptionHandler) -> None """Checks the type before adding it to the exception_handlers instance variable. :param exception_handler: Exception Handler instance. :type exception_handler: ask_sdk_runtime.dispatch_components.exception_components.AbstractExceptionHandler :raises: :py:class:`ask_sdk_runtime.exceptions.DispatchException` if a null input is provided or if the input is of invalid type """ if exception_handler is None or not isinstance( exception_handler, AbstractExceptionHandler): raise DispatchException( "Input is not an AbstractExceptionHandler instance") self._exception_handlers.append(exception_handler)
python
def add_exception_handler(self, exception_handler): # type: (AbstractExceptionHandler) -> None if exception_handler is None or not isinstance( exception_handler, AbstractExceptionHandler): raise DispatchException( "Input is not an AbstractExceptionHandler instance") self._exception_handlers.append(exception_handler)
[ "def", "add_exception_handler", "(", "self", ",", "exception_handler", ")", ":", "# type: (AbstractExceptionHandler) -> None", "if", "exception_handler", "is", "None", "or", "not", "isinstance", "(", "exception_handler", ",", "AbstractExceptionHandler", ")", ":", "raise",...
Checks the type before adding it to the exception_handlers instance variable. :param exception_handler: Exception Handler instance. :type exception_handler: ask_sdk_runtime.dispatch_components.exception_components.AbstractExceptionHandler :raises: :py:class:`ask_sdk_runtime.exceptions.DispatchException` if a null input is provided or if the input is of invalid type
[ "Checks", "the", "type", "before", "adding", "it", "to", "the", "exception_handlers", "instance", "variable", "." ]
097b6406aa12d5ca0b825b00c936861b530cbf39
https://github.com/alexa/alexa-skills-kit-sdk-for-python/blob/097b6406aa12d5ca0b825b00c936861b530cbf39/ask-sdk-runtime/ask_sdk_runtime/dispatch_components/exception_components.py#L165-L179
234,367
alexa/alexa-skills-kit-sdk-for-python
ask-sdk-runtime/ask_sdk_runtime/dispatch_components/exception_components.py
GenericExceptionMapper.get_handler
def get_handler(self, handler_input, exception): # type: (Input, Exception) -> Union[AbstractExceptionHandler, None] """Get the exception handler that can handle the input and exception. :param handler_input: Generic input passed to the dispatcher. :type handler_input: Input :param exception: Exception thrown by :py:class:`ask_sdk_runtime.dispatch.GenericRequestDispatcher` dispatch method. :type exception: Exception :return: Exception Handler that can handle the input or None. :rtype: Union[None, ask_sdk_runtime.dispatch_components.exception_components.AbstractExceptionHandler] """ for handler in self.exception_handlers: if handler.can_handle( handler_input=handler_input, exception=exception): return handler return None
python
def get_handler(self, handler_input, exception): # type: (Input, Exception) -> Union[AbstractExceptionHandler, None] for handler in self.exception_handlers: if handler.can_handle( handler_input=handler_input, exception=exception): return handler return None
[ "def", "get_handler", "(", "self", ",", "handler_input", ",", "exception", ")", ":", "# type: (Input, Exception) -> Union[AbstractExceptionHandler, None]", "for", "handler", "in", "self", ".", "exception_handlers", ":", "if", "handler", ".", "can_handle", "(", "handler_...
Get the exception handler that can handle the input and exception. :param handler_input: Generic input passed to the dispatcher. :type handler_input: Input :param exception: Exception thrown by :py:class:`ask_sdk_runtime.dispatch.GenericRequestDispatcher` dispatch method. :type exception: Exception :return: Exception Handler that can handle the input or None. :rtype: Union[None, ask_sdk_runtime.dispatch_components.exception_components.AbstractExceptionHandler]
[ "Get", "the", "exception", "handler", "that", "can", "handle", "the", "input", "and", "exception", "." ]
097b6406aa12d5ca0b825b00c936861b530cbf39
https://github.com/alexa/alexa-skills-kit-sdk-for-python/blob/097b6406aa12d5ca0b825b00c936861b530cbf39/ask-sdk-runtime/ask_sdk_runtime/dispatch_components/exception_components.py#L181-L200
234,368
alexa/alexa-skills-kit-sdk-for-python
ask-sdk-webservice-support/ask_sdk_webservice_support/verifier.py
RequestVerifier.verify
def verify( self, headers, serialized_request_env, deserialized_request_env): # type: (Dict[str, Any], str, RequestEnvelope) -> None """Verify if the input request signature and the body matches. The verify method retrieves the Signature Certificate Chain URL, validates the URL, retrieves the chain from the URL, validates the signing certificate, extract the public key, base64 decode the Signature and verifies if the hash value of the request body matches with the decrypted signature. :param headers: headers of the input POST request :type headers: Dict[str, Any] :param serialized_request_env: raw request envelope in the input POST request :type serialized_request_env: str :param deserialized_request_env: deserialized request envelope instance of the input POST request :type deserialized_request_env: :py:class:`ask_sdk_model.request_envelope.RequestEnvelope` :raises: :py:class:`VerificationException` if headers doesn't exist or verification fails """ cert_url = headers.get(self._signature_cert_chain_url_key) signature = headers.get(self._signature_key) if cert_url is None or signature is None: raise VerificationException( "Missing Signature/Certificate for the skill request") cert_chain = self._retrieve_and_validate_certificate_chain(cert_url) self._valid_request_body( cert_chain, signature, serialized_request_env)
python
def verify( self, headers, serialized_request_env, deserialized_request_env): # type: (Dict[str, Any], str, RequestEnvelope) -> None cert_url = headers.get(self._signature_cert_chain_url_key) signature = headers.get(self._signature_key) if cert_url is None or signature is None: raise VerificationException( "Missing Signature/Certificate for the skill request") cert_chain = self._retrieve_and_validate_certificate_chain(cert_url) self._valid_request_body( cert_chain, signature, serialized_request_env)
[ "def", "verify", "(", "self", ",", "headers", ",", "serialized_request_env", ",", "deserialized_request_env", ")", ":", "# type: (Dict[str, Any], str, RequestEnvelope) -> None", "cert_url", "=", "headers", ".", "get", "(", "self", ".", "_signature_cert_chain_url_key", ")"...
Verify if the input request signature and the body matches. The verify method retrieves the Signature Certificate Chain URL, validates the URL, retrieves the chain from the URL, validates the signing certificate, extract the public key, base64 decode the Signature and verifies if the hash value of the request body matches with the decrypted signature. :param headers: headers of the input POST request :type headers: Dict[str, Any] :param serialized_request_env: raw request envelope in the input POST request :type serialized_request_env: str :param deserialized_request_env: deserialized request envelope instance of the input POST request :type deserialized_request_env: :py:class:`ask_sdk_model.request_envelope.RequestEnvelope` :raises: :py:class:`VerificationException` if headers doesn't exist or verification fails
[ "Verify", "if", "the", "input", "request", "signature", "and", "the", "body", "matches", "." ]
097b6406aa12d5ca0b825b00c936861b530cbf39
https://github.com/alexa/alexa-skills-kit-sdk-for-python/blob/097b6406aa12d5ca0b825b00c936861b530cbf39/ask-sdk-webservice-support/ask_sdk_webservice_support/verifier.py#L165-L198
234,369
alexa/alexa-skills-kit-sdk-for-python
ask-sdk-webservice-support/ask_sdk_webservice_support/verifier.py
RequestVerifier._retrieve_and_validate_certificate_chain
def _retrieve_and_validate_certificate_chain(self, cert_url): # type: (str) -> Certificate """Retrieve and validate certificate chain. This method validates if the URL is valid and loads and validates the certificate chain, before returning it. :param cert_url: URL for retrieving certificate chain :type cert_url: str :return The certificate chain loaded from the URL :rtype cryptography.x509.Certificate :raises: :py:class:`VerificationException` if the URL is invalid, if the loaded certificate chain is invalid """ self._validate_certificate_url(cert_url) cert_chain = self._load_cert_chain(cert_url) self._validate_cert_chain(cert_chain) return cert_chain
python
def _retrieve_and_validate_certificate_chain(self, cert_url): # type: (str) -> Certificate self._validate_certificate_url(cert_url) cert_chain = self._load_cert_chain(cert_url) self._validate_cert_chain(cert_chain) return cert_chain
[ "def", "_retrieve_and_validate_certificate_chain", "(", "self", ",", "cert_url", ")", ":", "# type: (str) -> Certificate", "self", ".", "_validate_certificate_url", "(", "cert_url", ")", "cert_chain", "=", "self", ".", "_load_cert_chain", "(", "cert_url", ")", "self", ...
Retrieve and validate certificate chain. This method validates if the URL is valid and loads and validates the certificate chain, before returning it. :param cert_url: URL for retrieving certificate chain :type cert_url: str :return The certificate chain loaded from the URL :rtype cryptography.x509.Certificate :raises: :py:class:`VerificationException` if the URL is invalid, if the loaded certificate chain is invalid
[ "Retrieve", "and", "validate", "certificate", "chain", "." ]
097b6406aa12d5ca0b825b00c936861b530cbf39
https://github.com/alexa/alexa-skills-kit-sdk-for-python/blob/097b6406aa12d5ca0b825b00c936861b530cbf39/ask-sdk-webservice-support/ask_sdk_webservice_support/verifier.py#L200-L218
234,370
alexa/alexa-skills-kit-sdk-for-python
ask-sdk-webservice-support/ask_sdk_webservice_support/verifier.py
RequestVerifier._validate_certificate_url
def _validate_certificate_url(self, cert_url): # type: (str) -> None """Validate the URL containing the certificate chain. This method validates if the URL provided adheres to the format mentioned here : https://developer.amazon.com/docs/custom-skills/host-a-custom-skill-as-a-web-service.html#cert-verify-signature-certificate-url :param cert_url: URL for retrieving certificate chain :type cert_url: str :raises: :py:class:`VerificationException` if the URL is invalid """ parsed_url = urlparse(cert_url) protocol = parsed_url.scheme if protocol.lower() != CERT_CHAIN_URL_PROTOCOL.lower(): raise VerificationException( "Signature Certificate URL has invalid protocol: {}. " "Expecting {}".format(protocol, CERT_CHAIN_URL_PROTOCOL)) hostname = parsed_url.hostname if (hostname is None or hostname.lower() != CERT_CHAIN_URL_HOSTNAME.lower()): raise VerificationException( "Signature Certificate URL has invalid hostname: {}. " "Expecting {}".format(hostname, CERT_CHAIN_URL_HOSTNAME)) normalized_path = os.path.normpath(parsed_url.path) if not normalized_path.startswith(CERT_CHAIN_URL_STARTPATH): raise VerificationException( "Signature Certificate URL has invalid path: {}. " "Expecting the path to start with {}".format( normalized_path, CERT_CHAIN_URL_STARTPATH)) port = parsed_url.port if port is not None and port != CERT_CHAIN_URL_PORT: raise VerificationException( "Signature Certificate URL has invalid port: {}. " "Expecting {}".format(str(port), str(CERT_CHAIN_URL_PORT)))
python
def _validate_certificate_url(self, cert_url): # type: (str) -> None parsed_url = urlparse(cert_url) protocol = parsed_url.scheme if protocol.lower() != CERT_CHAIN_URL_PROTOCOL.lower(): raise VerificationException( "Signature Certificate URL has invalid protocol: {}. " "Expecting {}".format(protocol, CERT_CHAIN_URL_PROTOCOL)) hostname = parsed_url.hostname if (hostname is None or hostname.lower() != CERT_CHAIN_URL_HOSTNAME.lower()): raise VerificationException( "Signature Certificate URL has invalid hostname: {}. " "Expecting {}".format(hostname, CERT_CHAIN_URL_HOSTNAME)) normalized_path = os.path.normpath(parsed_url.path) if not normalized_path.startswith(CERT_CHAIN_URL_STARTPATH): raise VerificationException( "Signature Certificate URL has invalid path: {}. " "Expecting the path to start with {}".format( normalized_path, CERT_CHAIN_URL_STARTPATH)) port = parsed_url.port if port is not None and port != CERT_CHAIN_URL_PORT: raise VerificationException( "Signature Certificate URL has invalid port: {}. " "Expecting {}".format(str(port), str(CERT_CHAIN_URL_PORT)))
[ "def", "_validate_certificate_url", "(", "self", ",", "cert_url", ")", ":", "# type: (str) -> None", "parsed_url", "=", "urlparse", "(", "cert_url", ")", "protocol", "=", "parsed_url", ".", "scheme", "if", "protocol", ".", "lower", "(", ")", "!=", "CERT_CHAIN_UR...
Validate the URL containing the certificate chain. This method validates if the URL provided adheres to the format mentioned here : https://developer.amazon.com/docs/custom-skills/host-a-custom-skill-as-a-web-service.html#cert-verify-signature-certificate-url :param cert_url: URL for retrieving certificate chain :type cert_url: str :raises: :py:class:`VerificationException` if the URL is invalid
[ "Validate", "the", "URL", "containing", "the", "certificate", "chain", "." ]
097b6406aa12d5ca0b825b00c936861b530cbf39
https://github.com/alexa/alexa-skills-kit-sdk-for-python/blob/097b6406aa12d5ca0b825b00c936861b530cbf39/ask-sdk-webservice-support/ask_sdk_webservice_support/verifier.py#L220-L258
234,371
alexa/alexa-skills-kit-sdk-for-python
ask-sdk-webservice-support/ask_sdk_webservice_support/verifier.py
RequestVerifier._load_cert_chain
def _load_cert_chain(self, cert_url, x509_backend=default_backend()): # type: (str, X509Backend) -> Certificate """Loads the certificate chain from the URL. This method loads the certificate chain from the certificate cache. If there is a cache miss, the certificate chain is loaded from the certificate URL using the :py:func:`cryptography.x509.load_pem_x509_certificate` method. The x509 backend is set as default to the :py:class:`cryptography.hazmat.backends.default_backend` instance. A :py:class:`VerificationException` is raised if the certificate cannot be loaded. :param cert_url: URL for retrieving certificate chain :type cert_url: str :param x509_backend: Backend to be used, for loading pem x509 certificate :type x509_backend: cryptography.hazmat.backends.interfaces.X509Backend :return: Certificate chain loaded from cache or URL :rtype cryptography.x509.Certificate :raises: :py:class:`VerificationException` if unable to load the certificate """ try: if cert_url in self._cert_cache: return self._cert_cache.get(cert_url) else: with urlopen(cert_url) as cert_response: cert_data = cert_response.read() x509_certificate = load_pem_x509_certificate( cert_data, x509_backend) self._cert_cache[cert_url] = x509_certificate return x509_certificate except ValueError as e: raise VerificationException( "Unable to load certificate from URL", e)
python
def _load_cert_chain(self, cert_url, x509_backend=default_backend()): # type: (str, X509Backend) -> Certificate try: if cert_url in self._cert_cache: return self._cert_cache.get(cert_url) else: with urlopen(cert_url) as cert_response: cert_data = cert_response.read() x509_certificate = load_pem_x509_certificate( cert_data, x509_backend) self._cert_cache[cert_url] = x509_certificate return x509_certificate except ValueError as e: raise VerificationException( "Unable to load certificate from URL", e)
[ "def", "_load_cert_chain", "(", "self", ",", "cert_url", ",", "x509_backend", "=", "default_backend", "(", ")", ")", ":", "# type: (str, X509Backend) -> Certificate", "try", ":", "if", "cert_url", "in", "self", ".", "_cert_cache", ":", "return", "self", ".", "_c...
Loads the certificate chain from the URL. This method loads the certificate chain from the certificate cache. If there is a cache miss, the certificate chain is loaded from the certificate URL using the :py:func:`cryptography.x509.load_pem_x509_certificate` method. The x509 backend is set as default to the :py:class:`cryptography.hazmat.backends.default_backend` instance. A :py:class:`VerificationException` is raised if the certificate cannot be loaded. :param cert_url: URL for retrieving certificate chain :type cert_url: str :param x509_backend: Backend to be used, for loading pem x509 certificate :type x509_backend: cryptography.hazmat.backends.interfaces.X509Backend :return: Certificate chain loaded from cache or URL :rtype cryptography.x509.Certificate :raises: :py:class:`VerificationException` if unable to load the certificate
[ "Loads", "the", "certificate", "chain", "from", "the", "URL", "." ]
097b6406aa12d5ca0b825b00c936861b530cbf39
https://github.com/alexa/alexa-skills-kit-sdk-for-python/blob/097b6406aa12d5ca0b825b00c936861b530cbf39/ask-sdk-webservice-support/ask_sdk_webservice_support/verifier.py#L260-L296
234,372
alexa/alexa-skills-kit-sdk-for-python
ask-sdk-webservice-support/ask_sdk_webservice_support/verifier.py
RequestVerifier._validate_cert_chain
def _validate_cert_chain(self, cert_chain): # type: (Certificate) -> None """Validate the certificate chain. This method checks if the passed in certificate chain is valid, i.e it is not expired and the Alexa domain is present in the SAN extensions of the certificate chain. A :py:class:`VerificationException` is raised if the certificate chain is not valid. :param cert_chain: Certificate chain to be validated :type cert_chain: cryptography.x509.Certificate :return: None :raises: :py:class:`VerificationException` if certificated is not valid """ now = datetime.utcnow() if not (cert_chain.not_valid_before <= now <= cert_chain.not_valid_after): raise VerificationException("Signing Certificate expired") ext = cert_chain.extensions.get_extension_for_oid( ExtensionOID.SUBJECT_ALTERNATIVE_NAME) if CERT_CHAIN_DOMAIN not in ext.value.get_values_for_type( DNSName): raise VerificationException( "{} domain missing in Signature Certificate Chain".format( CERT_CHAIN_DOMAIN))
python
def _validate_cert_chain(self, cert_chain): # type: (Certificate) -> None now = datetime.utcnow() if not (cert_chain.not_valid_before <= now <= cert_chain.not_valid_after): raise VerificationException("Signing Certificate expired") ext = cert_chain.extensions.get_extension_for_oid( ExtensionOID.SUBJECT_ALTERNATIVE_NAME) if CERT_CHAIN_DOMAIN not in ext.value.get_values_for_type( DNSName): raise VerificationException( "{} domain missing in Signature Certificate Chain".format( CERT_CHAIN_DOMAIN))
[ "def", "_validate_cert_chain", "(", "self", ",", "cert_chain", ")", ":", "# type: (Certificate) -> None", "now", "=", "datetime", ".", "utcnow", "(", ")", "if", "not", "(", "cert_chain", ".", "not_valid_before", "<=", "now", "<=", "cert_chain", ".", "not_valid_a...
Validate the certificate chain. This method checks if the passed in certificate chain is valid, i.e it is not expired and the Alexa domain is present in the SAN extensions of the certificate chain. A :py:class:`VerificationException` is raised if the certificate chain is not valid. :param cert_chain: Certificate chain to be validated :type cert_chain: cryptography.x509.Certificate :return: None :raises: :py:class:`VerificationException` if certificated is not valid
[ "Validate", "the", "certificate", "chain", "." ]
097b6406aa12d5ca0b825b00c936861b530cbf39
https://github.com/alexa/alexa-skills-kit-sdk-for-python/blob/097b6406aa12d5ca0b825b00c936861b530cbf39/ask-sdk-webservice-support/ask_sdk_webservice_support/verifier.py#L298-L325
234,373
alexa/alexa-skills-kit-sdk-for-python
ask-sdk-webservice-support/ask_sdk_webservice_support/verifier.py
RequestVerifier._valid_request_body
def _valid_request_body( self, cert_chain, signature, serialized_request_env): # type: (Certificate, str, str) -> None """Validate the request body hash with signature. This method checks if the hash value of the request body matches with the hash value of the signature, decrypted using certificate chain. A :py:class:`VerificationException` is raised if there is a mismatch. :param cert_chain: Certificate chain to be validated :type cert_chain: cryptography.x509.Certificate :param signature: Encrypted signature of the request :type: str :param serialized_request_env: Raw request body :type: str :raises: :py:class:`VerificationException` if certificate is not valid """ decoded_signature = base64.b64decode(signature) public_key = cert_chain.public_key() request_env_bytes = serialized_request_env.encode(CHARACTER_ENCODING) try: public_key.verify( decoded_signature, request_env_bytes, self._padding, self._hash_algorithm) except InvalidSignature as e: raise VerificationException("Request body is not valid", e)
python
def _valid_request_body( self, cert_chain, signature, serialized_request_env): # type: (Certificate, str, str) -> None decoded_signature = base64.b64decode(signature) public_key = cert_chain.public_key() request_env_bytes = serialized_request_env.encode(CHARACTER_ENCODING) try: public_key.verify( decoded_signature, request_env_bytes, self._padding, self._hash_algorithm) except InvalidSignature as e: raise VerificationException("Request body is not valid", e)
[ "def", "_valid_request_body", "(", "self", ",", "cert_chain", ",", "signature", ",", "serialized_request_env", ")", ":", "# type: (Certificate, str, str) -> None", "decoded_signature", "=", "base64", ".", "b64decode", "(", "signature", ")", "public_key", "=", "cert_chai...
Validate the request body hash with signature. This method checks if the hash value of the request body matches with the hash value of the signature, decrypted using certificate chain. A :py:class:`VerificationException` is raised if there is a mismatch. :param cert_chain: Certificate chain to be validated :type cert_chain: cryptography.x509.Certificate :param signature: Encrypted signature of the request :type: str :param serialized_request_env: Raw request body :type: str :raises: :py:class:`VerificationException` if certificate is not valid
[ "Validate", "the", "request", "body", "hash", "with", "signature", "." ]
097b6406aa12d5ca0b825b00c936861b530cbf39
https://github.com/alexa/alexa-skills-kit-sdk-for-python/blob/097b6406aa12d5ca0b825b00c936861b530cbf39/ask-sdk-webservice-support/ask_sdk_webservice_support/verifier.py#L327-L356
234,374
alexa/alexa-skills-kit-sdk-for-python
ask-sdk-webservice-support/ask_sdk_webservice_support/verifier.py
TimestampVerifier.verify
def verify( self, headers, serialized_request_env, deserialized_request_env): # type: (Dict[str, Any], str, RequestEnvelope) -> None """Verify if the input request timestamp is in tolerated limits. The verify method retrieves the request timestamp and check if it falls in the limit set by the tolerance, by checking with the current timestamp in UTC. :param headers: headers of the input POST request :type headers: Dict[str, Any] :param serialized_request_env: raw request envelope in the input POST request :type serialized_request_env: str :param deserialized_request_env: deserialized request envelope instance of the input POST request :type deserialized_request_env: :py:class:`ask_sdk_model.request_envelope.RequestEnvelope` :raises: :py:class:`VerificationException` if difference between local timestamp and input request timestamp is more than specific tolerance limit """ local_now = datetime.now(tz.tzutc()) request_timestamp = deserialized_request_env.request.timestamp if (abs((local_now - request_timestamp).seconds) > (self._tolerance_in_millis / 1000)): raise VerificationException("Timestamp verification failed")
python
def verify( self, headers, serialized_request_env, deserialized_request_env): # type: (Dict[str, Any], str, RequestEnvelope) -> None local_now = datetime.now(tz.tzutc()) request_timestamp = deserialized_request_env.request.timestamp if (abs((local_now - request_timestamp).seconds) > (self._tolerance_in_millis / 1000)): raise VerificationException("Timestamp verification failed")
[ "def", "verify", "(", "self", ",", "headers", ",", "serialized_request_env", ",", "deserialized_request_env", ")", ":", "# type: (Dict[str, Any], str, RequestEnvelope) -> None", "local_now", "=", "datetime", ".", "now", "(", "tz", ".", "tzutc", "(", ")", ")", "reque...
Verify if the input request timestamp is in tolerated limits. The verify method retrieves the request timestamp and check if it falls in the limit set by the tolerance, by checking with the current timestamp in UTC. :param headers: headers of the input POST request :type headers: Dict[str, Any] :param serialized_request_env: raw request envelope in the input POST request :type serialized_request_env: str :param deserialized_request_env: deserialized request envelope instance of the input POST request :type deserialized_request_env: :py:class:`ask_sdk_model.request_envelope.RequestEnvelope` :raises: :py:class:`VerificationException` if difference between local timestamp and input request timestamp is more than specific tolerance limit
[ "Verify", "if", "the", "input", "request", "timestamp", "is", "in", "tolerated", "limits", "." ]
097b6406aa12d5ca0b825b00c936861b530cbf39
https://github.com/alexa/alexa-skills-kit-sdk-for-python/blob/097b6406aa12d5ca0b825b00c936861b530cbf39/ask-sdk-webservice-support/ask_sdk_webservice_support/verifier.py#L411-L437
234,375
mozilla/moz-sql-parser
moz_sql_parser/formatting.py
escape
def escape(identifier, ansi_quotes, should_quote): """ Escape identifiers. ANSI uses single quotes, but many databases use back quotes. """ if not should_quote(identifier): return identifier quote = '"' if ansi_quotes else '`' identifier = identifier.replace(quote, 2*quote) return '{0}{1}{2}'.format(quote, identifier, quote)
python
def escape(identifier, ansi_quotes, should_quote): if not should_quote(identifier): return identifier quote = '"' if ansi_quotes else '`' identifier = identifier.replace(quote, 2*quote) return '{0}{1}{2}'.format(quote, identifier, quote)
[ "def", "escape", "(", "identifier", ",", "ansi_quotes", ",", "should_quote", ")", ":", "if", "not", "should_quote", "(", "identifier", ")", ":", "return", "identifier", "quote", "=", "'\"'", "if", "ansi_quotes", "else", "'`'", "identifier", "=", "identifier", ...
Escape identifiers. ANSI uses single quotes, but many databases use back quotes.
[ "Escape", "identifiers", "." ]
35fcc69b8f73b48e1fd48025cae1e174d57c3921
https://github.com/mozilla/moz-sql-parser/blob/35fcc69b8f73b48e1fd48025cae1e174d57c3921/moz_sql_parser/formatting.py#L39-L51
234,376
mlouielu/twstock
twstock/analytics.py
Analytics.ma_bias_ratio
def ma_bias_ratio(self, day1, day2): """Calculate moving average bias ratio""" data1 = self.moving_average(self.price, day1) data2 = self.moving_average(self.price, day2) result = [data1[-i] - data2[-i] for i in range(1, min(len(data1), len(data2)) + 1)] return result[::-1]
python
def ma_bias_ratio(self, day1, day2): data1 = self.moving_average(self.price, day1) data2 = self.moving_average(self.price, day2) result = [data1[-i] - data2[-i] for i in range(1, min(len(data1), len(data2)) + 1)] return result[::-1]
[ "def", "ma_bias_ratio", "(", "self", ",", "day1", ",", "day2", ")", ":", "data1", "=", "self", ".", "moving_average", "(", "self", ".", "price", ",", "day1", ")", "data2", "=", "self", ".", "moving_average", "(", "self", ".", "price", ",", "day2", ")...
Calculate moving average bias ratio
[ "Calculate", "moving", "average", "bias", "ratio" ]
cddddcc084d2d00497d591ab3059e3205b755825
https://github.com/mlouielu/twstock/blob/cddddcc084d2d00497d591ab3059e3205b755825/twstock/analytics.py#L24-L30
234,377
mlouielu/twstock
twstock/analytics.py
Analytics.ma_bias_ratio_pivot
def ma_bias_ratio_pivot(self, data, sample_size=5, position=False): """Calculate pivot point""" sample = data[-sample_size:] if position is True: check_value = max(sample) pre_check_value = max(sample) > 0 elif position is False: check_value = min(sample) pre_check_value = max(sample) < 0 return ((sample_size - sample.index(check_value) < 4 and sample.index(check_value) != sample_size - 1 and pre_check_value), sample_size - sample.index(check_value) - 1, check_value)
python
def ma_bias_ratio_pivot(self, data, sample_size=5, position=False): sample = data[-sample_size:] if position is True: check_value = max(sample) pre_check_value = max(sample) > 0 elif position is False: check_value = min(sample) pre_check_value = max(sample) < 0 return ((sample_size - sample.index(check_value) < 4 and sample.index(check_value) != sample_size - 1 and pre_check_value), sample_size - sample.index(check_value) - 1, check_value)
[ "def", "ma_bias_ratio_pivot", "(", "self", ",", "data", ",", "sample_size", "=", "5", ",", "position", "=", "False", ")", ":", "sample", "=", "data", "[", "-", "sample_size", ":", "]", "if", "position", "is", "True", ":", "check_value", "=", "max", "("...
Calculate pivot point
[ "Calculate", "pivot", "point" ]
cddddcc084d2d00497d591ab3059e3205b755825
https://github.com/mlouielu/twstock/blob/cddddcc084d2d00497d591ab3059e3205b755825/twstock/analytics.py#L32-L46
234,378
mlouielu/twstock
twstock/stock.py
Stock.fetch
def fetch(self, year: int, month: int): """Fetch year month data""" self.raw_data = [self.fetcher.fetch(year, month, self.sid)] self.data = self.raw_data[0]['data'] return self.data
python
def fetch(self, year: int, month: int): self.raw_data = [self.fetcher.fetch(year, month, self.sid)] self.data = self.raw_data[0]['data'] return self.data
[ "def", "fetch", "(", "self", ",", "year", ":", "int", ",", "month", ":", "int", ")", ":", "self", ".", "raw_data", "=", "[", "self", ".", "fetcher", ".", "fetch", "(", "year", ",", "month", ",", "self", ".", "sid", ")", "]", "self", ".", "data"...
Fetch year month data
[ "Fetch", "year", "month", "data" ]
cddddcc084d2d00497d591ab3059e3205b755825
https://github.com/mlouielu/twstock/blob/cddddcc084d2d00497d591ab3059e3205b755825/twstock/stock.py#L151-L155
234,379
mlouielu/twstock
twstock/stock.py
Stock.fetch_from
def fetch_from(self, year: int, month: int): """Fetch data from year, month to current year month data""" self.raw_data = [] self.data = [] today = datetime.datetime.today() for year, month in self._month_year_iter(month, year, today.month, today.year): self.raw_data.append(self.fetcher.fetch(year, month, self.sid)) self.data.extend(self.raw_data[-1]['data']) return self.data
python
def fetch_from(self, year: int, month: int): self.raw_data = [] self.data = [] today = datetime.datetime.today() for year, month in self._month_year_iter(month, year, today.month, today.year): self.raw_data.append(self.fetcher.fetch(year, month, self.sid)) self.data.extend(self.raw_data[-1]['data']) return self.data
[ "def", "fetch_from", "(", "self", ",", "year", ":", "int", ",", "month", ":", "int", ")", ":", "self", ".", "raw_data", "=", "[", "]", "self", ".", "data", "=", "[", "]", "today", "=", "datetime", ".", "datetime", ".", "today", "(", ")", "for", ...
Fetch data from year, month to current year month data
[ "Fetch", "data", "from", "year", "month", "to", "current", "year", "month", "data" ]
cddddcc084d2d00497d591ab3059e3205b755825
https://github.com/mlouielu/twstock/blob/cddddcc084d2d00497d591ab3059e3205b755825/twstock/stock.py#L157-L165
234,380
mlouielu/twstock
twstock/stock.py
Stock.fetch_31
def fetch_31(self): """Fetch 31 days data""" today = datetime.datetime.today() before = today - datetime.timedelta(days=60) self.fetch_from(before.year, before.month) self.data = self.data[-31:] return self.data
python
def fetch_31(self): today = datetime.datetime.today() before = today - datetime.timedelta(days=60) self.fetch_from(before.year, before.month) self.data = self.data[-31:] return self.data
[ "def", "fetch_31", "(", "self", ")", ":", "today", "=", "datetime", ".", "datetime", ".", "today", "(", ")", "before", "=", "today", "-", "datetime", ".", "timedelta", "(", "days", "=", "60", ")", "self", ".", "fetch_from", "(", "before", ".", "year"...
Fetch 31 days data
[ "Fetch", "31", "days", "data" ]
cddddcc084d2d00497d591ab3059e3205b755825
https://github.com/mlouielu/twstock/blob/cddddcc084d2d00497d591ab3059e3205b755825/twstock/stock.py#L167-L173
234,381
hellock/icrawler
icrawler/utils/proxy_pool.py
Proxy.to_dict
def to_dict(self): """convert detailed proxy info into a dict Returns: dict: A dict with four keys: ``addr``, ``protocol``, ``weight`` and ``last_checked`` """ return dict( addr=self.addr, protocol=self.protocol, weight=self.weight, last_checked=self.last_checked)
python
def to_dict(self): return dict( addr=self.addr, protocol=self.protocol, weight=self.weight, last_checked=self.last_checked)
[ "def", "to_dict", "(", "self", ")", ":", "return", "dict", "(", "addr", "=", "self", ".", "addr", ",", "protocol", "=", "self", ".", "protocol", ",", "weight", "=", "self", ".", "weight", ",", "last_checked", "=", "self", ".", "last_checked", ")" ]
convert detailed proxy info into a dict Returns: dict: A dict with four keys: ``addr``, ``protocol``, ``weight`` and ``last_checked``
[ "convert", "detailed", "proxy", "info", "into", "a", "dict" ]
38c925758fd3d3e568d3ecc993f77bc0acfa4788
https://github.com/hellock/icrawler/blob/38c925758fd3d3e568d3ecc993f77bc0acfa4788/icrawler/utils/proxy_pool.py#L47-L58
234,382
hellock/icrawler
icrawler/utils/proxy_pool.py
ProxyPool.proxy_num
def proxy_num(self, protocol=None): """Get the number of proxies in the pool Args: protocol (str, optional): 'http' or 'https' or None. (default None) Returns: If protocol is None, return the total number of proxies, otherwise, return the number of proxies of corresponding protocol. """ http_num = len(self.proxies['http']) https_num = len(self.proxies['https']) if protocol == 'http': return http_num elif protocol == 'https': return https_num else: return http_num + https_num
python
def proxy_num(self, protocol=None): http_num = len(self.proxies['http']) https_num = len(self.proxies['https']) if protocol == 'http': return http_num elif protocol == 'https': return https_num else: return http_num + https_num
[ "def", "proxy_num", "(", "self", ",", "protocol", "=", "None", ")", ":", "http_num", "=", "len", "(", "self", ".", "proxies", "[", "'http'", "]", ")", "https_num", "=", "len", "(", "self", ".", "proxies", "[", "'https'", "]", ")", "if", "protocol", ...
Get the number of proxies in the pool Args: protocol (str, optional): 'http' or 'https' or None. (default None) Returns: If protocol is None, return the total number of proxies, otherwise, return the number of proxies of corresponding protocol.
[ "Get", "the", "number", "of", "proxies", "in", "the", "pool" ]
38c925758fd3d3e568d3ecc993f77bc0acfa4788
https://github.com/hellock/icrawler/blob/38c925758fd3d3e568d3ecc993f77bc0acfa4788/icrawler/utils/proxy_pool.py#L104-L121
234,383
hellock/icrawler
icrawler/utils/proxy_pool.py
ProxyPool.get_next
def get_next(self, protocol='http', format=False, policy='loop'): """Get the next proxy Args: protocol (str): 'http' or 'https'. (default 'http') format (bool): Whether to format the proxy. (default False) policy (str): Either 'loop' or 'random', indicating the policy of getting the next proxy. If set to 'loop', will return proxies in turn, otherwise will return a proxy randomly. Returns: Proxy or dict: If format is true, then return the formatted proxy which is compatible with requests.Session parameters, otherwise a Proxy object. """ if not self.proxies[protocol]: return None if policy == 'loop': idx = self.idx[protocol] self.idx[protocol] = (idx + 1) % len(self.proxies[protocol]) elif policy == 'random': idx = random.randint(0, self.proxy_num(protocol) - 1) else: self.logger.error('Unsupported get_next policy: {}'.format(policy)) exit() proxy = self.proxies[protocol][self.addr_list[protocol][idx]] if proxy.weight < random.random(): return self.get_next(protocol, format, policy) if format: return proxy.format() else: return proxy
python
def get_next(self, protocol='http', format=False, policy='loop'): if not self.proxies[protocol]: return None if policy == 'loop': idx = self.idx[protocol] self.idx[protocol] = (idx + 1) % len(self.proxies[protocol]) elif policy == 'random': idx = random.randint(0, self.proxy_num(protocol) - 1) else: self.logger.error('Unsupported get_next policy: {}'.format(policy)) exit() proxy = self.proxies[protocol][self.addr_list[protocol][idx]] if proxy.weight < random.random(): return self.get_next(protocol, format, policy) if format: return proxy.format() else: return proxy
[ "def", "get_next", "(", "self", ",", "protocol", "=", "'http'", ",", "format", "=", "False", ",", "policy", "=", "'loop'", ")", ":", "if", "not", "self", ".", "proxies", "[", "protocol", "]", ":", "return", "None", "if", "policy", "==", "'loop'", ":"...
Get the next proxy Args: protocol (str): 'http' or 'https'. (default 'http') format (bool): Whether to format the proxy. (default False) policy (str): Either 'loop' or 'random', indicating the policy of getting the next proxy. If set to 'loop', will return proxies in turn, otherwise will return a proxy randomly. Returns: Proxy or dict: If format is true, then return the formatted proxy which is compatible with requests.Session parameters, otherwise a Proxy object.
[ "Get", "the", "next", "proxy" ]
38c925758fd3d3e568d3ecc993f77bc0acfa4788
https://github.com/hellock/icrawler/blob/38c925758fd3d3e568d3ecc993f77bc0acfa4788/icrawler/utils/proxy_pool.py#L123-L154
234,384
hellock/icrawler
icrawler/utils/proxy_pool.py
ProxyPool.save
def save(self, filename): """Save proxies to file""" proxies = {'http': [], 'https': []} for protocol in ['http', 'https']: for proxy in self.proxies[protocol]: serializable_proxy = self.proxies[protocol][proxy].to_dict() proxies[protocol].append(serializable_proxy) with open(filename, 'w') as fout: json.dump(proxies, fout)
python
def save(self, filename): proxies = {'http': [], 'https': []} for protocol in ['http', 'https']: for proxy in self.proxies[protocol]: serializable_proxy = self.proxies[protocol][proxy].to_dict() proxies[protocol].append(serializable_proxy) with open(filename, 'w') as fout: json.dump(proxies, fout)
[ "def", "save", "(", "self", ",", "filename", ")", ":", "proxies", "=", "{", "'http'", ":", "[", "]", ",", "'https'", ":", "[", "]", "}", "for", "protocol", "in", "[", "'http'", ",", "'https'", "]", ":", "for", "proxy", "in", "self", ".", "proxies...
Save proxies to file
[ "Save", "proxies", "to", "file" ]
38c925758fd3d3e568d3ecc993f77bc0acfa4788
https://github.com/hellock/icrawler/blob/38c925758fd3d3e568d3ecc993f77bc0acfa4788/icrawler/utils/proxy_pool.py#L156-L164
234,385
hellock/icrawler
icrawler/utils/proxy_pool.py
ProxyPool.load
def load(self, filename): """Load proxies from file""" with open(filename, 'r') as fin: proxies = json.load(fin) for protocol in proxies: for proxy in proxies[protocol]: self.proxies[protocol][proxy['addr']] = Proxy( proxy['addr'], proxy['protocol'], proxy['weight'], proxy['last_checked']) self.addr_list[protocol].append(proxy['addr'])
python
def load(self, filename): with open(filename, 'r') as fin: proxies = json.load(fin) for protocol in proxies: for proxy in proxies[protocol]: self.proxies[protocol][proxy['addr']] = Proxy( proxy['addr'], proxy['protocol'], proxy['weight'], proxy['last_checked']) self.addr_list[protocol].append(proxy['addr'])
[ "def", "load", "(", "self", ",", "filename", ")", ":", "with", "open", "(", "filename", ",", "'r'", ")", "as", "fin", ":", "proxies", "=", "json", ".", "load", "(", "fin", ")", "for", "protocol", "in", "proxies", ":", "for", "proxy", "in", "proxies...
Load proxies from file
[ "Load", "proxies", "from", "file" ]
38c925758fd3d3e568d3ecc993f77bc0acfa4788
https://github.com/hellock/icrawler/blob/38c925758fd3d3e568d3ecc993f77bc0acfa4788/icrawler/utils/proxy_pool.py#L166-L175
234,386
hellock/icrawler
icrawler/utils/proxy_pool.py
ProxyPool.add_proxy
def add_proxy(self, proxy): """Add a valid proxy into pool You must call `add_proxy` method to add a proxy into pool instead of directly operate the `proxies` variable. """ protocol = proxy.protocol addr = proxy.addr if addr in self.proxies: self.proxies[protocol][addr].last_checked = proxy.last_checked else: self.proxies[protocol][addr] = proxy self.addr_list[protocol].append(addr)
python
def add_proxy(self, proxy): protocol = proxy.protocol addr = proxy.addr if addr in self.proxies: self.proxies[protocol][addr].last_checked = proxy.last_checked else: self.proxies[protocol][addr] = proxy self.addr_list[protocol].append(addr)
[ "def", "add_proxy", "(", "self", ",", "proxy", ")", ":", "protocol", "=", "proxy", ".", "protocol", "addr", "=", "proxy", ".", "addr", "if", "addr", "in", "self", ".", "proxies", ":", "self", ".", "proxies", "[", "protocol", "]", "[", "addr", "]", ...
Add a valid proxy into pool You must call `add_proxy` method to add a proxy into pool instead of directly operate the `proxies` variable.
[ "Add", "a", "valid", "proxy", "into", "pool" ]
38c925758fd3d3e568d3ecc993f77bc0acfa4788
https://github.com/hellock/icrawler/blob/38c925758fd3d3e568d3ecc993f77bc0acfa4788/icrawler/utils/proxy_pool.py#L177-L189
234,387
hellock/icrawler
icrawler/utils/proxy_pool.py
ProxyPool.remove_proxy
def remove_proxy(self, proxy): """Remove a proxy out of the pool""" del self.search_flag[proxy.protocol][proxy.addr] del self.addr_list[proxy.protocol][proxy.addr]
python
def remove_proxy(self, proxy): del self.search_flag[proxy.protocol][proxy.addr] del self.addr_list[proxy.protocol][proxy.addr]
[ "def", "remove_proxy", "(", "self", ",", "proxy", ")", ":", "del", "self", ".", "search_flag", "[", "proxy", ".", "protocol", "]", "[", "proxy", ".", "addr", "]", "del", "self", ".", "addr_list", "[", "proxy", ".", "protocol", "]", "[", "proxy", ".",...
Remove a proxy out of the pool
[ "Remove", "a", "proxy", "out", "of", "the", "pool" ]
38c925758fd3d3e568d3ecc993f77bc0acfa4788
https://github.com/hellock/icrawler/blob/38c925758fd3d3e568d3ecc993f77bc0acfa4788/icrawler/utils/proxy_pool.py#L191-L194
234,388
hellock/icrawler
icrawler/utils/proxy_pool.py
ProxyPool.increase_weight
def increase_weight(self, proxy): """Increase the weight of a proxy by multiplying inc_ratio""" new_weight = proxy.weight * self.inc_ratio if new_weight < 1.0: proxy.weight = new_weight else: proxy.weight = 1.0
python
def increase_weight(self, proxy): new_weight = proxy.weight * self.inc_ratio if new_weight < 1.0: proxy.weight = new_weight else: proxy.weight = 1.0
[ "def", "increase_weight", "(", "self", ",", "proxy", ")", ":", "new_weight", "=", "proxy", ".", "weight", "*", "self", ".", "inc_ratio", "if", "new_weight", "<", "1.0", ":", "proxy", ".", "weight", "=", "new_weight", "else", ":", "proxy", ".", "weight", ...
Increase the weight of a proxy by multiplying inc_ratio
[ "Increase", "the", "weight", "of", "a", "proxy", "by", "multiplying", "inc_ratio" ]
38c925758fd3d3e568d3ecc993f77bc0acfa4788
https://github.com/hellock/icrawler/blob/38c925758fd3d3e568d3ecc993f77bc0acfa4788/icrawler/utils/proxy_pool.py#L196-L202
234,389
hellock/icrawler
icrawler/utils/proxy_pool.py
ProxyPool.decrease_weight
def decrease_weight(self, proxy): """Decreasing the weight of a proxy by multiplying dec_ratio""" new_weight = proxy.weight * self.dec_ratio if new_weight < self.weight_thr: self.remove_proxy(proxy) else: proxy.weight = new_weight
python
def decrease_weight(self, proxy): new_weight = proxy.weight * self.dec_ratio if new_weight < self.weight_thr: self.remove_proxy(proxy) else: proxy.weight = new_weight
[ "def", "decrease_weight", "(", "self", ",", "proxy", ")", ":", "new_weight", "=", "proxy", ".", "weight", "*", "self", ".", "dec_ratio", "if", "new_weight", "<", "self", ".", "weight_thr", ":", "self", ".", "remove_proxy", "(", "proxy", ")", "else", ":",...
Decreasing the weight of a proxy by multiplying dec_ratio
[ "Decreasing", "the", "weight", "of", "a", "proxy", "by", "multiplying", "dec_ratio" ]
38c925758fd3d3e568d3ecc993f77bc0acfa4788
https://github.com/hellock/icrawler/blob/38c925758fd3d3e568d3ecc993f77bc0acfa4788/icrawler/utils/proxy_pool.py#L204-L210
234,390
hellock/icrawler
icrawler/utils/proxy_pool.py
ProxyPool.is_valid
def is_valid(self, addr, protocol='http', timeout=5): """Check if a proxy is valid Args: addr: A string in the form of 'ip:port' protocol: Either 'http' or 'https', different test urls will be used according to protocol. timeout: A integer indicating the timeout of connecting the test url. Returns: dict: If the proxy is valid, returns {'valid': True, 'response_time': xx} otherwise returns {'valid': False, 'msg': 'xxxxxx'}. """ start = time.time() try: r = requests.get(self.test_url[protocol], timeout=timeout, proxies={protocol: 'http://' + addr}) except KeyboardInterrupt: raise except requests.exceptions.Timeout: return {'valid': False, 'msg': 'timeout'} except: return {'valid': False, 'msg': 'exception'} else: if r.status_code == 200: response_time = time.time() - start return {'valid': True, 'response_time': response_time} else: return { 'valid': False, 'msg': 'status code: {}'.format(r.status_code) }
python
def is_valid(self, addr, protocol='http', timeout=5): start = time.time() try: r = requests.get(self.test_url[protocol], timeout=timeout, proxies={protocol: 'http://' + addr}) except KeyboardInterrupt: raise except requests.exceptions.Timeout: return {'valid': False, 'msg': 'timeout'} except: return {'valid': False, 'msg': 'exception'} else: if r.status_code == 200: response_time = time.time() - start return {'valid': True, 'response_time': response_time} else: return { 'valid': False, 'msg': 'status code: {}'.format(r.status_code) }
[ "def", "is_valid", "(", "self", ",", "addr", ",", "protocol", "=", "'http'", ",", "timeout", "=", "5", ")", ":", "start", "=", "time", ".", "time", "(", ")", "try", ":", "r", "=", "requests", ".", "get", "(", "self", ".", "test_url", "[", "protoc...
Check if a proxy is valid Args: addr: A string in the form of 'ip:port' protocol: Either 'http' or 'https', different test urls will be used according to protocol. timeout: A integer indicating the timeout of connecting the test url. Returns: dict: If the proxy is valid, returns {'valid': True, 'response_time': xx} otherwise returns {'valid': False, 'msg': 'xxxxxx'}.
[ "Check", "if", "a", "proxy", "is", "valid" ]
38c925758fd3d3e568d3ecc993f77bc0acfa4788
https://github.com/hellock/icrawler/blob/38c925758fd3d3e568d3ecc993f77bc0acfa4788/icrawler/utils/proxy_pool.py#L212-L244
234,391
hellock/icrawler
icrawler/utils/proxy_pool.py
ProxyPool.validate
def validate(self, proxy_scanner, expected_num=20, queue_timeout=3, val_timeout=5): """Target function of validation threads Args: proxy_scanner: A ProxyScanner object. expected_num: Max number of valid proxies to be scanned. queue_timeout: Timeout for getting a proxy from the queue. val_timeout: An integer passed to `is_valid` as argument `timeout`. """ while self.proxy_num() < expected_num: try: candidate_proxy = proxy_scanner.proxy_queue.get( timeout=queue_timeout) except queue.Empty: if proxy_scanner.is_scanning(): continue else: break addr = candidate_proxy['addr'] protocol = candidate_proxy['protocol'] ret = self.is_valid(addr, protocol, val_timeout) if self.proxy_num() >= expected_num: self.logger.info('Enough valid proxies, thread {} exit.' .format(threading.current_thread().name)) break if ret['valid']: self.add_proxy(Proxy(addr, protocol)) self.logger.info('{} ok, {:.2f}s'.format(addr, ret[ 'response_time'])) else: self.logger.info('{} invalid, {}'.format(addr, ret['msg']))
python
def validate(self, proxy_scanner, expected_num=20, queue_timeout=3, val_timeout=5): while self.proxy_num() < expected_num: try: candidate_proxy = proxy_scanner.proxy_queue.get( timeout=queue_timeout) except queue.Empty: if proxy_scanner.is_scanning(): continue else: break addr = candidate_proxy['addr'] protocol = candidate_proxy['protocol'] ret = self.is_valid(addr, protocol, val_timeout) if self.proxy_num() >= expected_num: self.logger.info('Enough valid proxies, thread {} exit.' .format(threading.current_thread().name)) break if ret['valid']: self.add_proxy(Proxy(addr, protocol)) self.logger.info('{} ok, {:.2f}s'.format(addr, ret[ 'response_time'])) else: self.logger.info('{} invalid, {}'.format(addr, ret['msg']))
[ "def", "validate", "(", "self", ",", "proxy_scanner", ",", "expected_num", "=", "20", ",", "queue_timeout", "=", "3", ",", "val_timeout", "=", "5", ")", ":", "while", "self", ".", "proxy_num", "(", ")", "<", "expected_num", ":", "try", ":", "candidate_pr...
Target function of validation threads Args: proxy_scanner: A ProxyScanner object. expected_num: Max number of valid proxies to be scanned. queue_timeout: Timeout for getting a proxy from the queue. val_timeout: An integer passed to `is_valid` as argument `timeout`.
[ "Target", "function", "of", "validation", "threads" ]
38c925758fd3d3e568d3ecc993f77bc0acfa4788
https://github.com/hellock/icrawler/blob/38c925758fd3d3e568d3ecc993f77bc0acfa4788/icrawler/utils/proxy_pool.py#L246-L280
234,392
hellock/icrawler
icrawler/utils/proxy_pool.py
ProxyPool.scan
def scan(self, proxy_scanner, expected_num=20, val_thr_num=4, queue_timeout=3, val_timeout=5, out_file='proxies.json'): """Scan and validate proxies Firstly, call the `scan` method of `proxy_scanner`, then using multiple threads to validate them. Args: proxy_scanner: A ProxyScanner object. expected_num: Max number of valid proxies to be scanned. val_thr_num: Number of threads used for validating proxies. queue_timeout: Timeout for getting a proxy from the queue. val_timeout: An integer passed to `is_valid` as argument `timeout`. out_file: A string or None. If not None, the proxies will be saved into `out_file`. """ try: proxy_scanner.scan() self.logger.info('starting {} threads to validating proxies...' .format(val_thr_num)) val_threads = [] for i in range(val_thr_num): t = threading.Thread( name='val-{:0>2d}'.format(i + 1), target=self.validate, kwargs=dict( proxy_scanner=proxy_scanner, expected_num=expected_num, queue_timeout=queue_timeout, val_timeout=val_timeout)) t.daemon = True val_threads.append(t) t.start() for t in val_threads: t.join() self.logger.info('Proxy scanning done!') except: raise finally: if out_file is not None: self.save(out_file)
python
def scan(self, proxy_scanner, expected_num=20, val_thr_num=4, queue_timeout=3, val_timeout=5, out_file='proxies.json'): try: proxy_scanner.scan() self.logger.info('starting {} threads to validating proxies...' .format(val_thr_num)) val_threads = [] for i in range(val_thr_num): t = threading.Thread( name='val-{:0>2d}'.format(i + 1), target=self.validate, kwargs=dict( proxy_scanner=proxy_scanner, expected_num=expected_num, queue_timeout=queue_timeout, val_timeout=val_timeout)) t.daemon = True val_threads.append(t) t.start() for t in val_threads: t.join() self.logger.info('Proxy scanning done!') except: raise finally: if out_file is not None: self.save(out_file)
[ "def", "scan", "(", "self", ",", "proxy_scanner", ",", "expected_num", "=", "20", ",", "val_thr_num", "=", "4", ",", "queue_timeout", "=", "3", ",", "val_timeout", "=", "5", ",", "out_file", "=", "'proxies.json'", ")", ":", "try", ":", "proxy_scanner", "...
Scan and validate proxies Firstly, call the `scan` method of `proxy_scanner`, then using multiple threads to validate them. Args: proxy_scanner: A ProxyScanner object. expected_num: Max number of valid proxies to be scanned. val_thr_num: Number of threads used for validating proxies. queue_timeout: Timeout for getting a proxy from the queue. val_timeout: An integer passed to `is_valid` as argument `timeout`. out_file: A string or None. If not None, the proxies will be saved into `out_file`.
[ "Scan", "and", "validate", "proxies" ]
38c925758fd3d3e568d3ecc993f77bc0acfa4788
https://github.com/hellock/icrawler/blob/38c925758fd3d3e568d3ecc993f77bc0acfa4788/icrawler/utils/proxy_pool.py#L282-L327
234,393
hellock/icrawler
icrawler/utils/proxy_pool.py
ProxyPool.default_scan
def default_scan(self, region='mainland', expected_num=20, val_thr_num=4, queue_timeout=3, val_timeout=5, out_file='proxies.json', src_files=None): """Default scan method, to simplify the usage of `scan` method. It will register following scan functions: 1. scan_file 2. scan_cnproxy (if region is mainland) 3. scan_free_proxy_list (if region is overseas) 4. scan_ip84 5. scan_mimiip After scanning, all the proxy info will be saved in out_file. Args: region: Either 'mainland' or 'overseas' expected_num: An integer indicating the expected number of proxies, if this argument is set too great, it may take long to finish scanning process. val_thr_num: Number of threads used for validating proxies. queue_timeout: An integer indicating the timeout for getting a candidate proxy from the queue. val_timeout: An integer indicating the timeout when connecting the test url using a candidate proxy. out_file: the file name of the output file saving all the proxy info src_files: A list of file names to scan """ if expected_num > 30: self.logger.warn('The more proxy you expect, the more time it ' 'will take. It is highly recommended to limit the' ' expected num under 30.') proxy_scanner = ProxyScanner() if src_files is None: src_files = [] elif isinstance(src_files, str): src_files = [src_files] for filename in src_files: proxy_scanner.register_func(proxy_scanner.scan_file, {'src_file': filename}) if region == 'mainland': proxy_scanner.register_func(proxy_scanner.scan_cnproxy, {}) elif region == 'overseas': proxy_scanner.register_func(proxy_scanner.scan_free_proxy_list, {}) proxy_scanner.register_func(proxy_scanner.scan_ip84, {'region': region, 'page': 5}) proxy_scanner.register_func(proxy_scanner.scan_mimiip, {'region': region, 'page': 5}) self.scan(proxy_scanner, expected_num, val_thr_num, queue_timeout, val_timeout, out_file)
python
def default_scan(self, region='mainland', expected_num=20, val_thr_num=4, queue_timeout=3, val_timeout=5, out_file='proxies.json', src_files=None): if expected_num > 30: self.logger.warn('The more proxy you expect, the more time it ' 'will take. It is highly recommended to limit the' ' expected num under 30.') proxy_scanner = ProxyScanner() if src_files is None: src_files = [] elif isinstance(src_files, str): src_files = [src_files] for filename in src_files: proxy_scanner.register_func(proxy_scanner.scan_file, {'src_file': filename}) if region == 'mainland': proxy_scanner.register_func(proxy_scanner.scan_cnproxy, {}) elif region == 'overseas': proxy_scanner.register_func(proxy_scanner.scan_free_proxy_list, {}) proxy_scanner.register_func(proxy_scanner.scan_ip84, {'region': region, 'page': 5}) proxy_scanner.register_func(proxy_scanner.scan_mimiip, {'region': region, 'page': 5}) self.scan(proxy_scanner, expected_num, val_thr_num, queue_timeout, val_timeout, out_file)
[ "def", "default_scan", "(", "self", ",", "region", "=", "'mainland'", ",", "expected_num", "=", "20", ",", "val_thr_num", "=", "4", ",", "queue_timeout", "=", "3", ",", "val_timeout", "=", "5", ",", "out_file", "=", "'proxies.json'", ",", "src_files", "=",...
Default scan method, to simplify the usage of `scan` method. It will register following scan functions: 1. scan_file 2. scan_cnproxy (if region is mainland) 3. scan_free_proxy_list (if region is overseas) 4. scan_ip84 5. scan_mimiip After scanning, all the proxy info will be saved in out_file. Args: region: Either 'mainland' or 'overseas' expected_num: An integer indicating the expected number of proxies, if this argument is set too great, it may take long to finish scanning process. val_thr_num: Number of threads used for validating proxies. queue_timeout: An integer indicating the timeout for getting a candidate proxy from the queue. val_timeout: An integer indicating the timeout when connecting the test url using a candidate proxy. out_file: the file name of the output file saving all the proxy info src_files: A list of file names to scan
[ "Default", "scan", "method", "to", "simplify", "the", "usage", "of", "scan", "method", "." ]
38c925758fd3d3e568d3ecc993f77bc0acfa4788
https://github.com/hellock/icrawler/blob/38c925758fd3d3e568d3ecc993f77bc0acfa4788/icrawler/utils/proxy_pool.py#L329-L383
234,394
hellock/icrawler
icrawler/utils/proxy_pool.py
ProxyScanner.register_func
def register_func(self, func_name, func_kwargs): """Register a scan function Args: func_name: The function name of a scan function. func_kwargs: A dict containing arguments of the scan function. """ self.scan_funcs.append(func_name) self.scan_kwargs.append(func_kwargs)
python
def register_func(self, func_name, func_kwargs): self.scan_funcs.append(func_name) self.scan_kwargs.append(func_kwargs)
[ "def", "register_func", "(", "self", ",", "func_name", ",", "func_kwargs", ")", ":", "self", ".", "scan_funcs", ".", "append", "(", "func_name", ")", "self", ".", "scan_kwargs", ".", "append", "(", "func_kwargs", ")" ]
Register a scan function Args: func_name: The function name of a scan function. func_kwargs: A dict containing arguments of the scan function.
[ "Register", "a", "scan", "function" ]
38c925758fd3d3e568d3ecc993f77bc0acfa4788
https://github.com/hellock/icrawler/blob/38c925758fd3d3e568d3ecc993f77bc0acfa4788/icrawler/utils/proxy_pool.py#L406-L414
234,395
hellock/icrawler
icrawler/utils/proxy_pool.py
ProxyScanner.scan_file
def scan_file(self, src_file): """Scan candidate proxies from an existing file""" self.logger.info('start scanning file {} for proxy list...' .format(src_file)) with open(src_file, 'r') as fin: proxies = json.load(fin) for protocol in proxies.keys(): for proxy in proxies[protocol]: self.proxy_queue.put({ 'addr': proxy['addr'], 'protocol': protocol })
python
def scan_file(self, src_file): self.logger.info('start scanning file {} for proxy list...' .format(src_file)) with open(src_file, 'r') as fin: proxies = json.load(fin) for protocol in proxies.keys(): for proxy in proxies[protocol]: self.proxy_queue.put({ 'addr': proxy['addr'], 'protocol': protocol })
[ "def", "scan_file", "(", "self", ",", "src_file", ")", ":", "self", ".", "logger", ".", "info", "(", "'start scanning file {} for proxy list...'", ".", "format", "(", "src_file", ")", ")", "with", "open", "(", "src_file", ",", "'r'", ")", "as", "fin", ":",...
Scan candidate proxies from an existing file
[ "Scan", "candidate", "proxies", "from", "an", "existing", "file" ]
38c925758fd3d3e568d3ecc993f77bc0acfa4788
https://github.com/hellock/icrawler/blob/38c925758fd3d3e568d3ecc993f77bc0acfa4788/icrawler/utils/proxy_pool.py#L499-L510
234,396
hellock/icrawler
icrawler/utils/proxy_pool.py
ProxyScanner.scan
def scan(self): """Start a thread for each registered scan function to scan proxy lists""" self.logger.info('{0} registered scan functions, starting {0} threads ' 'to scan candidate proxy lists...' .format(len(self.scan_funcs))) for i in range(len(self.scan_funcs)): t = threading.Thread( name=self.scan_funcs[i].__name__, target=self.scan_funcs[i], kwargs=self.scan_kwargs[i]) t.daemon = True self.scan_threads.append(t) t.start()
python
def scan(self): self.logger.info('{0} registered scan functions, starting {0} threads ' 'to scan candidate proxy lists...' .format(len(self.scan_funcs))) for i in range(len(self.scan_funcs)): t = threading.Thread( name=self.scan_funcs[i].__name__, target=self.scan_funcs[i], kwargs=self.scan_kwargs[i]) t.daemon = True self.scan_threads.append(t) t.start()
[ "def", "scan", "(", "self", ")", ":", "self", ".", "logger", ".", "info", "(", "'{0} registered scan functions, starting {0} threads '", "'to scan candidate proxy lists...'", ".", "format", "(", "len", "(", "self", ".", "scan_funcs", ")", ")", ")", "for", "i", "...
Start a thread for each registered scan function to scan proxy lists
[ "Start", "a", "thread", "for", "each", "registered", "scan", "function", "to", "scan", "proxy", "lists" ]
38c925758fd3d3e568d3ecc993f77bc0acfa4788
https://github.com/hellock/icrawler/blob/38c925758fd3d3e568d3ecc993f77bc0acfa4788/icrawler/utils/proxy_pool.py#L519-L531
234,397
hellock/icrawler
icrawler/utils/cached_queue.py
CachedQueue.is_duplicated
def is_duplicated(self, item): """Check whether the item has been in the cache If the item has not been seen before, then hash it and put it into the cache, otherwise indicates the item is duplicated. When the cache size exceeds capacity, discard the earliest items in the cache. Args: item (object): The item to be checked and stored in cache. It must be immutable or a list/dict. Returns: bool: Whether the item has been in cache. """ if isinstance(item, dict): hashable_item = json.dumps(item, sort_keys=True) elif isinstance(item, list): hashable_item = frozenset(item) else: hashable_item = item if hashable_item in self._cache: return True else: if self.cache_capacity > 0 and len( self._cache) >= self.cache_capacity: self._cache.popitem(False) self._cache[hashable_item] = 1 return False
python
def is_duplicated(self, item): if isinstance(item, dict): hashable_item = json.dumps(item, sort_keys=True) elif isinstance(item, list): hashable_item = frozenset(item) else: hashable_item = item if hashable_item in self._cache: return True else: if self.cache_capacity > 0 and len( self._cache) >= self.cache_capacity: self._cache.popitem(False) self._cache[hashable_item] = 1 return False
[ "def", "is_duplicated", "(", "self", ",", "item", ")", ":", "if", "isinstance", "(", "item", ",", "dict", ")", ":", "hashable_item", "=", "json", ".", "dumps", "(", "item", ",", "sort_keys", "=", "True", ")", "elif", "isinstance", "(", "item", ",", "...
Check whether the item has been in the cache If the item has not been seen before, then hash it and put it into the cache, otherwise indicates the item is duplicated. When the cache size exceeds capacity, discard the earliest items in the cache. Args: item (object): The item to be checked and stored in cache. It must be immutable or a list/dict. Returns: bool: Whether the item has been in cache.
[ "Check", "whether", "the", "item", "has", "been", "in", "the", "cache" ]
38c925758fd3d3e568d3ecc993f77bc0acfa4788
https://github.com/hellock/icrawler/blob/38c925758fd3d3e568d3ecc993f77bc0acfa4788/icrawler/utils/cached_queue.py#L27-L53
234,398
hellock/icrawler
icrawler/utils/cached_queue.py
CachedQueue.put
def put(self, item, block=True, timeout=None, dup_callback=None): """Put an item to queue if it is not duplicated. """ if not self.is_duplicated(item): super(CachedQueue, self).put(item, block, timeout) else: if dup_callback: dup_callback(item)
python
def put(self, item, block=True, timeout=None, dup_callback=None): if not self.is_duplicated(item): super(CachedQueue, self).put(item, block, timeout) else: if dup_callback: dup_callback(item)
[ "def", "put", "(", "self", ",", "item", ",", "block", "=", "True", ",", "timeout", "=", "None", ",", "dup_callback", "=", "None", ")", ":", "if", "not", "self", ".", "is_duplicated", "(", "item", ")", ":", "super", "(", "CachedQueue", ",", "self", ...
Put an item to queue if it is not duplicated.
[ "Put", "an", "item", "to", "queue", "if", "it", "is", "not", "duplicated", "." ]
38c925758fd3d3e568d3ecc993f77bc0acfa4788
https://github.com/hellock/icrawler/blob/38c925758fd3d3e568d3ecc993f77bc0acfa4788/icrawler/utils/cached_queue.py#L55-L62
234,399
hellock/icrawler
icrawler/utils/signal.py
Signal.set
def set(self, **signals): """Set signals. Args: signals: A dict(key-value pairs) of all signals. For example {'signal1': True, 'signal2': 10} """ for name in signals: if name not in self._signals: self._init_status[name] = signals[name] self._signals[name] = signals[name]
python
def set(self, **signals): for name in signals: if name not in self._signals: self._init_status[name] = signals[name] self._signals[name] = signals[name]
[ "def", "set", "(", "self", ",", "*", "*", "signals", ")", ":", "for", "name", "in", "signals", ":", "if", "name", "not", "in", "self", ".", "_signals", ":", "self", ".", "_init_status", "[", "name", "]", "=", "signals", "[", "name", "]", "self", ...
Set signals. Args: signals: A dict(key-value pairs) of all signals. For example {'signal1': True, 'signal2': 10}
[ "Set", "signals", "." ]
38c925758fd3d3e568d3ecc993f77bc0acfa4788
https://github.com/hellock/icrawler/blob/38c925758fd3d3e568d3ecc993f77bc0acfa4788/icrawler/utils/signal.py#L19-L29