_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q269600
OptionsProviderMixIn.load_defaults
test
def load_defaults(self): """initialize the provider using default values""" for opt, optdict in self.options: action = optdict.get("action") if action != "callback": # callback action have no default if optdict is None: optdict = self.get_option_def(opt) default = optdict.get("default") self.set_option(opt, default, action, optdict)
python
{ "resource": "" }
q269601
OptionsProviderMixIn.option_attrname
test
def option_attrname(self, opt, optdict=None): """get the config attribute corresponding to opt""" if optdict is None: optdict = self.get_option_def(opt) return optdict.get("dest", opt.replace("-", "_"))
python
{ "resource": "" }
q269602
OptionsProviderMixIn.get_option_def
test
def get_option_def(self, opt): """return the dictionary defining an option given its name""" assert self.options for option in self.options: if option[0] == opt: return option[1] raise optparse.OptionError( "no such option %s in section %r" % (opt, self.name), opt )
python
{ "resource": "" }
q269603
OptionsProviderMixIn.options_by_section
test
def options_by_section(self): """return an iterator on options grouped by section (section, [list of (optname, optdict, optvalue)]) """ sections = {} for optname, optdict in self.options: sections.setdefault(optdict.get("group"), []).append( (optname, optdict, self.option_value(optname)) ) if None in sections: yield None, sections.pop(None) for section, options in sorted(sections.items()): yield section.upper(), options
python
{ "resource": "" }
q269604
is_method_call
test
def is_method_call(func, types=(), methods=()): """Determines if a BoundMethod node represents a method call. Args: func (astroid.BoundMethod): The BoundMethod AST node to check. types (Optional[String]): Optional sequence of caller type names to restrict check. methods (Optional[String]): Optional sequence of method names to restrict check. Returns: bool: true if the node represents a method call for the given type and method names, False otherwise. """ return ( isinstance(func, astroid.BoundMethod) and isinstance(func.bound, astroid.Instance) and (func.bound.name in types if types else True) and (func.name in methods if methods else True) )
python
{ "resource": "" }
q269605
is_complex_format_str
test
def is_complex_format_str(node): """Checks if node represents a string with complex formatting specs. Args: node (astroid.node_classes.NodeNG): AST node to check Returns: bool: True if inferred string uses complex formatting, False otherwise """ inferred = utils.safe_infer(node) if inferred is None or not isinstance(inferred.value, str): return True try: parsed = list(string.Formatter().parse(inferred.value)) except ValueError: # This format string is invalid return False for _, _, format_spec, _ in parsed: if format_spec: return True return False
python
{ "resource": "" }
q269606
LoggingChecker.visit_module
test
def visit_module(self, node): # pylint: disable=unused-argument """Clears any state left in this checker from last module checked.""" # The code being checked can just as easily "import logging as foo", # so it is necessary to process the imports and store in this field # what name the logging module is actually given. self._logging_names = set() logging_mods = self.config.logging_modules self._format_style = self.config.logging_format_style self._logging_modules = set(logging_mods) self._from_imports = {} for logging_mod in logging_mods: parts = logging_mod.rsplit(".", 1) if len(parts) > 1: self._from_imports[parts[0]] = parts[1]
python
{ "resource": "" }
q269607
LoggingChecker.visit_importfrom
test
def visit_importfrom(self, node): """Checks to see if a module uses a non-Python logging module.""" try: logging_name = self._from_imports[node.modname] for module, as_name in node.names: if module == logging_name: self._logging_names.add(as_name or module) except KeyError: pass
python
{ "resource": "" }
q269608
LoggingChecker.visit_import
test
def visit_import(self, node): """Checks to see if this module uses Python's built-in logging.""" for module, as_name in node.names: if module in self._logging_modules: self._logging_names.add(as_name or module)
python
{ "resource": "" }
q269609
LoggingChecker.visit_call
test
def visit_call(self, node): """Checks calls to logging methods.""" def is_logging_name(): return ( isinstance(node.func, astroid.Attribute) and isinstance(node.func.expr, astroid.Name) and node.func.expr.name in self._logging_names ) def is_logger_class(): try: for inferred in node.func.infer(): if isinstance(inferred, astroid.BoundMethod): parent = inferred._proxied.parent if isinstance(parent, astroid.ClassDef) and ( parent.qname() == "logging.Logger" or any( ancestor.qname() == "logging.Logger" for ancestor in parent.ancestors() ) ): return True, inferred._proxied.name except astroid.exceptions.InferenceError: pass return False, None if is_logging_name(): name = node.func.attrname else: result, name = is_logger_class() if not result: return self._check_log_method(node, name)
python
{ "resource": "" }
q269610
LoggingChecker._check_format_string
test
def _check_format_string(self, node, format_arg): """Checks that format string tokens match the supplied arguments. Args: node (astroid.node_classes.NodeNG): AST node to be checked. format_arg (int): Index of the format string in the node arguments. """ num_args = _count_supplied_tokens(node.args[format_arg + 1 :]) if not num_args: # If no args were supplied the string is not interpolated and can contain # formatting characters - it's used verbatim. Don't check any further. return format_string = node.args[format_arg].value if not isinstance(format_string, str): # If the log format is constant non-string (e.g. logging.debug(5)), # ensure there are no arguments. required_num_args = 0 else: try: if self._format_style == "old": keyword_args, required_num_args, _, _ = utils.parse_format_string( format_string ) if keyword_args: # Keyword checking on logging strings is complicated by # special keywords - out of scope. return elif self._format_style == "new": keyword_arguments, implicit_pos_args, explicit_pos_args = utils.parse_format_method_string( format_string ) keyword_args_cnt = len( set(k for k, l in keyword_arguments if not isinstance(k, int)) ) required_num_args = ( keyword_args_cnt + implicit_pos_args + explicit_pos_args ) except utils.UnsupportedFormatCharacter as ex: char = format_string[ex.index] self.add_message( "logging-unsupported-format", node=node, args=(char, ord(char), ex.index), ) return except utils.IncompleteFormatString: self.add_message("logging-format-truncated", node=node) return if num_args > required_num_args: self.add_message("logging-too-many-args", node=node) elif num_args < required_num_args: self.add_message("logging-too-few-args", node=node)
python
{ "resource": "" }
q269611
in_loop
test
def in_loop(node): """return True if the node is inside a kind of for loop""" parent = node.parent while parent is not None: if isinstance( parent, ( astroid.For, astroid.ListComp, astroid.SetComp, astroid.DictComp, astroid.GeneratorExp, ), ): return True parent = parent.parent return False
python
{ "resource": "" }
q269612
_get_break_loop_node
test
def _get_break_loop_node(break_node): """ Returns the loop node that holds the break node in arguments. Args: break_node (astroid.Break): the break node of interest. Returns: astroid.For or astroid.While: the loop node holding the break node. """ loop_nodes = (astroid.For, astroid.While) parent = break_node.parent while not isinstance(parent, loop_nodes) or break_node in getattr( parent, "orelse", [] ): break_node = parent parent = parent.parent if parent is None: break return parent
python
{ "resource": "" }
q269613
_loop_exits_early
test
def _loop_exits_early(loop): """ Returns true if a loop may ends up in a break statement. Args: loop (astroid.For, astroid.While): the loop node inspected. Returns: bool: True if the loop may ends up in a break statement, False otherwise. """ loop_nodes = (astroid.For, astroid.While) definition_nodes = (astroid.FunctionDef, astroid.ClassDef) inner_loop_nodes = [ _node for _node in loop.nodes_of_class(loop_nodes, skip_klass=definition_nodes) if _node != loop ] return any( _node for _node in loop.nodes_of_class(astroid.Break, skip_klass=definition_nodes) if _get_break_loop_node(_node) not in inner_loop_nodes )
python
{ "resource": "" }
q269614
_get_properties
test
def _get_properties(config): """Returns a tuple of property classes and names. Property classes are fully qualified, such as 'abc.abstractproperty' and property names are the actual names, such as 'abstract_property'. """ property_classes = {BUILTIN_PROPERTY} property_names = set() # Not returning 'property', it has its own check. if config is not None: property_classes.update(config.property_classes) property_names.update( (prop.rsplit(".", 1)[-1] for prop in config.property_classes) ) return property_classes, property_names
python
{ "resource": "" }
q269615
_determine_function_name_type
test
def _determine_function_name_type(node, config=None): """Determine the name type whose regex the a function's name should match. :param node: A function node. :type node: astroid.node_classes.NodeNG :param config: Configuration from which to pull additional property classes. :type config: :class:`optparse.Values` :returns: One of ('function', 'method', 'attr') :rtype: str """ property_classes, property_names = _get_properties(config) if not node.is_method(): return "function" if node.decorators: decorators = node.decorators.nodes else: decorators = [] for decorator in decorators: # If the function is a property (decorated with @property # or @abc.abstractproperty), the name type is 'attr'. if isinstance(decorator, astroid.Name) or ( isinstance(decorator, astroid.Attribute) and decorator.attrname in property_names ): infered = utils.safe_infer(decorator) if infered and infered.qname() in property_classes: return "attr" # If the function is decorated using the prop_method.{setter,getter} # form, treat it like an attribute as well. elif isinstance(decorator, astroid.Attribute) and decorator.attrname in ( "setter", "deleter", ): return "attr" return "method"
python
{ "resource": "" }
q269616
report_by_type_stats
test
def report_by_type_stats(sect, stats, _): """make a report of * percentage of different types documented * percentage of different types with a bad name """ # percentage of different types documented and/or with a bad name nice_stats = {} for node_type in ("module", "class", "method", "function"): try: total = stats[node_type] except KeyError: raise exceptions.EmptyReportError() nice_stats[node_type] = {} if total != 0: try: documented = total - stats["undocumented_" + node_type] percent = (documented * 100.0) / total nice_stats[node_type]["percent_documented"] = "%.2f" % percent except KeyError: nice_stats[node_type]["percent_documented"] = "NC" try: percent = (stats["badname_" + node_type] * 100.0) / total nice_stats[node_type]["percent_badname"] = "%.2f" % percent except KeyError: nice_stats[node_type]["percent_badname"] = "NC" lines = ("type", "number", "old number", "difference", "%documented", "%badname") for node_type in ("module", "class", "method", "function"): new = stats[node_type] lines += ( node_type, str(new), "NC", "NC", nice_stats[node_type].get("percent_documented", "0"), nice_stats[node_type].get("percent_badname", "0"), ) sect.append(reporter_nodes.Table(children=lines, cols=6, rheaders=1))
python
{ "resource": "" }
q269617
redefined_by_decorator
test
def redefined_by_decorator(node): """return True if the object is a method redefined via decorator. For example: @property def x(self): return self._x @x.setter def x(self, value): self._x = value """ if node.decorators: for decorator in node.decorators.nodes: if ( isinstance(decorator, astroid.Attribute) and getattr(decorator.expr, "name", None) == node.name ): return True return False
python
{ "resource": "" }
q269618
_is_one_arg_pos_call
test
def _is_one_arg_pos_call(call): """Is this a call with exactly 1 argument, where that argument is positional? """ return isinstance(call, astroid.Call) and len(call.args) == 1 and not call.keywords
python
{ "resource": "" }
q269619
BasicErrorChecker.visit_starred
test
def visit_starred(self, node): """Check that a Starred expression is used in an assignment target.""" if isinstance(node.parent, astroid.Call): # f(*args) is converted to Call(args=[Starred]), so ignore # them for this check. return if PY35 and isinstance( node.parent, (astroid.List, astroid.Tuple, astroid.Set, astroid.Dict) ): # PEP 448 unpacking. return stmt = node.statement() if not isinstance(stmt, astroid.Assign): return if stmt.value is node or stmt.value.parent_of(node): self.add_message("star-needs-assignment-target", node=node)
python
{ "resource": "" }
q269620
BasicErrorChecker._check_nonlocal_and_global
test
def _check_nonlocal_and_global(self, node): """Check that a name is both nonlocal and global.""" def same_scope(current): return current.scope() is node from_iter = itertools.chain.from_iterable nonlocals = set( from_iter( child.names for child in node.nodes_of_class(astroid.Nonlocal) if same_scope(child) ) ) if not nonlocals: return global_vars = set( from_iter( child.names for child in node.nodes_of_class(astroid.Global) if same_scope(child) ) ) for name in nonlocals.intersection(global_vars): self.add_message("nonlocal-and-global", args=(name,), node=node)
python
{ "resource": "" }
q269621
BasicErrorChecker.visit_call
test
def visit_call(self, node): """ Check instantiating abstract class with abc.ABCMeta as metaclass. """ try: for inferred in node.func.infer(): self._check_inferred_class_is_abstract(inferred, node) except astroid.InferenceError: return
python
{ "resource": "" }
q269622
BasicErrorChecker._check_else_on_loop
test
def _check_else_on_loop(self, node): """Check that any loop with an else clause has a break statement.""" if node.orelse and not _loop_exits_early(node): self.add_message( "useless-else-on-loop", node=node, # This is not optimal, but the line previous # to the first statement in the else clause # will usually be the one that contains the else:. line=node.orelse[0].lineno - 1, )
python
{ "resource": "" }
q269623
BasicErrorChecker._check_in_loop
test
def _check_in_loop(self, node, node_name): """check that a node is inside a for or while loop""" _node = node.parent while _node: if isinstance(_node, (astroid.For, astroid.While)): if node not in _node.orelse: return if isinstance(_node, (astroid.ClassDef, astroid.FunctionDef)): break if ( isinstance(_node, astroid.TryFinally) and node in _node.finalbody and isinstance(node, astroid.Continue) ): self.add_message("continue-in-finally", node=node) _node = _node.parent self.add_message("not-in-loop", node=node, args=node_name)
python
{ "resource": "" }
q269624
BasicChecker.open
test
def open(self): """initialize visit variables and statistics """ self._tryfinallys = [] self.stats = self.linter.add_stats(module=0, function=0, method=0, class_=0)
python
{ "resource": "" }
q269625
BasicChecker.visit_expr
test
def visit_expr(self, node): """check for various kind of statements without effect""" expr = node.value if isinstance(expr, astroid.Const) and isinstance(expr.value, str): # treat string statement in a separated message # Handle PEP-257 attribute docstrings. # An attribute docstring is defined as being a string right after # an assignment at the module level, class level or __init__ level. scope = expr.scope() if isinstance( scope, (astroid.ClassDef, astroid.Module, astroid.FunctionDef) ): if isinstance(scope, astroid.FunctionDef) and scope.name != "__init__": pass else: sibling = expr.previous_sibling() if ( sibling is not None and sibling.scope() is scope and isinstance(sibling, (astroid.Assign, astroid.AnnAssign)) ): return self.add_message("pointless-string-statement", node=node) return # Ignore if this is : # * a direct function call # * the unique child of a try/except body # * a yieldd statement # * an ellipsis (which can be used on Python 3 instead of pass) # warn W0106 if we have any underlying function call (we can't predict # side effects), else pointless-statement if isinstance( expr, (astroid.Yield, astroid.Await, astroid.Ellipsis, astroid.Call) ) or ( isinstance(node.parent, astroid.TryExcept) and node.parent.body == [node] ): return if any(expr.nodes_of_class(astroid.Call)): self.add_message( "expression-not-assigned", node=node, args=expr.as_string() ) else: self.add_message("pointless-statement", node=node)
python
{ "resource": "" }
q269626
BasicChecker.visit_lambda
test
def visit_lambda(self, node): """check whether or not the lambda is suspicious """ # if the body of the lambda is a call expression with the same # argument list as the lambda itself, then the lambda is # possibly unnecessary and at least suspicious. if node.args.defaults: # If the arguments of the lambda include defaults, then a # judgment cannot be made because there is no way to check # that the defaults defined by the lambda are the same as # the defaults defined by the function called in the body # of the lambda. return call = node.body if not isinstance(call, astroid.Call): # The body of the lambda must be a function call expression # for the lambda to be unnecessary. return if isinstance(node.body.func, astroid.Attribute) and isinstance( node.body.func.expr, astroid.Call ): # Chained call, the intermediate call might # return something else (but we don't check that, yet). return call_site = CallSite.from_call(call) ordinary_args = list(node.args.args) new_call_args = list(self._filter_vararg(node, call.args)) if node.args.kwarg: if self._has_variadic_argument(call.kwargs, node.args.kwarg): return if node.args.vararg: if self._has_variadic_argument(call.starargs, node.args.vararg): return elif call.starargs: return if call.keywords: # Look for additional keyword arguments that are not part # of the lambda's signature lambda_kwargs = {keyword.name for keyword in node.args.defaults} if len(lambda_kwargs) != len(call_site.keyword_arguments): # Different lengths, so probably not identical return if set(call_site.keyword_arguments).difference(lambda_kwargs): return # The "ordinary" arguments must be in a correspondence such that: # ordinary_args[i].name == call.args[i].name. if len(ordinary_args) != len(new_call_args): return for arg, passed_arg in zip(ordinary_args, new_call_args): if not isinstance(passed_arg, astroid.Name): return if arg.name != passed_arg.name: return self.add_message("unnecessary-lambda", line=node.fromlineno, node=node)
python
{ "resource": "" }
q269627
BasicChecker.visit_assert
test
def visit_assert(self, node): """check the use of an assert statement on a tuple.""" if ( node.fail is None and isinstance(node.test, astroid.Tuple) and len(node.test.elts) == 2 ): self.add_message("assert-on-tuple", node=node)
python
{ "resource": "" }
q269628
BasicChecker.visit_dict
test
def visit_dict(self, node): """check duplicate key in dictionary""" keys = set() for k, _ in node.items: if isinstance(k, astroid.Const): key = k.value if key in keys: self.add_message("duplicate-key", node=node, args=key) keys.add(key)
python
{ "resource": "" }
q269629
BasicChecker._check_unreachable
test
def _check_unreachable(self, node): """check unreachable code""" unreach_stmt = node.next_sibling() if unreach_stmt is not None: self.add_message("unreachable", node=unreach_stmt)
python
{ "resource": "" }
q269630
BasicChecker._check_not_in_finally
test
def _check_not_in_finally(self, node, node_name, breaker_classes=()): """check that a node is not inside a finally clause of a try...finally statement. If we found before a try...finally bloc a parent which its type is in breaker_classes, we skip the whole check.""" # if self._tryfinallys is empty, we're not an in try...finally block if not self._tryfinallys: return # the node could be a grand-grand...-children of the try...finally _parent = node.parent _node = node while _parent and not isinstance(_parent, breaker_classes): if hasattr(_parent, "finalbody") and _node in _parent.finalbody: self.add_message("lost-exception", node=node, args=node_name) return _node = _parent _parent = _node.parent
python
{ "resource": "" }
q269631
BasicChecker._check_reversed
test
def _check_reversed(self, node): """ check that the argument to `reversed` is a sequence """ try: argument = utils.safe_infer(utils.get_argument_from_call(node, position=0)) except utils.NoSuchArgumentError: pass else: if argument is astroid.Uninferable: return if argument is None: # Nothing was infered. # Try to see if we have iter(). if isinstance(node.args[0], astroid.Call): try: func = next(node.args[0].func.infer()) except astroid.InferenceError: return if getattr( func, "name", None ) == "iter" and utils.is_builtin_object(func): self.add_message("bad-reversed-sequence", node=node) return if isinstance(argument, (astroid.List, astroid.Tuple)): return if isinstance(argument, astroid.Instance): if argument._proxied.name == "dict" and utils.is_builtin_object( argument._proxied ): self.add_message("bad-reversed-sequence", node=node) return if any( ancestor.name == "dict" and utils.is_builtin_object(ancestor) for ancestor in argument._proxied.ancestors() ): # Mappings aren't accepted by reversed(), unless # they provide explicitly a __reversed__ method. try: argument.locals[REVERSED_PROTOCOL_METHOD] except KeyError: self.add_message("bad-reversed-sequence", node=node) return if hasattr(argument, "getattr"): # everything else is not a proper sequence for reversed() for methods in REVERSED_METHODS: for meth in methods: try: argument.getattr(meth) except astroid.NotFoundError: break else: break else: self.add_message("bad-reversed-sequence", node=node) else: self.add_message("bad-reversed-sequence", node=node)
python
{ "resource": "" }
q269632
NameChecker.visit_assignname
test
def visit_assignname(self, node): """check module level assigned names""" self._check_assign_to_new_keyword_violation(node.name, node) frame = node.frame() assign_type = node.assign_type() if isinstance(assign_type, astroid.Comprehension): self._check_name("inlinevar", node.name, node) elif isinstance(frame, astroid.Module): if isinstance(assign_type, astroid.Assign) and not in_loop(assign_type): if isinstance(utils.safe_infer(assign_type.value), astroid.ClassDef): self._check_name("class", node.name, node) else: if not _redefines_import(node): # Don't emit if the name redefines an import # in an ImportError except handler. self._check_name("const", node.name, node) elif isinstance(assign_type, astroid.ExceptHandler): self._check_name("variable", node.name, node) elif isinstance(frame, astroid.FunctionDef): # global introduced variable aren't in the function locals if node.name in frame and node.name not in frame.argnames(): if not _redefines_import(node): self._check_name("variable", node.name, node) elif isinstance(frame, astroid.ClassDef): if not list(frame.local_attr_ancestors(node.name)): self._check_name("class_attribute", node.name, node)
python
{ "resource": "" }
q269633
NameChecker._check_name
test
def _check_name(self, node_type, name, node, confidence=interfaces.HIGH): """check for a name using the type's regexp""" def _should_exempt_from_invalid_name(node): if node_type == "variable": inferred = utils.safe_infer(node) if isinstance(inferred, astroid.ClassDef): return True return False if utils.is_inside_except(node): clobbering, _ = utils.clobber_in_except(node) if clobbering: return if name in self.config.good_names: return if name in self.config.bad_names: self.stats["badname_" + node_type] += 1 self.add_message("blacklisted-name", node=node, args=name) return regexp = self._name_regexps[node_type] match = regexp.match(name) if _is_multi_naming_match(match, node_type, confidence): name_group = self._find_name_group(node_type) bad_name_group = self._bad_names.setdefault(name_group, {}) warnings = bad_name_group.setdefault(match.lastgroup, []) warnings.append((node, node_type, name, confidence)) if match is None and not _should_exempt_from_invalid_name(node): self._raise_name_warning(node, node_type, name, confidence)
python
{ "resource": "" }
q269634
DocStringChecker._check_docstring
test
def _check_docstring( self, node_type, node, report_missing=True, confidence=interfaces.HIGH ): """check the node has a non empty docstring""" docstring = node.doc if docstring is None: if not report_missing: return lines = utils.get_node_last_lineno(node) - node.lineno if node_type == "module" and not lines: # If the module has no body, there's no reason # to require a docstring. return max_lines = self.config.docstring_min_length if node_type != "module" and max_lines > -1 and lines < max_lines: return self.stats["undocumented_" + node_type] += 1 if ( node.body and isinstance(node.body[0], astroid.Expr) and isinstance(node.body[0].value, astroid.Call) ): # Most likely a string with a format call. Let's see. func = utils.safe_infer(node.body[0].value.func) if isinstance(func, astroid.BoundMethod) and isinstance( func.bound, astroid.Instance ): # Strings in Python 3, others in Python 2. if PY3K and func.bound.name == "str": return if func.bound.name in ("str", "unicode", "bytes"): return self.add_message( "missing-docstring", node=node, args=(node_type,), confidence=confidence ) elif not docstring.strip(): self.stats["undocumented_" + node_type] += 1 self.add_message( "empty-docstring", node=node, args=(node_type,), confidence=confidence )
python
{ "resource": "" }
q269635
ComparisonChecker._check_literal_comparison
test
def _check_literal_comparison(self, literal, node): """Check if we compare to a literal, which is usually what we do not want to do.""" nodes = (astroid.List, astroid.Tuple, astroid.Dict, astroid.Set) is_other_literal = isinstance(literal, nodes) is_const = False if isinstance(literal, astroid.Const): if isinstance(literal.value, bool) or literal.value is None: # Not interested in this values. return is_const = isinstance(literal.value, (bytes, str, int, float)) if is_const or is_other_literal: self.add_message("literal-comparison", node=node)
python
{ "resource": "" }
q269636
PathGraphingAstVisitor._subgraph
test
def _subgraph(self, node, name, extra_blocks=()): """create the subgraphs representing any `if` and `for` statements""" if self.graph is None: # global loop self.graph = PathGraph(node) self._subgraph_parse(node, node, extra_blocks) self.graphs["%s%s" % (self.classname, name)] = self.graph self.reset() else: self._append_node(node) self._subgraph_parse(node, node, extra_blocks)
python
{ "resource": "" }
q269637
PathGraphingAstVisitor._subgraph_parse
test
def _subgraph_parse( self, node, pathnode, extra_blocks ): # pylint: disable=unused-argument """parse the body and any `else` block of `if` and `for` statements""" loose_ends = [] self.tail = node self.dispatch_list(node.body) loose_ends.append(self.tail) for extra in extra_blocks: self.tail = node self.dispatch_list(extra.body) loose_ends.append(self.tail) if node.orelse: self.tail = node self.dispatch_list(node.orelse) loose_ends.append(self.tail) else: loose_ends.append(node) if node: bottom = "%s" % self._bottom_counter self._bottom_counter += 1 for le in loose_ends: self.graph.connect(le, bottom) self.tail = bottom
python
{ "resource": "" }
q269638
McCabeMethodChecker.visit_module
test
def visit_module(self, node): """visit an astroid.Module node to check too complex rating and add message if is greather than max_complexity stored from options""" visitor = PathGraphingAstVisitor() for child in node.body: visitor.preorder(child, visitor) for graph in visitor.graphs.values(): complexity = graph.complexity() node = graph.root if hasattr(node, "name"): node_name = "'%s'" % node.name else: node_name = "This '%s'" % node.__class__.__name__.lower() if complexity <= self.config.max_complexity: continue self.add_message( "too-complex", node=node, confidence=HIGH, args=(node_name, complexity) )
python
{ "resource": "" }
q269639
ASTWalker.add_checker
test
def add_checker(self, checker): """walk to the checker's dir and collect visit and leave methods""" # XXX : should be possible to merge needed_checkers and add_checker vcids = set() lcids = set() visits = self.visit_events leaves = self.leave_events for member in dir(checker): cid = member[6:] if cid == "default": continue if member.startswith("visit_"): v_meth = getattr(checker, member) # don't use visit_methods with no activated message: if self._is_method_enabled(v_meth): visits[cid].append(v_meth) vcids.add(cid) elif member.startswith("leave_"): l_meth = getattr(checker, member) # don't use leave_methods with no activated message: if self._is_method_enabled(l_meth): leaves[cid].append(l_meth) lcids.add(cid) visit_default = getattr(checker, "visit_default", None) if visit_default: for cls in nodes.ALL_NODE_CLASSES: cid = cls.__name__.lower() if cid not in vcids: visits[cid].append(visit_default)
python
{ "resource": "" }
q269640
ASTWalker.walk
test
def walk(self, astroid): """call visit events of astroid checkers for the given node, recurse on its children, then leave events. """ cid = astroid.__class__.__name__.lower() # Detect if the node is a new name for a deprecated alias. # In this case, favour the methods for the deprecated # alias if any, in order to maintain backwards # compatibility. visit_events = self.visit_events.get(cid, ()) leave_events = self.leave_events.get(cid, ()) if astroid.is_statement: self.nbstatements += 1 # generate events for this node on each checker for cb in visit_events or (): cb(astroid) # recurse on children for child in astroid.get_children(): self.walk(child) for cb in leave_events or (): cb(astroid)
python
{ "resource": "" }
q269641
ClassDiagram.add_relationship
test
def add_relationship(self, from_object, to_object, relation_type, name=None): """create a relation ship """ rel = Relationship(from_object, to_object, relation_type, name) self.relationships.setdefault(relation_type, []).append(rel)
python
{ "resource": "" }
q269642
ClassDiagram.get_relationship
test
def get_relationship(self, from_object, relation_type): """return a relation ship or None """ for rel in self.relationships.get(relation_type, ()): if rel.from_object is from_object: return rel raise KeyError(relation_type)
python
{ "resource": "" }
q269643
ClassDiagram.get_attrs
test
def get_attrs(self, node): """return visible attributes, possibly with class name""" attrs = [] properties = [ (n, m) for n, m in node.items() if isinstance(m, astroid.FunctionDef) and decorated_with_property(m) ] for node_name, associated_nodes in ( list(node.instance_attrs_type.items()) + list(node.locals_type.items()) + properties ): if not self.show_attr(node_name): continue names = self.class_names(associated_nodes) if names: node_name = "%s : %s" % (node_name, ", ".join(names)) attrs.append(node_name) return sorted(attrs)
python
{ "resource": "" }
q269644
ClassDiagram.get_methods
test
def get_methods(self, node): """return visible methods""" methods = [ m for m in node.values() if isinstance(m, astroid.FunctionDef) and not decorated_with_property(m) and self.show_attr(m.name) ] return sorted(methods, key=lambda n: n.name)
python
{ "resource": "" }
q269645
ClassDiagram.add_object
test
def add_object(self, title, node): """create a diagram object """ assert node not in self._nodes ent = DiagramEntity(title, node) self._nodes[node] = ent self.objects.append(ent)
python
{ "resource": "" }
q269646
ClassDiagram.class_names
test
def class_names(self, nodes): """return class names if needed in diagram""" names = [] for node in nodes: if isinstance(node, astroid.Instance): node = node._proxied if ( isinstance(node, astroid.ClassDef) and hasattr(node, "name") and not self.has_node(node) ): if node.name not in names: node_name = node.name names.append(node_name) return names
python
{ "resource": "" }
q269647
ClassDiagram.classes
test
def classes(self): """return all class nodes in the diagram""" return [o for o in self.objects if isinstance(o.node, astroid.ClassDef)]
python
{ "resource": "" }
q269648
ClassDiagram.classe
test
def classe(self, name): """return a class by its name, raise KeyError if not found """ for klass in self.classes(): if klass.node.name == name: return klass raise KeyError(name)
python
{ "resource": "" }
q269649
PackageDiagram.modules
test
def modules(self): """return all module nodes in the diagram""" return [o for o in self.objects if isinstance(o.node, astroid.Module)]
python
{ "resource": "" }
q269650
PackageDiagram.module
test
def module(self, name): """return a module by its name, raise KeyError if not found """ for mod in self.modules(): if mod.node.name == name: return mod raise KeyError(name)
python
{ "resource": "" }
q269651
PackageDiagram.get_module
test
def get_module(self, name, node): """return a module by its name, looking also for relative imports; raise KeyError if not found """ for mod in self.modules(): mod_name = mod.node.name if mod_name == name: return mod # search for fullname of relative import modules package = node.root().name if mod_name == "%s.%s" % (package, name): return mod if mod_name == "%s.%s" % (package.rsplit(".", 1)[0], name): return mod raise KeyError(name)
python
{ "resource": "" }
q269652
PackageDiagram.add_from_depend
test
def add_from_depend(self, node, from_module): """add dependencies created by from-imports """ mod_name = node.root().name obj = self.module(mod_name) if from_module not in obj.node.depends: obj.node.depends.append(from_module)
python
{ "resource": "" }
q269653
Grant.delete
test
def delete(self): """Removes itself from the cache Note: This is required by the oauthlib """ log.debug( "Deleting grant %s for client %s" % (self.code, self.client_id) ) self._cache.delete(self.key) return None
python
{ "resource": "" }
q269654
BaseBinding.query
test
def query(self): """Determines which method of getting the query object for use""" if hasattr(self.model, 'query'): return self.model.query else: return self.session.query(self.model)
python
{ "resource": "" }
q269655
UserBinding.get
test
def get(self, username, password, *args, **kwargs): """Returns the User object Returns None if the user isn't found or the passwords don't match :param username: username of the user :param password: password of the user """ user = self.query.filter_by(username=username).first() if user and user.check_password(password): return user return None
python
{ "resource": "" }
q269656
TokenBinding.get
test
def get(self, access_token=None, refresh_token=None): """returns a Token object with the given access token or refresh token :param access_token: User's access token :param refresh_token: User's refresh token """ if access_token: return self.query.filter_by(access_token=access_token).first() elif refresh_token: return self.query.filter_by(refresh_token=refresh_token).first() return None
python
{ "resource": "" }
q269657
TokenBinding.set
test
def set(self, token, request, *args, **kwargs): """Creates a Token object and removes all expired tokens that belong to the user :param token: token object :param request: OAuthlib request object """ if hasattr(request, 'user') and request.user: user = request.user elif self.current_user: # for implicit token user = self.current_user() client = request.client tokens = self.query.filter_by( client_id=client.client_id, user_id=user.id).all() if tokens: for tk in tokens: self.session.delete(tk) self.session.commit() expires_in = token.get('expires_in') expires = datetime.utcnow() + timedelta(seconds=expires_in) tok = self.model(**token) tok.expires = expires tok.client_id = client.client_id tok.user_id = user.id self.session.add(tok) self.session.commit() return tok
python
{ "resource": "" }
q269658
GrantBinding.set
test
def set(self, client_id, code, request, *args, **kwargs): """Creates Grant object with the given params :param client_id: ID of the client :param code: :param request: OAuthlib request object """ expires = datetime.utcnow() + timedelta(seconds=100) grant = self.model( client_id=request.client.client_id, code=code['code'], redirect_uri=request.redirect_uri, scope=' '.join(request.scopes), user=self.current_user(), expires=expires ) self.session.add(grant) self.session.commit()
python
{ "resource": "" }
q269659
GrantBinding.get
test
def get(self, client_id, code): """Get the Grant object with the given client ID and code :param client_id: ID of the client :param code: """ return self.query.filter_by(client_id=client_id, code=code).first()
python
{ "resource": "" }
q269660
prepare_request
test
def prepare_request(uri, headers=None, data=None, method=None): """Make request parameters right.""" if headers is None: headers = {} if data and not method: method = 'POST' elif not method: method = 'GET' if method == 'GET' and data: uri = add_params_to_uri(uri, data) data = None return uri, headers, data, method
python
{ "resource": "" }
q269661
OAuth.init_app
test
def init_app(self, app): """Init app with Flask instance. You can also pass the instance of Flask later:: oauth = OAuth() oauth.init_app(app) """ self.app = app app.extensions = getattr(app, 'extensions', {}) app.extensions[self.state_key] = self
python
{ "resource": "" }
q269662
OAuth.remote_app
test
def remote_app(self, name, register=True, **kwargs): """Registers a new remote application. :param name: the name of the remote application :param register: whether the remote app will be registered Find more parameters from :class:`OAuthRemoteApp`. """ remote = OAuthRemoteApp(self, name, **kwargs) if register: assert name not in self.remote_apps self.remote_apps[name] = remote return remote
python
{ "resource": "" }
q269663
OAuthRemoteApp.request
test
def request(self, url, data=None, headers=None, format='urlencoded', method='GET', content_type=None, token=None): """ Sends a request to the remote server with OAuth tokens attached. :param data: the data to be sent to the server. :param headers: an optional dictionary of headers. :param format: the format for the `data`. Can be `urlencoded` for URL encoded data or `json` for JSON. :param method: the HTTP request method to use. :param content_type: an optional content type. If a content type is provided, the data is passed as it, and the `format` is ignored. :param token: an optional token to pass, if it is None, token will be generated by tokengetter. """ headers = dict(headers or {}) if token is None: token = self.get_request_token() client = self.make_client(token) url = self.expand_url(url) if method == 'GET': assert format == 'urlencoded' if data: url = add_params_to_uri(url, data) data = None else: if content_type is None: data, content_type = encode_request_data(data, format) if content_type is not None: headers['Content-Type'] = content_type if self.request_token_url: # oauth1 uri, headers, body = client.sign( url, http_method=method, body=data, headers=headers ) else: # oauth2 uri, headers, body = client.add_token( url, http_method=method, body=data, headers=headers ) if hasattr(self, 'pre_request'): # This is designed for some rubbish services like weibo. # Since they don't follow the standards, we need to # change the uri, headers, or body. uri, headers, body = self.pre_request(uri, headers, body) if body: data = to_bytes(body, self.encoding) else: data = None resp, content = self.http_request( uri, headers, data=to_bytes(body, self.encoding), method=method ) return OAuthResponse(resp, content, self.content_type)
python
{ "resource": "" }
q269664
OAuthRemoteApp.authorize
test
def authorize(self, callback=None, state=None, **kwargs): """ Returns a redirect response to the remote authorization URL with the signed callback given. :param callback: a redirect url for the callback :param state: an optional value to embed in the OAuth request. Use this if you want to pass around application state (e.g. CSRF tokens). :param kwargs: add optional key/value pairs to the query string """ params = dict(self.request_token_params) or {} params.update(**kwargs) if self.request_token_url: token = self.generate_request_token(callback)[0] url = '%s?oauth_token=%s' % ( self.expand_url(self.authorize_url), url_quote(token) ) if params: url += '&' + url_encode(params) else: assert callback is not None, 'Callback is required for OAuth2' client = self.make_client() if 'scope' in params: scope = params.pop('scope') else: scope = None if isinstance(scope, str): # oauthlib need unicode scope = _encode(scope, self.encoding) if 'state' in params: if not state: state = params.pop('state') else: # remove state in params params.pop('state') if callable(state): # state can be function for generate a random string state = state() session['%s_oauthredir' % self.name] = callback url = client.prepare_request_uri( self.expand_url(self.authorize_url), redirect_uri=callback, scope=scope, state=state, **params ) return redirect(url)
python
{ "resource": "" }
q269665
OAuthRemoteApp.handle_oauth1_response
test
def handle_oauth1_response(self, args): """Handles an oauth1 authorization response.""" client = self.make_client() client.verifier = args.get('oauth_verifier') tup = session.get('%s_oauthtok' % self.name) if not tup: raise OAuthException( 'Token not found, maybe you disabled cookie', type='token_not_found' ) client.resource_owner_key = tup[0] client.resource_owner_secret = tup[1] uri, headers, data = client.sign( self.expand_url(self.access_token_url), _encode(self.access_token_method) ) headers.update(self._access_token_headers) resp, content = self.http_request( uri, headers, to_bytes(data, self.encoding), method=self.access_token_method ) data = parse_response(resp, content) if resp.code not in (200, 201): raise OAuthException( 'Invalid response from %s' % self.name, type='invalid_response', data=data ) return data
python
{ "resource": "" }
q269666
OAuthRemoteApp.handle_oauth2_response
test
def handle_oauth2_response(self, args): """Handles an oauth2 authorization response.""" client = self.make_client() remote_args = { 'code': args.get('code'), 'client_secret': self.consumer_secret, 'redirect_uri': session.get('%s_oauthredir' % self.name) } log.debug('Prepare oauth2 remote args %r', remote_args) remote_args.update(self.access_token_params) headers = copy(self._access_token_headers) if self.access_token_method == 'POST': headers.update({'Content-Type': 'application/x-www-form-urlencoded'}) body = client.prepare_request_body(**remote_args) resp, content = self.http_request( self.expand_url(self.access_token_url), headers=headers, data=to_bytes(body, self.encoding), method=self.access_token_method, ) elif self.access_token_method == 'GET': qs = client.prepare_request_body(**remote_args) url = self.expand_url(self.access_token_url) url += ('?' in url and '&' or '?') + qs resp, content = self.http_request( url, headers=headers, method=self.access_token_method, ) else: raise OAuthException( 'Unsupported access_token_method: %s' % self.access_token_method ) data = parse_response(resp, content, content_type=self.content_type) if resp.code not in (200, 201): raise OAuthException( 'Invalid response from %s' % self.name, type='invalid_response', data=data ) return data
python
{ "resource": "" }
q269667
OAuthRemoteApp.authorized_response
test
def authorized_response(self, args=None): """Handles authorization response smartly.""" if args is None: args = request.args if 'oauth_verifier' in args: data = self.handle_oauth1_response(args) elif 'code' in args: data = self.handle_oauth2_response(args) else: data = self.handle_unknown_response() # free request token session.pop('%s_oauthtok' % self.name, None) session.pop('%s_oauthredir' % self.name, None) return data
python
{ "resource": "" }
q269668
OAuthRemoteApp.authorized_handler
test
def authorized_handler(self, f): """Handles an OAuth callback. .. versionchanged:: 0.7 @authorized_handler is deprecated in favor of authorized_response. """ @wraps(f) def decorated(*args, **kwargs): log.warn( '@authorized_handler is deprecated in favor of ' 'authorized_response' ) data = self.authorized_response() return f(*((data,) + args), **kwargs) return decorated
python
{ "resource": "" }
q269669
_hash_token
test
def _hash_token(application, token): """Creates a hashable object for given token then we could use it as a dictionary key. """ if isinstance(token, dict): hashed_token = tuple(sorted(token.items())) elif isinstance(token, tuple): hashed_token = token else: raise TypeError('%r is unknown type of token' % token) return (application.__class__.__name__, application.name, hashed_token)
python
{ "resource": "" }
q269670
BaseApplication._make_client_with_token
test
def _make_client_with_token(self, token): """Uses cached client or create new one with specific token.""" cached_clients = getattr(self, 'clients', None) hashed_token = _hash_token(self, token) if cached_clients and hashed_token in cached_clients: return cached_clients[hashed_token] client = self.make_client(token) # implemented in subclasses if cached_clients: cached_clients[hashed_token] = client return client
python
{ "resource": "" }
q269671
OAuth1Application.make_client
test
def make_client(self, token): """Creates a client with specific access token pair. :param token: a tuple of access token pair ``(token, token_secret)`` or a dictionary of access token response. :returns: a :class:`requests_oauthlib.oauth1_session.OAuth1Session` object. """ if isinstance(token, dict): access_token = token['oauth_token'] access_token_secret = token['oauth_token_secret'] else: access_token, access_token_secret = token return self.make_oauth_session( resource_owner_key=access_token, resource_owner_secret=access_token_secret)
python
{ "resource": "" }
q269672
OAuth2Application.insecure_transport
test
def insecure_transport(self): """Creates a context to enable the oauthlib environment variable in order to debug with insecure transport. """ origin = os.environ.get('OAUTHLIB_INSECURE_TRANSPORT') if current_app.debug or current_app.testing: try: os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = '1' yield finally: if origin: os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = origin else: os.environ.pop('OAUTHLIB_INSECURE_TRANSPORT', None) else: if origin: warnings.warn( 'OAUTHLIB_INSECURE_TRANSPORT has been found in os.environ ' 'but the app is not running in debug mode or testing mode.' ' It may put you in danger of the Man-in-the-middle attack' ' while using OAuth 2.', RuntimeWarning) yield
python
{ "resource": "" }
q269673
OAuth1Provider.confirm_authorization_request
test
def confirm_authorization_request(self): """When consumer confirm the authrozation.""" server = self.server uri, http_method, body, headers = extract_params() try: realms, credentials = server.get_realms_and_credentials( uri, http_method=http_method, body=body, headers=headers ) ret = server.create_authorization_response( uri, http_method, body, headers, realms, credentials ) log.debug('Authorization successful.') return create_response(*ret) except errors.OAuth1Error as e: return redirect(e.in_uri(self.error_uri)) except errors.InvalidClientError as e: return redirect(e.in_uri(self.error_uri))
python
{ "resource": "" }
q269674
OAuth1Provider.request_token_handler
test
def request_token_handler(self, f): """Request token handler decorator. The decorated function should return an dictionary or None as the extra credentials for creating the token response. If you don't need to add any extra credentials, it could be as simple as:: @app.route('/oauth/request_token') @oauth.request_token_handler def request_token(): return {} """ @wraps(f) def decorated(*args, **kwargs): server = self.server uri, http_method, body, headers = extract_params() credentials = f(*args, **kwargs) try: ret = server.create_request_token_response( uri, http_method, body, headers, credentials) return create_response(*ret) except errors.OAuth1Error as e: return _error_response(e) return decorated
python
{ "resource": "" }
q269675
OAuth1RequestValidator.get_client_secret
test
def get_client_secret(self, client_key, request): """Get client secret. The client object must has ``client_secret`` attribute. """ log.debug('Get client secret of %r', client_key) if not request.client: request.client = self._clientgetter(client_key=client_key) if request.client: return request.client.client_secret return None
python
{ "resource": "" }
q269676
OAuth1RequestValidator.get_request_token_secret
test
def get_request_token_secret(self, client_key, token, request): """Get request token secret. The request token object should a ``secret`` attribute. """ log.debug('Get request token secret of %r for %r', token, client_key) tok = request.request_token or self._grantgetter(token=token) if tok and tok.client_key == client_key: request.request_token = tok return tok.secret return None
python
{ "resource": "" }
q269677
OAuth1RequestValidator.get_access_token_secret
test
def get_access_token_secret(self, client_key, token, request): """Get access token secret. The access token object should a ``secret`` attribute. """ log.debug('Get access token secret of %r for %r', token, client_key) tok = request.access_token or self._tokengetter( client_key=client_key, token=token, ) if tok: request.access_token = tok return tok.secret return None
python
{ "resource": "" }
q269678
OAuth1RequestValidator.get_default_realms
test
def get_default_realms(self, client_key, request): """Default realms of the client.""" log.debug('Get realms for %r', client_key) if not request.client: request.client = self._clientgetter(client_key=client_key) client = request.client if hasattr(client, 'default_realms'): return client.default_realms return []
python
{ "resource": "" }
q269679
OAuth1RequestValidator.get_realms
test
def get_realms(self, token, request): """Realms for this request token.""" log.debug('Get realms of %r', token) tok = request.request_token or self._grantgetter(token=token) if not tok: return [] request.request_token = tok if hasattr(tok, 'realms'): return tok.realms or [] return []
python
{ "resource": "" }
q269680
OAuth1RequestValidator.get_redirect_uri
test
def get_redirect_uri(self, token, request): """Redirect uri for this request token.""" log.debug('Get redirect uri of %r', token) tok = request.request_token or self._grantgetter(token=token) return tok.redirect_uri
python
{ "resource": "" }
q269681
OAuth1RequestValidator.get_rsa_key
test
def get_rsa_key(self, client_key, request): """Retrieves a previously stored client provided RSA key.""" if not request.client: request.client = self._clientgetter(client_key=client_key) if hasattr(request.client, 'rsa_key'): return request.client.rsa_key return None
python
{ "resource": "" }
q269682
OAuth1RequestValidator.validate_client_key
test
def validate_client_key(self, client_key, request): """Validates that supplied client key.""" log.debug('Validate client key for %r', client_key) if not request.client: request.client = self._clientgetter(client_key=client_key) if request.client: return True return False
python
{ "resource": "" }
q269683
OAuth1RequestValidator.validate_request_token
test
def validate_request_token(self, client_key, token, request): """Validates request token is available for client.""" log.debug('Validate request token %r for %r', token, client_key) tok = request.request_token or self._grantgetter(token=token) if tok and tok.client_key == client_key: request.request_token = tok return True return False
python
{ "resource": "" }
q269684
OAuth1RequestValidator.validate_access_token
test
def validate_access_token(self, client_key, token, request): """Validates access token is available for client.""" log.debug('Validate access token %r for %r', token, client_key) tok = request.access_token or self._tokengetter( client_key=client_key, token=token, ) if tok: request.access_token = tok return True return False
python
{ "resource": "" }
q269685
OAuth1RequestValidator.validate_timestamp_and_nonce
test
def validate_timestamp_and_nonce(self, client_key, timestamp, nonce, request, request_token=None, access_token=None): """Validate the timestamp and nonce is used or not.""" log.debug('Validate timestamp and nonce %r', client_key) nonce_exists = self._noncegetter( client_key=client_key, timestamp=timestamp, nonce=nonce, request_token=request_token, access_token=access_token ) if nonce_exists: return False self._noncesetter( client_key=client_key, timestamp=timestamp, nonce=nonce, request_token=request_token, access_token=access_token ) return True
python
{ "resource": "" }
q269686
OAuth1RequestValidator.validate_redirect_uri
test
def validate_redirect_uri(self, client_key, redirect_uri, request): """Validate if the redirect_uri is allowed by the client.""" log.debug('Validate redirect_uri %r for %r', redirect_uri, client_key) if not request.client: request.client = self._clientgetter(client_key=client_key) if not request.client: return False if not request.client.redirect_uris and redirect_uri is None: return True request.redirect_uri = redirect_uri return redirect_uri in request.client.redirect_uris
python
{ "resource": "" }
q269687
OAuth1RequestValidator.validate_realms
test
def validate_realms(self, client_key, token, request, uri=None, realms=None): """Check if the token has permission on those realms.""" log.debug('Validate realms %r for %r', realms, client_key) if request.access_token: tok = request.access_token else: tok = self._tokengetter(client_key=client_key, token=token) request.access_token = tok if not tok: return False return set(tok.realms).issuperset(set(realms))
python
{ "resource": "" }
q269688
OAuth1RequestValidator.validate_verifier
test
def validate_verifier(self, client_key, token, verifier, request): """Validate verifier exists.""" log.debug('Validate verifier %r for %r', verifier, client_key) data = self._verifiergetter(verifier=verifier, token=token) if not data: return False if not hasattr(data, 'user'): log.debug('Verifier should has user attribute') return False request.user = data.user if hasattr(data, 'client_key'): return data.client_key == client_key return True
python
{ "resource": "" }
q269689
OAuth1RequestValidator.verify_request_token
test
def verify_request_token(self, token, request): """Verify if the request token is existed.""" log.debug('Verify request token %r', token) tok = request.request_token or self._grantgetter(token=token) if tok: request.request_token = tok return True return False
python
{ "resource": "" }
q269690
OAuth1RequestValidator.verify_realms
test
def verify_realms(self, token, realms, request): """Verify if the realms match the requested realms.""" log.debug('Verify realms %r', realms) tok = request.request_token or self._grantgetter(token=token) if not tok: return False request.request_token = tok if not hasattr(tok, 'realms'): # realms not enabled return True return set(tok.realms) == set(realms)
python
{ "resource": "" }
q269691
OAuth1RequestValidator.save_access_token
test
def save_access_token(self, token, request): """Save access token to database. A tokensetter is required, which accepts a token and request parameters:: def tokensetter(token, request): access_token = Token( client=request.client, user=request.user, token=token['oauth_token'], secret=token['oauth_token_secret'], realms=token['oauth_authorized_realms'], ) return access_token.save() """ log.debug('Save access token %r', token) self._tokensetter(token, request)
python
{ "resource": "" }
q269692
OAuth1RequestValidator.save_request_token
test
def save_request_token(self, token, request): """Save request token to database. A grantsetter is required, which accepts a token and request parameters:: def grantsetter(token, request): grant = Grant( token=token['oauth_token'], secret=token['oauth_token_secret'], client=request.client, redirect_uri=oauth.redirect_uri, realms=request.realms, ) return grant.save() """ log.debug('Save request token %r', token) self._grantsetter(token, request)
python
{ "resource": "" }
q269693
OAuth1RequestValidator.save_verifier
test
def save_verifier(self, token, verifier, request): """Save verifier to database. A verifiersetter is required. It would be better to combine request token and verifier together:: def verifiersetter(token, verifier, request): tok = Grant.query.filter_by(token=token).first() tok.verifier = verifier['oauth_verifier'] tok.user = get_current_user() return tok.save() .. admonition:: Note: A user is required on verifier, remember to attach current user to verifier. """ log.debug('Save verifier %r for %r', verifier, token) self._verifiersetter( token=token, verifier=verifier, request=request )
python
{ "resource": "" }
q269694
OAuth2Provider.error_uri
test
def error_uri(self): """The error page URI. When something turns error, it will redirect to this error page. You can configure the error page URI with Flask config:: OAUTH2_PROVIDER_ERROR_URI = '/error' You can also define the error page by a named endpoint:: OAUTH2_PROVIDER_ERROR_ENDPOINT = 'oauth.error' """ error_uri = self.app.config.get('OAUTH2_PROVIDER_ERROR_URI') if error_uri: return error_uri error_endpoint = self.app.config.get('OAUTH2_PROVIDER_ERROR_ENDPOINT') if error_endpoint: return url_for(error_endpoint) return '/oauth/errors'
python
{ "resource": "" }
q269695
OAuth2Provider.confirm_authorization_request
test
def confirm_authorization_request(self): """When consumer confirm the authorization.""" server = self.server scope = request.values.get('scope') or '' scopes = scope.split() credentials = dict( client_id=request.values.get('client_id'), redirect_uri=request.values.get('redirect_uri', None), response_type=request.values.get('response_type', None), state=request.values.get('state', None) ) log.debug('Fetched credentials from request %r.', credentials) redirect_uri = credentials.get('redirect_uri') log.debug('Found redirect_uri %s.', redirect_uri) uri, http_method, body, headers = extract_params() try: ret = server.create_authorization_response( uri, http_method, body, headers, scopes, credentials) log.debug('Authorization successful.') return create_response(*ret) except oauth2.FatalClientError as e: log.debug('Fatal client error %r', e, exc_info=True) return self._on_exception(e, e.in_uri(self.error_uri)) except oauth2.OAuth2Error as e: log.debug('OAuth2Error: %r', e, exc_info=True) # on auth error, we should preserve state if it's present according to RFC 6749 state = request.values.get('state') if state and not e.state: e.state = state # set e.state so e.in_uri() can add the state query parameter to redirect uri return self._on_exception(e, e.in_uri(redirect_uri or self.error_uri)) except Exception as e: log.exception(e) return self._on_exception(e, add_params_to_uri( self.error_uri, {'error': str(e)} ))
python
{ "resource": "" }
q269696
OAuth2Provider.verify_request
test
def verify_request(self, scopes): """Verify current request, get the oauth data. If you can't use the ``require_oauth`` decorator, you can fetch the data in your request body:: def your_handler(): valid, req = oauth.verify_request(['email']) if valid: return jsonify(user=req.user) return jsonify(status='error') """ uri, http_method, body, headers = extract_params() return self.server.verify_request( uri, http_method, body, headers, scopes )
python
{ "resource": "" }
q269697
OAuth2RequestValidator._get_client_creds_from_request
test
def _get_client_creds_from_request(self, request): """Return client credentials based on the current request. According to the rfc6749, client MAY use the HTTP Basic authentication scheme as defined in [RFC2617] to authenticate with the authorization server. The client identifier is encoded using the "application/x-www-form-urlencoded" encoding algorithm per Appendix B, and the encoded value is used as the username; the client password is encoded using the same algorithm and used as the password. The authorization server MUST support the HTTP Basic authentication scheme for authenticating clients that were issued a client password. See `Section 2.3.1`_. .. _`Section 2.3.1`: https://tools.ietf.org/html/rfc6749#section-2.3.1 """ if request.client_id is not None: return request.client_id, request.client_secret auth = request.headers.get('Authorization') # If Werkzeug successfully parsed the Authorization header, # `extract_params` helper will replace the header with a parsed dict, # otherwise, there is nothing useful in the header and we just skip it. if isinstance(auth, dict): return auth['username'], auth['password'] return None, None
python
{ "resource": "" }
q269698
OAuth2RequestValidator.client_authentication_required
test
def client_authentication_required(self, request, *args, **kwargs): """Determine if client authentication is required for current request. According to the rfc6749, client authentication is required in the following cases: Resource Owner Password Credentials Grant: see `Section 4.3.2`_. Authorization Code Grant: see `Section 4.1.3`_. Refresh Token Grant: see `Section 6`_. .. _`Section 4.3.2`: http://tools.ietf.org/html/rfc6749#section-4.3.2 .. _`Section 4.1.3`: http://tools.ietf.org/html/rfc6749#section-4.1.3 .. _`Section 6`: http://tools.ietf.org/html/rfc6749#section-6 """ def is_confidential(client): if hasattr(client, 'is_confidential'): return client.is_confidential client_type = getattr(client, 'client_type', None) if client_type: return client_type == 'confidential' return True grant_types = ('password', 'authorization_code', 'refresh_token') client_id, _ = self._get_client_creds_from_request(request) if client_id and request.grant_type in grant_types: client = self._clientgetter(client_id) if client: return is_confidential(client) return False
python
{ "resource": "" }
q269699
OAuth2RequestValidator.authenticate_client
test
def authenticate_client(self, request, *args, **kwargs): """Authenticate itself in other means. Other means means is described in `Section 3.2.1`_. .. _`Section 3.2.1`: http://tools.ietf.org/html/rfc6749#section-3.2.1 """ client_id, client_secret = self._get_client_creds_from_request(request) log.debug('Authenticate client %r', client_id) client = self._clientgetter(client_id) if not client: log.debug('Authenticate client failed, client not found.') return False request.client = client # http://tools.ietf.org/html/rfc6749#section-2 # The client MAY omit the parameter if the client secret is an empty string. if hasattr(client, 'client_secret') and client.client_secret != client_secret: log.debug('Authenticate client failed, secret not match.') return False log.debug('Authenticate client success.') return True
python
{ "resource": "" }