signature
stringlengths
8
3.44k
body
stringlengths
0
1.41M
docstring
stringlengths
1
122k
id
stringlengths
5
17
def valid_symbol_name(name):
if name in RESERVED_WORDS:<EOL><INDENT>return False<EOL><DEDENT>gen = generate_tokens(io.BytesIO(name.encode('<STR_LIT:utf-8>')).readline)<EOL>typ, _, start, end, _ = next(gen)<EOL>if typ == tk_ENCODING:<EOL><INDENT>typ, _, start, end, _ = next(gen)<EOL><DEDENT>return typ == tk_NAME and start == (<NUM_LIT:1>, <NUM_LIT:0>) and end == (<NUM_LIT:1>, len(name))<EOL>
Determine whether the input symbol name is a valid name. Arguments --------- name : str name to check for validity. Returns -------- valid : bool whether name is a a valid symbol name This checks for Python reserved words and that the name matches the regular expression ``[a-zA-Z_][a-zA-Z0-9_]``
f12457:m6
def op2func(op):
return OPERATORS[op.__class__]<EOL>
Return function for operator nodes.
f12457:m7
def get_ast_names(astnode):
finder = NameFinder()<EOL>finder.generic_visit(astnode)<EOL>return finder.names<EOL>
Return symbol Names from an AST node.
f12457:m8
def make_symbol_table(use_numpy=True, **kws):
symtable = {}<EOL>for sym in FROM_PY:<EOL><INDENT>if sym in builtins:<EOL><INDENT>symtable[sym] = builtins[sym]<EOL><DEDENT><DEDENT>for sym in FROM_MATH:<EOL><INDENT>if hasattr(math, sym):<EOL><INDENT>symtable[sym] = getattr(math, sym)<EOL><DEDENT><DEDENT>if HAS_NUMPY and use_numpy:<EOL><INDENT>for sym in FROM_NUMPY:<EOL><INDENT>if hasattr(numpy, sym):<EOL><INDENT>symtable[sym] = getattr(numpy, sym)<EOL><DEDENT><DEDENT>for name, sym in NUMPY_RENAMES.items():<EOL><INDENT>if hasattr(numpy, sym):<EOL><INDENT>symtable[name] = getattr(numpy, sym)<EOL><DEDENT><DEDENT><DEDENT>symtable.update(LOCALFUNCS)<EOL>symtable.update(kws)<EOL>return symtable<EOL>
Create a default symboltable, taking dict of user-defined symbols. Arguments --------- numpy : bool, optional whether to include symbols from numpy kws : optional additional symbol name, value pairs to include in symbol table Returns -------- symbol_table : dict a symbol table that can be used in `asteval.Interpereter`
f12457:m9
def __init__(self):
pass<EOL>
TODO: docstring in public method.
f12457:c0:m0
def __nonzero__(self):
return False<EOL>
TODO: docstring in magic method.
f12457:c0:m1
def __init__(self, node, exc=None, msg='<STR_LIT>', expr=None, lineno=None):
self.node = node<EOL>self.expr = expr<EOL>self.msg = msg<EOL>self.exc = exc<EOL>self.lineno = lineno<EOL>self.exc_info = exc_info()<EOL>if self.exc is None and self.exc_info[<NUM_LIT:0>] is not None:<EOL><INDENT>self.exc = self.exc_info[<NUM_LIT:0>]<EOL><DEDENT>if self.msg is '<STR_LIT>' and self.exc_info[<NUM_LIT:1>] is not None:<EOL><INDENT>self.msg = self.exc_info[<NUM_LIT:1>]<EOL><DEDENT>
TODO: docstring in public method.
f12457:c1:m0
def get_error(self):
col_offset = -<NUM_LIT:1><EOL>if self.node is not None:<EOL><INDENT>try:<EOL><INDENT>col_offset = self.node.col_offset<EOL><DEDENT>except AttributeError:<EOL><INDENT>pass<EOL><DEDENT><DEDENT>try:<EOL><INDENT>exc_name = self.exc.__name__<EOL><DEDENT>except AttributeError:<EOL><INDENT>exc_name = str(self.exc)<EOL><DEDENT>if exc_name in (None, '<STR_LIT:None>'):<EOL><INDENT>exc_name = '<STR_LIT>'<EOL><DEDENT>out = ["<STR_LIT>" % self.expr]<EOL>if col_offset > <NUM_LIT:0>:<EOL><INDENT>out.append("<STR_LIT>" % ((col_offset)*'<STR_LIT:U+0020>'))<EOL><DEDENT>out.append(str(self.msg))<EOL>return (exc_name, '<STR_LIT:\n>'.join(out))<EOL>
Retrieve error data.
f12457:c1:m1
def __init__(self):
self.names = []<EOL>ast.NodeVisitor.__init__(self)<EOL>
TODO: docstring in public method.
f12457:c2:m0
def generic_visit(self, node):
if node.__class__.__name__ == '<STR_LIT:Name>':<EOL><INDENT>if node.ctx.__class__ == ast.Load and node.id not in self.names:<EOL><INDENT>self.names.append(node.id)<EOL><DEDENT><DEDENT>ast.NodeVisitor.generic_visit(self, node)<EOL>
TODO: docstring in public method.
f12457:c2:m1
def remove_nodehandler(self, node):
out = None<EOL>if node in self.node_handlers:<EOL><INDENT>out = self.node_handlers.pop(node)<EOL><DEDENT>return out<EOL>
remove support for a node returns current node handler, so that it might be re-added with add_nodehandler()
f12458:c0:m1
def set_nodehandler(self, node, handler):
self.node_handlers[node] = handler<EOL>
set node handler
f12458:c0:m2
def user_defined_symbols(self):
sym_in_current = set(self.symtable.keys())<EOL>sym_from_construction = set(self.no_deepcopy)<EOL>unique_symbols = sym_in_current.difference(sym_from_construction)<EOL>return unique_symbols<EOL>
Return a set of symbols that have been added to symtable after construction. I.e., the symbols from self.symtable that are not in self.no_deepcopy. Returns ------- unique_symbols : set symbols in symtable that are not in self.no_deepcopy
f12458:c0:m3
def unimplemented(self, node):
self.raise_exception(node, exc=NotImplementedError,<EOL>msg="<STR_LIT>" %<EOL>(node.__class__.__name__))<EOL>
Unimplemented nodes.
f12458:c0:m4
def raise_exception(self, node, exc=None, msg='<STR_LIT>', expr=None,<EOL>lineno=None):
if self.error is None:<EOL><INDENT>self.error = []<EOL><DEDENT>if expr is None:<EOL><INDENT>expr = self.expr<EOL><DEDENT>if len(self.error) > <NUM_LIT:0> and not isinstance(node, ast.Module):<EOL><INDENT>msg = '<STR_LIT:%s>' % msg<EOL><DEDENT>err = ExceptionHolder(node, exc=exc, msg=msg, expr=expr, lineno=lineno)<EOL>self._interrupt = ast.Break()<EOL>self.error.append(err)<EOL>if self.error_msg is None:<EOL><INDENT>self.error_msg = "<STR_LIT>" % (self.expr)<EOL><DEDENT>elif len(msg) > <NUM_LIT:0>:<EOL><INDENT>self.error_msg = msg<EOL><DEDENT>if exc is None:<EOL><INDENT>try:<EOL><INDENT>exc = self.error[<NUM_LIT:0>].exc<EOL><DEDENT>except:<EOL><INDENT>exc = RuntimeError<EOL><DEDENT><DEDENT>raise exc(self.error_msg)<EOL>
Add an exception.
f12458:c0:m5
def parse(self, text):
self.expr = text<EOL>try:<EOL><INDENT>out = ast.parse(text)<EOL><DEDENT>except SyntaxError:<EOL><INDENT>self.raise_exception(None, msg='<STR_LIT>', expr=text)<EOL><DEDENT>except:<EOL><INDENT>self.raise_exception(None, msg='<STR_LIT>', expr=text)<EOL><DEDENT>return out<EOL>
Parse statement/expression to Ast representation.
f12458:c0:m6
def run(self, node, expr=None, lineno=None, with_raise=True):
<EOL>if time.time() - self.start_time > self.max_time:<EOL><INDENT>raise RuntimeError(ERR_MAX_TIME.format(self.max_time))<EOL><DEDENT>out = None<EOL>if len(self.error) > <NUM_LIT:0>:<EOL><INDENT>return out<EOL><DEDENT>if node is None:<EOL><INDENT>return out<EOL><DEDENT>if isinstance(node, str):<EOL><INDENT>node = self.parse(node)<EOL><DEDENT>if lineno is not None:<EOL><INDENT>self.lineno = lineno<EOL><DEDENT>if expr is not None:<EOL><INDENT>self.expr = expr<EOL><DEDENT>try:<EOL><INDENT>handler = self.node_handlers[node.__class__.__name__.lower()]<EOL><DEDENT>except KeyError:<EOL><INDENT>return self.unimplemented(node)<EOL><DEDENT>try:<EOL><INDENT>ret = handler(node)<EOL>if isinstance(ret, enumerate):<EOL><INDENT>ret = list(ret)<EOL><DEDENT>return ret<EOL><DEDENT>except:<EOL><INDENT>if with_raise:<EOL><INDENT>self.raise_exception(node, expr=expr)<EOL><DEDENT><DEDENT>
Execute parsed Ast representation for an expression.
f12458:c0:m7
def __call__(self, expr, **kw):
return self.eval(expr, **kw)<EOL>
Call class instance as function.
f12458:c0:m8
def eval(self, expr, lineno=<NUM_LIT:0>, show_errors=True):
self.lineno = lineno<EOL>self.error = []<EOL>self.start_time = time.time()<EOL>try:<EOL><INDENT>node = self.parse(expr)<EOL><DEDENT>except:<EOL><INDENT>errmsg = exc_info()[<NUM_LIT:1>]<EOL>if len(self.error) > <NUM_LIT:0>:<EOL><INDENT>errmsg = "<STR_LIT:\n>".join(self.error[<NUM_LIT:0>].get_error())<EOL><DEDENT>if not show_errors:<EOL><INDENT>try:<EOL><INDENT>exc = self.error[<NUM_LIT:0>].exc<EOL><DEDENT>except:<EOL><INDENT>exc = RuntimeError<EOL><DEDENT>raise exc(errmsg)<EOL><DEDENT>print(errmsg, file=self.err_writer)<EOL>return<EOL><DEDENT>try:<EOL><INDENT>return self.run(node, expr=expr, lineno=lineno)<EOL><DEDENT>except:<EOL><INDENT>errmsg = exc_info()[<NUM_LIT:1>]<EOL>if len(self.error) > <NUM_LIT:0>:<EOL><INDENT>errmsg = "<STR_LIT:\n>".join(self.error[<NUM_LIT:0>].get_error())<EOL><DEDENT>if not show_errors:<EOL><INDENT>try:<EOL><INDENT>exc = self.error[<NUM_LIT:0>].exc<EOL><DEDENT>except:<EOL><INDENT>exc = RuntimeError<EOL><DEDENT>raise exc(errmsg)<EOL><DEDENT>print(errmsg, file=self.err_writer)<EOL>return<EOL><DEDENT>
Evaluate a single statement.
f12458:c0:m9
@staticmethod<EOL><INDENT>def dump(node, **kw):<DEDENT>
return ast.dump(node, **kw)<EOL>
Simple ast dumper.
f12458:c0:m10
def on_expr(self, node):
return self.run(node.value)<EOL>
Expression.
f12458:c0:m11
def on_index(self, node):
return self.run(node.value)<EOL>
Index.
f12458:c0:m12
def on_return(self, node):
self.retval = self.run(node.value)<EOL>if self.retval is None:<EOL><INDENT>self.retval = ReturnedNone<EOL><DEDENT>return<EOL>
Return statement: look for None, return special sentinal.
f12458:c0:m13
def on_repr(self, node):
return repr(self.run(node.value))<EOL>
Repr.
f12458:c0:m14
def on_module(self, node):
out = None<EOL>for tnode in node.body:<EOL><INDENT>out = self.run(tnode)<EOL><DEDENT>return out<EOL>
Module def.
f12458:c0:m15
def on_expression(self, node):
return self.on_module(node)<EOL>
basic expression
f12458:c0:m16
def on_pass(self, node):
return None<EOL>
Pass statement.
f12458:c0:m17
def on_ellipsis(self, node):
return Ellipsis<EOL>
Ellipses.
f12458:c0:m18
def on_interrupt(self, node):
self._interrupt = node<EOL>return node<EOL>
Interrupt handler.
f12458:c0:m19
def on_break(self, node):
return self.on_interrupt(node)<EOL>
Break.
f12458:c0:m20
def on_continue(self, node):
return self.on_interrupt(node)<EOL>
Continue.
f12458:c0:m21
def on_list(self, node):
return [self.run(e) for e in node.elts]<EOL>
List.
f12458:c0:m23
def on_tuple(self, node):
return tuple(self.on_list(node))<EOL>
Tuple.
f12458:c0:m24
def on_dict(self, node):
return dict([(self.run(k), self.run(v)) for k, v in<EOL>zip(node.keys, node.values)])<EOL>
Dictionary.
f12458:c0:m25
def on_num(self, node):
return node.n<EOL>
Return number.
f12458:c0:m26
def on_str(self, node):
return node.s<EOL>
Return string.
f12458:c0:m27
def on_nameconstant(self, node):
return node.value<EOL>
named constant
f12458:c0:m28
def on_name(self, node):
ctx = node.ctx.__class__<EOL>if ctx in (ast.Param, ast.Del):<EOL><INDENT>return str(node.id)<EOL><DEDENT>else:<EOL><INDENT>if node.id in self.symtable:<EOL><INDENT>return self.symtable[node.id]<EOL><DEDENT>else:<EOL><INDENT>msg = "<STR_LIT>" % node.id<EOL>self.raise_exception(node, exc=NameError, msg=msg)<EOL><DEDENT><DEDENT>
Name node.
f12458:c0:m29
def on_nameconstant(self, node):
return node.value<EOL>
True, False, None in python >= 3.4
f12458:c0:m30
def node_assign(self, node, val):
if node.__class__ == ast.Name:<EOL><INDENT>if not valid_symbol_name(node.id) or node.id in self.readonly_symbols:<EOL><INDENT>errmsg = "<STR_LIT>" % node.id<EOL>self.raise_exception(node, exc=NameError, msg=errmsg)<EOL><DEDENT>self.symtable[node.id] = val<EOL>if node.id in self.no_deepcopy:<EOL><INDENT>self.no_deepcopy.remove(node.id)<EOL><DEDENT><DEDENT>elif node.__class__ == ast.Attribute:<EOL><INDENT>if node.ctx.__class__ == ast.Load:<EOL><INDENT>msg = "<STR_LIT>" % node.attr<EOL>self.raise_exception(node, exc=AttributeError, msg=msg)<EOL><DEDENT>setattr(self.run(node.value), node.attr, val)<EOL><DEDENT>elif node.__class__ == ast.Subscript:<EOL><INDENT>sym = self.run(node.value)<EOL>xslice = self.run(node.slice)<EOL>if isinstance(node.slice, ast.Index):<EOL><INDENT>sym[xslice] = val<EOL><DEDENT>elif isinstance(node.slice, ast.Slice):<EOL><INDENT>sym[slice(xslice.start, xslice.stop)] = val<EOL><DEDENT>elif isinstance(node.slice, ast.ExtSlice):<EOL><INDENT>sym[xslice] = val<EOL><DEDENT><DEDENT>elif node.__class__ in (ast.Tuple, ast.List):<EOL><INDENT>if len(val) == len(node.elts):<EOL><INDENT>for telem, tval in zip(node.elts, val):<EOL><INDENT>self.node_assign(telem, tval)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT><DEDENT>
Assign a value (not the node.value object) to a node. This is used by on_assign, but also by for, list comprehension, etc.
f12458:c0:m31
def on_attribute(self, node):
ctx = node.ctx.__class__<EOL>if ctx == ast.Store:<EOL><INDENT>msg = "<STR_LIT>"<EOL>self.raise_exception(node, exc=RuntimeError, msg=msg)<EOL><DEDENT>sym = self.run(node.value)<EOL>if ctx == ast.Del:<EOL><INDENT>return delattr(sym, node.attr)<EOL><DEDENT>fmt = "<STR_LIT>"<EOL>if node.attr not in UNSAFE_ATTRS:<EOL><INDENT>fmt = "<STR_LIT>"<EOL>try:<EOL><INDENT>return getattr(sym, node.attr)<EOL><DEDENT>except AttributeError:<EOL><INDENT>pass<EOL><DEDENT><DEDENT>obj = self.run(node.value)<EOL>msg = fmt % (node.attr, obj)<EOL>self.raise_exception(node, exc=AttributeError, msg=msg)<EOL>
Extract attribute.
f12458:c0:m32
def on_assign(self, node):
val = self.run(node.value)<EOL>for tnode in node.targets:<EOL><INDENT>self.node_assign(tnode, val)<EOL><DEDENT>return<EOL>
Simple assignment.
f12458:c0:m33
def on_augassign(self, node):
return self.on_assign(ast.Assign(targets=[node.target],<EOL>value=ast.BinOp(left=node.target,<EOL>op=node.op,<EOL>right=node.value)))<EOL>
Augmented assign.
f12458:c0:m34
def on_slice(self, node):
return slice(self.run(node.lower),<EOL>self.run(node.upper),<EOL>self.run(node.step))<EOL>
Simple slice.
f12458:c0:m35
def on_extslice(self, node):
return tuple([self.run(tnode) for tnode in node.dims])<EOL>
Extended slice.
f12458:c0:m36
def on_subscript(self, node):
val = self.run(node.value)<EOL>nslice = self.run(node.slice)<EOL>ctx = node.ctx.__class__<EOL>if ctx in (ast.Load, ast.Store):<EOL><INDENT>if isinstance(node.slice, (ast.Index, ast.Slice, ast.Ellipsis)):<EOL><INDENT>return val.__getitem__(nslice)<EOL><DEDENT>elif isinstance(node.slice, ast.ExtSlice):<EOL><INDENT>return val[nslice]<EOL><DEDENT><DEDENT>else:<EOL><INDENT>msg = "<STR_LIT>"<EOL>self.raise_exception(node, msg=msg)<EOL><DEDENT>
Subscript handling -- one of the tricky parts.
f12458:c0:m37
def on_delete(self, node):
for tnode in node.targets:<EOL><INDENT>if tnode.ctx.__class__ != ast.Del:<EOL><INDENT>break<EOL><DEDENT>children = []<EOL>while tnode.__class__ == ast.Attribute:<EOL><INDENT>children.append(tnode.attr)<EOL>tnode = tnode.value<EOL><DEDENT>if tnode.__class__ == ast.Name and tnode.id not in self.readonly_symbols:<EOL><INDENT>children.append(tnode.id)<EOL>children.reverse()<EOL>self.symtable.pop('<STR_LIT:.>'.join(children))<EOL><DEDENT>else:<EOL><INDENT>msg = "<STR_LIT>"<EOL>self.raise_exception(node, msg=msg)<EOL><DEDENT><DEDENT>
Delete statement.
f12458:c0:m38
def on_unaryop(self, node):
return op2func(node.op)(self.run(node.operand))<EOL>
Unary operator.
f12458:c0:m39
def on_binop(self, node):
return op2func(node.op)(self.run(node.left),<EOL>self.run(node.right))<EOL>
Binary operator.
f12458:c0:m40
def on_boolop(self, node):
val = self.run(node.values[<NUM_LIT:0>])<EOL>is_and = ast.And == node.op.__class__<EOL>if (is_and and val) or (not is_and and not val):<EOL><INDENT>for n in node.values[<NUM_LIT:1>:]:<EOL><INDENT>val = op2func(node.op)(val, self.run(n))<EOL>if (is_and and not val) or (not is_and and val):<EOL><INDENT>break<EOL><DEDENT><DEDENT><DEDENT>return val<EOL>
Boolean operator.
f12458:c0:m41
def on_compare(self, node):
lval = self.run(node.left)<EOL>out = True<EOL>for op, rnode in zip(node.ops, node.comparators):<EOL><INDENT>rval = self.run(rnode)<EOL>out = op2func(op)(lval, rval)<EOL>lval = rval<EOL>if self.use_numpy and isinstance(out, numpy.ndarray) and out.any():<EOL><INDENT>break<EOL><DEDENT>elif not out:<EOL><INDENT>break<EOL><DEDENT><DEDENT>return out<EOL>
comparison operators
f12458:c0:m42
def on_print(self, node):
dest = self.run(node.dest) or self.writer<EOL>end = '<STR_LIT>'<EOL>if node.nl:<EOL><INDENT>end = '<STR_LIT:\n>'<EOL><DEDENT>out = [self.run(tnode) for tnode in node.values]<EOL>if out and len(self.error) == <NUM_LIT:0>:<EOL><INDENT>self._printer(*out, file=dest, end=end)<EOL><DEDENT>
Note: implements Python2 style print statement, not print() function. May need improvement....
f12458:c0:m43
def _printer(self, *out, **kws):
flush = kws.pop('<STR_LIT>', True)<EOL>fileh = kws.pop('<STR_LIT:file>', self.writer)<EOL>sep = kws.pop('<STR_LIT>', '<STR_LIT:U+0020>')<EOL>end = kws.pop('<STR_LIT>', '<STR_LIT:\n>')<EOL>print(*out, file=fileh, sep=sep, end=end)<EOL>if flush:<EOL><INDENT>fileh.flush()<EOL><DEDENT>
Generic print function.
f12458:c0:m44
def on_for(self, node):
for val in self.run(node.iter):<EOL><INDENT>self.node_assign(node.target, val)<EOL>self._interrupt = None<EOL>for tnode in node.body:<EOL><INDENT>self.run(tnode)<EOL>if self._interrupt is not None:<EOL><INDENT>break<EOL><DEDENT><DEDENT>if isinstance(self._interrupt, ast.Break):<EOL><INDENT>break<EOL><DEDENT><DEDENT>else:<EOL><INDENT>for tnode in node.orelse:<EOL><INDENT>self.run(tnode)<EOL><DEDENT><DEDENT>self._interrupt = None<EOL>
For blocks.
f12458:c0:m48
def on_listcomp(self, node):
out = []<EOL>for tnode in node.generators:<EOL><INDENT>if tnode.__class__ == ast.comprehension:<EOL><INDENT>for val in self.run(tnode.iter):<EOL><INDENT>self.node_assign(tnode.target, val)<EOL>add = True<EOL>for cond in tnode.ifs:<EOL><INDENT>add = add and self.run(cond)<EOL><DEDENT>if add:<EOL><INDENT>out.append(self.run(node.elt))<EOL><DEDENT><DEDENT><DEDENT><DEDENT>return out<EOL>
List comprehension.
f12458:c0:m49
def on_excepthandler(self, node):
return (self.run(node.type), node.name, node.body)<EOL>
Exception handler...
f12458:c0:m50
def on_try(self, node):
no_errors = True<EOL>for tnode in node.body:<EOL><INDENT>self.run(tnode, with_raise=False)<EOL>no_errors = no_errors and len(self.error) == <NUM_LIT:0><EOL>if len(self.error) > <NUM_LIT:0>:<EOL><INDENT>e_type, e_value, e_tback = self.error[-<NUM_LIT:1>].exc_info<EOL>for hnd in node.handlers:<EOL><INDENT>htype = None<EOL>if hnd.type is not None:<EOL><INDENT>htype = builtins.get(hnd.type.id, None)<EOL><DEDENT>if htype is None or isinstance(e_type(), htype):<EOL><INDENT>self.error = []<EOL>if hnd.name is not None:<EOL><INDENT>self.node_assign(hnd.name, e_value)<EOL><DEDENT>for tline in hnd.body:<EOL><INDENT>self.run(tline)<EOL><DEDENT>break<EOL><DEDENT><DEDENT>break<EOL><DEDENT><DEDENT>if no_errors and hasattr(node, '<STR_LIT>'):<EOL><INDENT>for tnode in node.orelse:<EOL><INDENT>self.run(tnode)<EOL><DEDENT><DEDENT>if hasattr(node, '<STR_LIT>'):<EOL><INDENT>for tnode in node.finalbody:<EOL><INDENT>self.run(tnode)<EOL><DEDENT><DEDENT>
Try/except/else/finally blocks.
f12458:c0:m51
def on_raise(self, node):
if version_info[<NUM_LIT:0>] == <NUM_LIT:3>:<EOL><INDENT>excnode = node.exc<EOL>msgnode = node.cause<EOL><DEDENT>else:<EOL><INDENT>excnode = node.type<EOL>msgnode = node.inst<EOL><DEDENT>out = self.run(excnode)<EOL>msg = '<STR_LIT:U+0020>'.join(out.args)<EOL>msg2 = self.run(msgnode)<EOL>if msg2 not in (None, '<STR_LIT:None>'):<EOL><INDENT>msg = "<STR_LIT>" % (msg, msg2)<EOL><DEDENT>self.raise_exception(None, exc=out.__class__, msg=msg, expr='<STR_LIT>')<EOL>
Raise statement: note difference for python 2 and 3.
f12458:c0:m52
def on_call(self, node):
<EOL>func = self.run(node.func)<EOL>if not hasattr(func, '<STR_LIT>') and not isinstance(func, type):<EOL><INDENT>msg = "<STR_LIT>" % (func)<EOL>self.raise_exception(node, exc=TypeError, msg=msg)<EOL><DEDENT>args = [self.run(targ) for targ in node.args]<EOL>starargs = getattr(node, '<STR_LIT>', None)<EOL>if starargs is not None:<EOL><INDENT>args = args + self.run(starargs)<EOL><DEDENT>keywords = {}<EOL>if six.PY3 and func == print:<EOL><INDENT>keywords['<STR_LIT:file>'] = self.writer<EOL><DEDENT>for key in node.keywords:<EOL><INDENT>if not isinstance(key, ast.keyword):<EOL><INDENT>msg = "<STR_LIT>" % (func)<EOL>self.raise_exception(node, msg=msg)<EOL><DEDENT>keywords[key.arg] = self.run(key.value)<EOL><DEDENT>kwargs = getattr(node, '<STR_LIT>', None)<EOL>if kwargs is not None:<EOL><INDENT>keywords.update(self.run(kwargs))<EOL><DEDENT>try:<EOL><INDENT>return func(*args, **keywords)<EOL><DEDENT>except Exception as ex:<EOL><INDENT>self.raise_exception(<EOL>node, msg="<STR_LIT>"<EOL>"<STR_LIT>" % (func.__name__, args, keywords, ex))<EOL><DEDENT>
Function execution.
f12458:c0:m53
def on_functiondef(self, node):
<EOL>if node.decorator_list:<EOL><INDENT>raise Warning("<STR_LIT>")<EOL><DEDENT>kwargs = []<EOL>if not valid_symbol_name(node.name) or node.name in self.readonly_symbols:<EOL><INDENT>errmsg = "<STR_LIT>" % node.name<EOL>self.raise_exception(node, exc=NameError, msg=errmsg)<EOL><DEDENT>offset = len(node.args.args) - len(node.args.defaults)<EOL>for idef, defnode in enumerate(node.args.defaults):<EOL><INDENT>defval = self.run(defnode)<EOL>keyval = self.run(node.args.args[idef+offset])<EOL>kwargs.append((keyval, defval))<EOL><DEDENT>if version_info[<NUM_LIT:0>] == <NUM_LIT:3>:<EOL><INDENT>args = [tnode.arg for tnode in node.args.args[:offset]]<EOL><DEDENT>else:<EOL><INDENT>args = [tnode.id for tnode in node.args.args[:offset]]<EOL><DEDENT>doc = None<EOL>nb0 = node.body[<NUM_LIT:0>]<EOL>if isinstance(nb0, ast.Expr) and isinstance(nb0.value, ast.Str):<EOL><INDENT>doc = nb0.value.s<EOL><DEDENT>varkws = node.args.kwarg<EOL>vararg = node.args.vararg<EOL>if version_info[<NUM_LIT:0>] == <NUM_LIT:3>:<EOL><INDENT>if isinstance(vararg, ast.arg):<EOL><INDENT>vararg = vararg.arg<EOL><DEDENT>if isinstance(varkws, ast.arg):<EOL><INDENT>varkws = varkws.arg<EOL><DEDENT><DEDENT>self.symtable[node.name] = Procedure(node.name, self, doc=doc,<EOL>lineno=self.lineno,<EOL>body=node.body,<EOL>args=args, kwargs=kwargs,<EOL>vararg=vararg, varkws=varkws)<EOL>if node.name in self.no_deepcopy:<EOL><INDENT>self.no_deepcopy.remove(node.name)<EOL><DEDENT>
Define procedures.
f12458:c0:m55
def __init__(self, name, interp, doc=None, lineno=<NUM_LIT:0>,<EOL>body=None, args=None, kwargs=None,<EOL>vararg=None, varkws=None):
self.__ininit__ = True<EOL>self.name = name<EOL>self.__name__ = self.name<EOL>self.__asteval__ = interp<EOL>self.raise_exc = self.__asteval__.raise_exception<EOL>self.__doc__ = doc<EOL>self.body = body<EOL>self.argnames = args<EOL>self.kwargs = kwargs<EOL>self.vararg = vararg<EOL>self.varkws = varkws<EOL>self.lineno = lineno<EOL>self.__ininit__ = False<EOL>
TODO: docstring in public method.
f12458:c1:m0
def __repr__(self):
sig = "<STR_LIT>"<EOL>if len(self.argnames) > <NUM_LIT:0>:<EOL><INDENT>sig = "<STR_LIT>" % (sig, '<STR_LIT:U+002CU+0020>'.join(self.argnames))<EOL><DEDENT>if self.vararg is not None:<EOL><INDENT>sig = "<STR_LIT>" % (sig, self.vararg)<EOL><DEDENT>if len(self.kwargs) > <NUM_LIT:0>:<EOL><INDENT>if len(sig) > <NUM_LIT:0>:<EOL><INDENT>sig = "<STR_LIT>" % sig<EOL><DEDENT>_kw = ["<STR_LIT>" % (k, v) for k, v in self.kwargs]<EOL>sig = "<STR_LIT>" % (sig, '<STR_LIT:U+002CU+0020>'.join(_kw))<EOL><DEDENT>if self.varkws is not None:<EOL><INDENT>sig = "<STR_LIT>" % (sig, self.varkws)<EOL><DEDENT>sig = "<STR_LIT>" % (self.name, sig)<EOL>if self.__doc__ is not None:<EOL><INDENT>sig = "<STR_LIT>" % (sig, self.__doc__)<EOL><DEDENT>return sig<EOL>
TODO: docstring in magic method.
f12458:c1:m3
def __call__(self, *args, **kwargs):
symlocals = {}<EOL>args = list(args)<EOL>nargs = len(args)<EOL>nkws = len(kwargs)<EOL>nargs_expected = len(self.argnames)<EOL>if (nargs < nargs_expected) and nkws > <NUM_LIT:0>:<EOL><INDENT>for name in self.argnames[nargs:]:<EOL><INDENT>if name in kwargs:<EOL><INDENT>args.append(kwargs.pop(name))<EOL><DEDENT><DEDENT>nargs = len(args)<EOL>nargs_expected = len(self.argnames)<EOL>nkws = len(kwargs)<EOL><DEDENT>if nargs < nargs_expected:<EOL><INDENT>msg = "<STR_LIT>"<EOL>self.raise_exc(None, exc=TypeError,<EOL>msg=msg % (self.name, nargs_expected, nargs))<EOL><DEDENT>if len(self.argnames) > <NUM_LIT:0> and kwargs is not None:<EOL><INDENT>msg = "<STR_LIT>"<EOL>for targ in self.argnames:<EOL><INDENT>if targ in kwargs:<EOL><INDENT>self.raise_exc(None, exc=TypeError,<EOL>msg=msg % (targ, self.name),<EOL>lineno=self.lineno)<EOL><DEDENT><DEDENT><DEDENT>if nargs != nargs_expected:<EOL><INDENT>msg = None<EOL>if nargs < nargs_expected:<EOL><INDENT>msg = '<STR_LIT>' % self.name<EOL>msg = '<STR_LIT>' % (msg, nargs_expected, nargs)<EOL>self.raise_exc(None, exc=TypeError, msg=msg)<EOL><DEDENT><DEDENT>if nargs > nargs_expected and self.vararg is None:<EOL><INDENT>if nargs - nargs_expected > len(self.kwargs):<EOL><INDENT>msg = '<STR_LIT>'<EOL>msg = msg % (self.name, len(self.kwargs)+nargs_expected, nargs)<EOL>self.raise_exc(None, exc=TypeError, msg=msg)<EOL><DEDENT>for i, xarg in enumerate(args[nargs_expected:]):<EOL><INDENT>kw_name = self.kwargs[i][<NUM_LIT:0>]<EOL>if kw_name not in kwargs:<EOL><INDENT>kwargs[kw_name] = xarg<EOL><DEDENT><DEDENT><DEDENT>for argname in self.argnames:<EOL><INDENT>symlocals[argname] = args.pop(<NUM_LIT:0>)<EOL><DEDENT>try:<EOL><INDENT>if self.vararg is not None:<EOL><INDENT>symlocals[self.vararg] = tuple(args)<EOL><DEDENT>for key, val in self.kwargs:<EOL><INDENT>if key in kwargs:<EOL><INDENT>val = kwargs.pop(key)<EOL><DEDENT>symlocals[key] = val<EOL><DEDENT>if self.varkws is not None:<EOL><INDENT>symlocals[self.varkws] = kwargs<EOL><DEDENT>elif len(kwargs) > <NUM_LIT:0>:<EOL><INDENT>msg = '<STR_LIT>'<EOL>msg = msg % (self.name, '<STR_LIT:U+002C>'.join(list(kwargs.keys())))<EOL>self.raise_exc(None, msg=msg, exc=TypeError,<EOL>lineno=self.lineno)<EOL><DEDENT><DEDENT>except (ValueError, LookupError, TypeError,<EOL>NameError, AttributeError):<EOL><INDENT>msg = '<STR_LIT>' % self.name<EOL>self.raise_exc(None, msg=msg, lineno=self.lineno)<EOL><DEDENT>save_symtable = self.__asteval__.symtable.copy()<EOL>self.__asteval__.symtable.update(symlocals)<EOL>self.__asteval__.retval = None<EOL>retval = None<EOL>for node in self.body:<EOL><INDENT>self.__asteval__.run(node, expr='<STR_LIT>', lineno=self.lineno)<EOL>if len(self.__asteval__.error) > <NUM_LIT:0>:<EOL><INDENT>break<EOL><DEDENT>if self.__asteval__.retval is not None:<EOL><INDENT>retval = self.__asteval__.retval<EOL>self.__asteval__.retval = None<EOL>if retval is ReturnedNone:<EOL><INDENT>retval = None<EOL><DEDENT>break<EOL><DEDENT><DEDENT>self.__asteval__.symtable = save_symtable<EOL>symlocals = None<EOL>return retval<EOL>
TODO: docstring in public method.
f12458:c1:m4
def serialize_number(x, fmt=SER_BINARY, outlen=None):
ret = b'<STR_LIT>'<EOL>if fmt == SER_BINARY:<EOL><INDENT>while x:<EOL><INDENT>x, r = divmod(x, <NUM_LIT>)<EOL>ret = six.int2byte(int(r)) + ret<EOL><DEDENT>if outlen is not None:<EOL><INDENT>assert len(ret) <= outlen<EOL>ret = ret.rjust(outlen, b'<STR_LIT>')<EOL><DEDENT>return ret<EOL><DEDENT>assert fmt == SER_COMPACT<EOL>while x:<EOL><INDENT>x, r = divmod(x, len(COMPACT_DIGITS))<EOL>ret = COMPACT_DIGITS[r:r + <NUM_LIT:1>] + ret<EOL><DEDENT>if outlen is not None:<EOL><INDENT>assert len(ret) <= outlen<EOL>ret = ret.rjust(outlen, COMPACT_DIGITS[<NUM_LIT:0>:<NUM_LIT:1>])<EOL><DEDENT>return ret<EOL>
Serializes `x' to a string of length `outlen' in format `fmt
f12466:m0
def deserialize_number(s, fmt=SER_BINARY):
ret = gmpy.mpz(<NUM_LIT:0>)<EOL>if fmt == SER_BINARY:<EOL><INDENT>if isinstance(s, six.text_type):<EOL><INDENT>raise ValueError(<EOL>"<STR_LIT>" +<EOL>"<STR_LIT>")<EOL><DEDENT>for c in s:<EOL><INDENT>ret *= <NUM_LIT><EOL>ret += byte2int(c)<EOL><DEDENT>return ret<EOL><DEDENT>assert fmt == SER_COMPACT<EOL>if isinstance(s, six.text_type):<EOL><INDENT>s = s.encode('<STR_LIT:ascii>')<EOL><DEDENT>for c in s:<EOL><INDENT>ret *= len(COMPACT_DIGITS)<EOL>ret += R_COMPACT_DIGITS[c]<EOL><DEDENT>return ret<EOL>
Deserializes a number from a string `s' in format `fmt
f12466:m1
def mod_issquare(a, p):
if not a:<EOL><INDENT>return True<EOL><DEDENT>p1 = p // <NUM_LIT:2><EOL>p2 = pow(a, p1, p)<EOL>return p2 == <NUM_LIT:1><EOL>
Returns whether `a' is a square modulo p
f12466:m3
def mod_root(a, p):
if a == <NUM_LIT:0>:<EOL><INDENT>return <NUM_LIT:0><EOL><DEDENT>if not mod_issquare(a, p):<EOL><INDENT>raise ValueError<EOL><DEDENT>n = <NUM_LIT:2><EOL>while mod_issquare(n, p):<EOL><INDENT>n += <NUM_LIT:1><EOL><DEDENT>q = p - <NUM_LIT:1><EOL>r = <NUM_LIT:0><EOL>while not q.getbit(r):<EOL><INDENT>r += <NUM_LIT:1><EOL><DEDENT>q = q >> r<EOL>y = pow(n, q, p)<EOL>h = q >> <NUM_LIT:1><EOL>b = pow(a, h, p)<EOL>x = (a * b) % p<EOL>b = (b * x) % p<EOL>while b != <NUM_LIT:1>:<EOL><INDENT>h = (b * b) % p<EOL>m = <NUM_LIT:1><EOL>while h != <NUM_LIT:1>:<EOL><INDENT>h = (h * h) % p<EOL>m += <NUM_LIT:1><EOL><DEDENT>h = gmpy.mpz(<NUM_LIT:0>)<EOL>h = h.setbit(r - m - <NUM_LIT:1>)<EOL>t = pow(y, h, p)<EOL>y = (t * t) % p<EOL>r = m<EOL>x = (x * t) % p<EOL>b = (b * y) % p<EOL><DEDENT>return x<EOL>
Return a root of `a' modulo p
f12466:m4
def _passphrase_to_hash(passphrase):
return hashlib.sha256(passphrase).digest()<EOL>
Converts a passphrase to a hash.
f12466:m5
def encrypt(s, pk, pk_format=SER_COMPACT, mac_bytes=<NUM_LIT:10>, curve=None):
curve = (Curve.by_pk_len(len(pk)) if curve is None<EOL>else Curve.by_name(curve))<EOL>p = curve.pubkey_from_string(pk, pk_format)<EOL>return p.encrypt(s, mac_bytes)<EOL>
Encrypts `s' for public key `pk
f12466:m6
def decrypt(s, passphrase, curve='<STR_LIT>', mac_bytes=<NUM_LIT:10>):
curve = Curve.by_name(curve)<EOL>privkey = curve.passphrase_to_privkey(passphrase)<EOL>return privkey.decrypt(s, mac_bytes)<EOL>
Decrypts `s' with passphrase `passphrase
f12466:m7
def encrypt_file(in_path_or_file, out_path_or_file, pk, pk_format=SER_COMPACT,<EOL>mac_bytes=<NUM_LIT:10>, chunk_size=<NUM_LIT>, curve=None):
close_in, close_out = False, False<EOL>in_file, out_file = in_path_or_file, out_path_or_file<EOL>try:<EOL><INDENT>if stringlike(in_path_or_file):<EOL><INDENT>in_file = open(in_path_or_file, '<STR_LIT:rb>')<EOL>close_in = True<EOL><DEDENT>if stringlike(out_path_or_file):<EOL><INDENT>out_file = open(out_path_or_file, '<STR_LIT:wb>')<EOL>close_out = True<EOL><DEDENT>_encrypt_file(in_file, out_file, pk, pk_format, mac_bytes, chunk_size,<EOL>curve)<EOL><DEDENT>finally:<EOL><INDENT>if close_out:<EOL><INDENT>out_file.close()<EOL><DEDENT>if close_in:<EOL><INDENT>in_file.close()<EOL><DEDENT><DEDENT>
Encrypts `in_file' to `out_file' for pubkey `pk
f12466:m8
def decrypt_file(in_path_or_file, out_path_or_file, passphrase,<EOL>curve='<STR_LIT>', mac_bytes=<NUM_LIT:10>, chunk_size=<NUM_LIT>):
close_in, close_out = False, False<EOL>in_file, out_file = in_path_or_file, out_path_or_file<EOL>try:<EOL><INDENT>if stringlike(in_path_or_file):<EOL><INDENT>in_file = open(in_path_or_file, '<STR_LIT:rb>')<EOL>close_in = True<EOL><DEDENT>if stringlike(out_path_or_file):<EOL><INDENT>out_file = open(out_path_or_file, '<STR_LIT:wb>')<EOL>close_out = True<EOL><DEDENT>_decrypt_file(in_file, out_file, passphrase, curve, mac_bytes,<EOL>chunk_size)<EOL><DEDENT>finally:<EOL><INDENT>if close_out:<EOL><INDENT>out_file.close()<EOL><DEDENT>if close_in:<EOL><INDENT>in_file.close()<EOL><DEDENT><DEDENT>
Decrypts `in_file' to `out_file' with passphrase `passphrase
f12466:m9
def verify(s, sig, pk, sig_format=SER_COMPACT, pk_format=SER_COMPACT,<EOL>curve=None):
if isinstance(s, six.text_type):<EOL><INDENT>raise ValueError("<STR_LIT>" +<EOL>"<STR_LIT>")<EOL><DEDENT>curve = (Curve.by_pk_len(len(pk)) if curve is None<EOL>else Curve.by_name(curve))<EOL>p = curve.pubkey_from_string(pk, pk_format)<EOL>return p.verify(hashlib.sha512(s).digest(), sig, sig_format)<EOL>
Verifies that `sig' is a signature of pubkey `pk' for the message `s'.
f12466:m12
def sign(s, passphrase, sig_format=SER_COMPACT, curve='<STR_LIT>'):
if isinstance(s, six.text_type):<EOL><INDENT>raise ValueError("<STR_LIT>" +<EOL>"<STR_LIT>")<EOL><DEDENT>curve = Curve.by_name(curve)<EOL>privkey = curve.passphrase_to_privkey(passphrase)<EOL>return privkey.sign(hashlib.sha512(s).digest(), sig_format)<EOL>
Signs `s' with passphrase `passphrase
f12466:m13
def generate_keypair(curve='<STR_LIT>', randfunc=None):
if randfunc is None:<EOL><INDENT>randfunc = Crypto.Random.new().read<EOL><DEDENT>curve = Curve.by_name(curve)<EOL>raw_privkey = randfunc(curve.order_len_bin)<EOL>privkey = serialize_number(deserialize_number(raw_privkey), SER_COMPACT)<EOL>pubkey = str(passphrase_to_pubkey(privkey))<EOL>return (privkey, pubkey)<EOL>
Convenience function to generate a random new keypair (passphrase, pubkey).
f12466:m15
def verify(self, h, sig, sig_fmt=SER_BINARY):
s = deserialize_number(sig, sig_fmt)<EOL>return self.p._ECDSA_verify(h, s)<EOL>
Verifies that `sig' is a signature for a message with SHA-512 hash `h'.
f12466:c3:m1
@contextlib.contextmanager<EOL><INDENT>def encrypt_to(self, f, mac_bytes=<NUM_LIT:10>):<DEDENT>
ctx = EncryptionContext(f, self.p, mac_bytes)<EOL>yield ctx<EOL>ctx.finish()<EOL>
Returns a file like object `ef'. Anything written to `ef' will be encrypted for this pubkey and written to `f'.
f12466:c3:m2
def encrypt(self, s, mac_bytes=<NUM_LIT:10>):
if isinstance(s, six.text_type):<EOL><INDENT>raise ValueError(<EOL>"<STR_LIT>" +<EOL>"<STR_LIT>")<EOL><DEDENT>out = BytesIO()<EOL>with self.encrypt_to(out, mac_bytes) as f:<EOL><INDENT>f.write(s)<EOL><DEDENT>return out.getvalue()<EOL>
Encrypt `s' for this pubkey.
f12466:c3:m3
@contextlib.contextmanager<EOL><INDENT>def decrypt_from(self, f, mac_bytes=<NUM_LIT:10>):<DEDENT>
ctx = DecryptionContext(self.curve, f, self, mac_bytes)<EOL>yield ctx<EOL>ctx.read()<EOL>
Decrypts a message from f.
f12466:c4:m1
def sign(self, h, sig_format=SER_BINARY):
outlen = (self.curve.sig_len_compact if sig_format == SER_COMPACT<EOL>else self.curve.sig_len_bin)<EOL>sig = self._ECDSA_sign(h)<EOL>return serialize_number(sig, sig_format, outlen)<EOL>
Signs the message with SHA-512 hash `h' with this private key.
f12466:c4:m3
def __init__(self, raw_curve_params):
r = raw_curve_parameters(*raw_curve_params)<EOL>self.name = r.name<EOL>self.a = deserialize_number(binascii.unhexlify(r.a), SER_BINARY)<EOL>self.b = deserialize_number(binascii.unhexlify(r.b), SER_BINARY)<EOL>self.m = deserialize_number(binascii.unhexlify(r.m), SER_BINARY)<EOL>self.order = deserialize_number(<EOL>binascii.unhexlify(r.order), SER_BINARY)<EOL>self.base = AffinePoint(<EOL>curve=self, x=deserialize_number(<EOL>binascii.unhexlify(<EOL>r.base_x), SER_BINARY), y=deserialize_number(<EOL>binascii.unhexlify(<EOL>r.base_y), SER_BINARY))<EOL>self.cofactor = r.cofactor<EOL>self.pk_len_bin = get_serialized_number_len(<EOL>(<NUM_LIT:2> * self.m) - <NUM_LIT:1>, SER_BINARY)<EOL>self.pk_len_compact = get_serialized_number_len(<EOL>(<NUM_LIT:2> * self.m) - <NUM_LIT:1>, SER_COMPACT)<EOL>assert self.pk_len_compact == r.pk_len_compact<EOL>self.sig_len_bin = get_serialized_number_len(<EOL>(self.order * self.order) - <NUM_LIT:1>, SER_BINARY)<EOL>self.sig_len_compact = get_serialized_number_len(<EOL>(self.order * self.order) - <NUM_LIT:1>, SER_COMPACT)<EOL>self.dh_len_bin = min((self.order.numdigits(<NUM_LIT:2>) // <NUM_LIT:2> + <NUM_LIT:7>) // <NUM_LIT:8>, <NUM_LIT:32>)<EOL>self.dh_len_compact = get_serialized_number_len(<EOL><NUM_LIT:2> ** self.dh_len_bin - <NUM_LIT:1>, SER_COMPACT)<EOL>self.elem_len_bin = get_serialized_number_len(self.m, SER_BINARY)<EOL>self.order_len_bin = get_serialized_number_len(self.order, SER_BINARY)<EOL>
Initialize a new curve from raw curve parameters. Use `Curve.by_pk_len' instead
f12466:c7:m3
@property<EOL><INDENT>def key_bytes(self):<DEDENT>
return self.pk_len_bin<EOL>
The approximate number of bytes of information in a key.
f12466:c7:m4
def hash_to_exponent(self, h):
ctr = Crypto.Util.Counter.new(<NUM_LIT>, initial_value=<NUM_LIT:0>)<EOL>cipher = Crypto.Cipher.AES.new(h,<EOL>Crypto.Cipher.AES.MODE_CTR, counter=ctr)<EOL>buf = cipher.encrypt(b'<STR_LIT>' * self.order_len_bin)<EOL>return self._buf_to_exponent(buf)<EOL>
Converts a 32 byte hash to an exponent
f12466:c7:m9
def get(self, path):
return json.loads(self._make_request('<STR_LIT:GET>', path))<EOL>
Make a GET request. Args: `path`: The path to the resource. Returns: The content of the response. Raises: An exception depending on the HTTP status code of the response.
f12472:c0:m0
def post(self, path, data, filename=None):
return self._send('<STR_LIT:POST>', path, data, filename)<EOL>
Make a POST request. If a `filename` is not specified, then the data must already be JSON-encoded. We specify the Content-Type accordingly. Else, we make a multipart/form-encoded request. In this case, the data variable must be a dict-like object. The file must already be suitably (usually UTF-8) encoded. Args: `path`: The path to the resource. `data`: The data to send. The data must already be JSON-encoded. `filename`: The filename of the file to send. Returns: The content of the response. Raises: An exception depending on the HTTP status code of the response.
f12472:c0:m1
def put(self, path, data, filename=None):
return self._send('<STR_LIT>', path, data, filename)<EOL>
Make a PUT request. If a `filename` is not specified, then the data must already be JSON-encoded. We specify the Content-Type accordingly. Else, we make a multipart/form-encoded request. In this case, the data variable must be a dict-like object. The file must already be suitably (usually UTF-8) encoded. Args: `path`: The path to the resource. `data`: The data to send. The data must already be JSON-encoded. `filename`: The filename of the file to send. Returns: The content of the response. Raises: An exception depending on the HTTP status code of the response.
f12472:c0:m2
def delete(self, path):
return self._make_request('<STR_LIT>', path)<EOL>
Make a DELETE request. Args: `path`: The path to the resource. Returns: The content of the response. Raises: An exception depending on the HTTP status code of the response.
f12472:c0:m3
def _make_request(self, method, path, data=None, **kwargs):
_logger.debug("<STR_LIT>" % method)<EOL>url = self._construct_full_url(path)<EOL>_logger.debug("<STR_LIT>" % url)<EOL>self._auth_info.populate_request_data(kwargs)<EOL>_logger.debug("<STR_LIT>" % kwargs)<EOL>if self._auth_info._headers:<EOL><INDENT>kwargs.setdefault('<STR_LIT>', {}).update(self._auth_info._headers)<EOL><DEDENT>res = requests.request(method, url, data=data, **kwargs)<EOL>if res.ok:<EOL><INDENT>_logger.debug("<STR_LIT>")<EOL>return res.content.decode('<STR_LIT:utf-8>')<EOL><DEDENT>if hasattr(res, '<STR_LIT:content>'):<EOL><INDENT>_logger.debug("<STR_LIT>", res.status_code, res.content)<EOL>raise self._exception_for(res.status_code)(<EOL>res.content, http_code=res.status_code<EOL>)<EOL><DEDENT>else:<EOL><INDENT>msg = "<STR_LIT>" % res.request.url<EOL>_logger.error(msg)<EOL>raise NoResponseError(msg)<EOL><DEDENT>
Make a request. Use the `requests` module to actually perform the request. Args: `method`: The method to use. `path`: The path to the resource. `data`: Any data to send (for POST and PUT requests). `kwargs`: Other parameters for `requests`. Returns: The content of the response. Raises: An exception depending on the HTTP status code of the response.
f12472:c0:m4
def _send(self, method, path, data, filename):
if filename is None:<EOL><INDENT>return self._send_json(method, path, data)<EOL><DEDENT>else:<EOL><INDENT>return self._send_file(method, path, data, filename)<EOL><DEDENT>
Send data to a remote server, either with a POST or a PUT request. Args: `method`: The method (POST or PUT) to use. `path`: The path to the resource. `data`: The data to send. `filename`: The filename of the file to send (if any). Returns: The content of the response. Raises: An exception depending on the HTTP status code of the response.
f12472:c0:m5
def _send_json(self, method, path, data):
headers = {'<STR_LIT>': '<STR_LIT:application/json>'}<EOL>return self._make_request(method, path, data=data, headers=headers)<EOL>
Make a application/json request. Args: `method`: The method of the request (POST or PUT). `path`: The path to the resource. `data`: The JSON-encoded data. Returns: The content of the response. Raises: An exception depending on the HTTP status code of the response.
f12472:c0:m6
def _send_file(self, method, path, data, filename):
with open(filename, '<STR_LIT:r>') as f:<EOL><INDENT>return self._make_request(method, path, data=data, files=[f, ])<EOL><DEDENT>
Make a multipart/form-encoded request. Args: `method`: The method of the request (POST or PUT). `path`: The path to the resource. `data`: The JSON-encoded data. `filename`: The filename of the file to send. Returns: The content of the response. Raises: An exception depending on the HTTP status code of the response.
f12472:c0:m7
def __init__(self, hostname, auth=AnonymousAuth()):
self._hostname = self._construct_full_hostname(hostname)<EOL>_logger.debug("<STR_LIT>" % self._hostname)<EOL>self._auth_info = auth<EOL>
Initializer for the base class. Save the hostname to use for all requests as well as any authentication info needed. Args: hostname: The host for the requests. auth: The authentication info needed for any requests.
f12473:c0:m0
def _construct_full_hostname(self, hostname):
if hostname.startswith(('<STR_LIT>', '<STR_LIT>', )):<EOL><INDENT>return hostname<EOL><DEDENT>if '<STR_LIT>' in hostname:<EOL><INDENT>protocol, host = hostname.split('<STR_LIT>', <NUM_LIT:1>)<EOL>raise ValueError('<STR_LIT>' % protocol)<EOL><DEDENT>return '<STR_LIT>'.join([self.default_scheme, hostname, ])<EOL>
Create a full (scheme included) hostname from the argument given. Only HTTP and HTTP+SSL protocols are allowed. Args: hostname: The hostname to use. Returns: The full hostname. Raises: ValueError: A not supported protocol is used.
f12473:c0:m1
def _construct_full_url(self, path):
return urlparse.urljoin(self._hostname, path)<EOL>
Construct the full url from the host and the path parts.
f12473:c0:m2
def _error_message(self, code, msg):
return self.error_messages[code] % msg<EOL>
Return the message that corresponds to the request (status code and error message) specified. Args: `code`: The http status code. `msg`: The message to display. Returns: The error message for the code given.
f12473:c0:m3
def _exception_for(self, code):
if code in self.errors:<EOL><INDENT>return self.errors[code]<EOL><DEDENT>elif <NUM_LIT> <= code < <NUM_LIT>:<EOL><INDENT>return exceptions.RemoteServerError<EOL><DEDENT>else:<EOL><INDENT>return exceptions.UnknownError<EOL><DEDENT>
Return the exception class suitable for the specified HTTP status code. Raises: UnknownError: The HTTP status code is not one of the knowns.
f12473:c0:m4
@classmethod<EOL><INDENT>def get(self, username=None, password=None, headers={}):<DEDENT>
if all((username, password, )):<EOL><INDENT>return BasicAuth(username, password, headers)<EOL><DEDENT>elif not any((username, password, )):<EOL><INDENT>return AnonymousAuth(headers)<EOL><DEDENT>else:<EOL><INDENT>if username is None:<EOL><INDENT>data = ("<STR_LIT:username>", username, )<EOL><DEDENT>else:<EOL><INDENT>data = ("<STR_LIT>", password, )<EOL><DEDENT>msg = "<STR_LIT>" % (data[<NUM_LIT:0>], data[<NUM_LIT:1>])<EOL>raise ValueError(msg)<EOL><DEDENT>
Factory method to get the correct AuthInfo object. The returned value depends on the arguments given. In case the username and password don't have a value (ie evaluate to False), return an object for anonymous access. Else, return an auth object that supports basic authentication. Args: `username`: The username of the user. `password`: The password of the user. `headers`: Custom headers to be sent to each request. Raises: ValueError in case one of the two arguments evaluates to False, (such as having the None value).
f12474:c0:m0
def populate_request_data(self, request_args):
return request_args<EOL>
Add any auth info to the arguments of the (to be performed) request. The method of the base class does nothing. Args: `request_args`: The arguments of the next request. Returns: The updated arguments for the request.
f12474:c0:m1
def __init__(self, username, password, headers={}):
self._username = username<EOL>self._password = password<EOL>self._headers = headers<EOL>
Initializer. :param str username: The username to be used for the authentication with Transifex. It can either have the value 'API' (suggested) or the username of a user :param str password: The password to be used for the authentication with Transifex. It should be a Transifex token (suggested) if the username is 'API', or the password of the user whose username is used for authentication :param dict headers: A dictionary with custom headers which will be sent in every request to the Transifex API.
f12474:c1:m0
def populate_request_data(self, request_args):
request_args['<STR_LIT>'] = HTTPBasicAuth(<EOL>self._username, self._password)<EOL>return request_args<EOL>
Add the authentication info to the supplied dictionary. We use the `requests.HTTPBasicAuth` class as the `auth` param. Args: `request_args`: The arguments that will be passed to the request. Returns: The updated arguments for the request.
f12474:c1:m1