_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 31 13.1k | 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":
| 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:
| 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 | 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))
| 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
| 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
| 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
| 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 == | 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:
| 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"
| 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(
| 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,
| 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 | 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 | 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:
| 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 ( | 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:
| 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:
| 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?
""" | 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
| 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
| 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():
| 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(
| 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)
| python | {
"resource": ""
} |
q269624 | BasicChecker.open | test | def open(self):
"""initialize visit variables and statistics
"""
self._tryfinallys = []
| 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()
| 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):
| 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)
| 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
| python | {
"resource": ""
} |
q269629 | BasicChecker._check_unreachable | test | def _check_unreachable(self, node):
"""check unreachable code"""
unreach_stmt = node.next_sibling()
| 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
| 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.
| 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): | 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)
| 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)
| 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)
| 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 | 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
| 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
| 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:
| 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
| python | {
"resource": ""
} |
q269641 | ClassDiagram.add_relationship | test | def add_relationship(self, from_object, to_object, relation_type, name=None):
"""create a relation ship
"""
| 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, ()):
| 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):
| python | {
"resource": ""
} |
q269644 | ClassDiagram.get_methods | test | def get_methods(self, node):
"""return visible methods"""
methods = [
m
for m in node.values()
| python | {
"resource": ""
} |
q269645 | ClassDiagram.add_object | test | def add_object(self, title, node):
"""create a diagram object
"""
assert node | 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)
| python | {
"resource": ""
} |
q269647 | ClassDiagram.classes | test | def classes(self):
"""return all class nodes in the diagram"""
return | 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():
| python | {
"resource": ""
} |
q269649 | PackageDiagram.modules | test | def modules(self):
"""return all module nodes in the diagram"""
| python | {
"resource": ""
} |
q269650 | PackageDiagram.module | test | def module(self, name):
"""return a module by its name, raise KeyError if not found
| 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 | 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 | python | {
"resource": ""
} |
q269653 | Grant.delete | test | def delete(self):
"""Removes itself from the cache
Note: This is required by the oauthlib
| python | {
"resource": ""
} |
q269654 | BaseBinding.query | test | def query(self):
"""Determines which method of getting the query object for use"""
if hasattr(self.model, 'query'):
| 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
"""
| 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:
| 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 | 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,
| python | {
"resource": ""
} |
q269659 | GrantBinding.get | test | def get(self, client_id, code):
"""Get the Grant object with the given client ID and code
| 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' | 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)
"""
| 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`.
"""
| 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
| 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)
)
| 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)
| 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 | 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: | 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)
| 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:
| 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]
| 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`
| 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:
| 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
)
| 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):
| 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 | 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 | 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 = | 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) | 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) | 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)
| 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)
| 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:
| 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)
| 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(
| 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)
| 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:
| 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: | 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 | 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)
| 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
| 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'],
| 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,
| 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:
| 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'
"""
| 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, | 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)
| 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
""" | 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
| 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
# | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.