id int32 0 252k | repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1 value | code stringlengths 75 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
227,600 | atztogo/phonopy | phonopy/interface/__init__.py | get_default_physical_units | def get_default_physical_units(interface_mode=None):
"""Return physical units used for calculators
Physical units: energy, distance, atomic mass, force
vasp : eV, Angstrom, AMU, eV/Angstrom
wien2k : Ry, au(=borh), AMU, mRy/au
abinit : hartree, au, AMU, eV/Angstrom
elk : hartree, au, AMU, hartree/au
qe : Ry, au, AMU, Ry/au
siesta : eV, au, AMU, eV/Angstroem
CRYSTAL : eV, Angstrom, AMU, eV/Angstroem
DFTB+ : hartree, au, AMU hartree/au
TURBOMOLE : hartree, au, AMU, hartree/au
"""
from phonopy.units import (Wien2kToTHz, AbinitToTHz, PwscfToTHz, ElkToTHz,
SiestaToTHz, VaspToTHz, CP2KToTHz, CrystalToTHz,
DftbpToTHz, TurbomoleToTHz, Hartree, Bohr)
units = {'factor': None,
'nac_factor': None,
'distance_to_A': None,
'force_constants_unit': None,
'length_unit': None}
if interface_mode is None or interface_mode == 'vasp':
units['factor'] = VaspToTHz
units['nac_factor'] = Hartree * Bohr
units['distance_to_A'] = 1.0
units['force_constants_unit'] = 'eV/Angstrom^2'
units['length_unit'] = 'Angstrom'
elif interface_mode == 'abinit':
units['factor'] = AbinitToTHz
units['nac_factor'] = Hartree / Bohr
units['distance_to_A'] = Bohr
units['force_constants_unit'] = 'eV/Angstrom.au'
units['length_unit'] = 'au'
elif interface_mode == 'qe':
units['factor'] = PwscfToTHz
units['nac_factor'] = 2.0
units['distance_to_A'] = Bohr
units['force_constants_unit'] = 'Ry/au^2'
units['length_unit'] = 'au'
elif interface_mode == 'wien2k':
units['factor'] = Wien2kToTHz
units['nac_factor'] = 2000.0
units['distance_to_A'] = Bohr
units['force_constants_unit'] = 'mRy/au^2'
units['length_unit'] = 'au'
elif interface_mode == 'elk':
units['factor'] = ElkToTHz
units['nac_factor'] = 1.0
units['distance_to_A'] = Bohr
units['force_constants_unit'] = 'hartree/au^2'
units['length_unit'] = 'au'
elif interface_mode == 'siesta':
units['factor'] = SiestaToTHz
units['nac_factor'] = Hartree / Bohr
units['distance_to_A'] = Bohr
units['force_constants_unit'] = 'eV/Angstrom.au'
units['length_unit'] = 'au'
elif interface_mode == 'cp2k':
units['factor'] = CP2KToTHz
units['nac_factor'] = Hartree / Bohr # in a.u.
units['distance_to_A'] = Bohr
units['force_constants_unit'] = 'hartree/au^2'
units['length_unit'] = 'Angstrom'
elif interface_mode == 'crystal':
units['factor'] = CrystalToTHz
units['nac_factor'] = Hartree * Bohr
units['distance_to_A'] = 1.0
units['force_constants_unit'] = 'eV/Angstrom^2'
units['length_unit'] = 'Angstrom'
elif interface_mode == 'dftbp':
units['factor'] = DftbpToTHz
units['nac_factor'] = Hartree * Bohr
units['distance_to_A'] = Bohr
units['force_constants_unit'] = 'hartree/au^2'
units['length_unit'] = 'au'
elif interface_mode == 'turbomole':
units['factor'] = TurbomoleToTHz
units['nac_factor'] = 1.0
units['distance_to_A'] = Bohr
units['force_constants_unit'] = 'hartree/au^2'
units['length_unit'] = 'au'
return units | python | def get_default_physical_units(interface_mode=None):
"""Return physical units used for calculators
Physical units: energy, distance, atomic mass, force
vasp : eV, Angstrom, AMU, eV/Angstrom
wien2k : Ry, au(=borh), AMU, mRy/au
abinit : hartree, au, AMU, eV/Angstrom
elk : hartree, au, AMU, hartree/au
qe : Ry, au, AMU, Ry/au
siesta : eV, au, AMU, eV/Angstroem
CRYSTAL : eV, Angstrom, AMU, eV/Angstroem
DFTB+ : hartree, au, AMU hartree/au
TURBOMOLE : hartree, au, AMU, hartree/au
"""
from phonopy.units import (Wien2kToTHz, AbinitToTHz, PwscfToTHz, ElkToTHz,
SiestaToTHz, VaspToTHz, CP2KToTHz, CrystalToTHz,
DftbpToTHz, TurbomoleToTHz, Hartree, Bohr)
units = {'factor': None,
'nac_factor': None,
'distance_to_A': None,
'force_constants_unit': None,
'length_unit': None}
if interface_mode is None or interface_mode == 'vasp':
units['factor'] = VaspToTHz
units['nac_factor'] = Hartree * Bohr
units['distance_to_A'] = 1.0
units['force_constants_unit'] = 'eV/Angstrom^2'
units['length_unit'] = 'Angstrom'
elif interface_mode == 'abinit':
units['factor'] = AbinitToTHz
units['nac_factor'] = Hartree / Bohr
units['distance_to_A'] = Bohr
units['force_constants_unit'] = 'eV/Angstrom.au'
units['length_unit'] = 'au'
elif interface_mode == 'qe':
units['factor'] = PwscfToTHz
units['nac_factor'] = 2.0
units['distance_to_A'] = Bohr
units['force_constants_unit'] = 'Ry/au^2'
units['length_unit'] = 'au'
elif interface_mode == 'wien2k':
units['factor'] = Wien2kToTHz
units['nac_factor'] = 2000.0
units['distance_to_A'] = Bohr
units['force_constants_unit'] = 'mRy/au^2'
units['length_unit'] = 'au'
elif interface_mode == 'elk':
units['factor'] = ElkToTHz
units['nac_factor'] = 1.0
units['distance_to_A'] = Bohr
units['force_constants_unit'] = 'hartree/au^2'
units['length_unit'] = 'au'
elif interface_mode == 'siesta':
units['factor'] = SiestaToTHz
units['nac_factor'] = Hartree / Bohr
units['distance_to_A'] = Bohr
units['force_constants_unit'] = 'eV/Angstrom.au'
units['length_unit'] = 'au'
elif interface_mode == 'cp2k':
units['factor'] = CP2KToTHz
units['nac_factor'] = Hartree / Bohr # in a.u.
units['distance_to_A'] = Bohr
units['force_constants_unit'] = 'hartree/au^2'
units['length_unit'] = 'Angstrom'
elif interface_mode == 'crystal':
units['factor'] = CrystalToTHz
units['nac_factor'] = Hartree * Bohr
units['distance_to_A'] = 1.0
units['force_constants_unit'] = 'eV/Angstrom^2'
units['length_unit'] = 'Angstrom'
elif interface_mode == 'dftbp':
units['factor'] = DftbpToTHz
units['nac_factor'] = Hartree * Bohr
units['distance_to_A'] = Bohr
units['force_constants_unit'] = 'hartree/au^2'
units['length_unit'] = 'au'
elif interface_mode == 'turbomole':
units['factor'] = TurbomoleToTHz
units['nac_factor'] = 1.0
units['distance_to_A'] = Bohr
units['force_constants_unit'] = 'hartree/au^2'
units['length_unit'] = 'au'
return units | [
"def",
"get_default_physical_units",
"(",
"interface_mode",
"=",
"None",
")",
":",
"from",
"phonopy",
".",
"units",
"import",
"(",
"Wien2kToTHz",
",",
"AbinitToTHz",
",",
"PwscfToTHz",
",",
"ElkToTHz",
",",
"SiestaToTHz",
",",
"VaspToTHz",
",",
"CP2KToTHz",
",",
"CrystalToTHz",
",",
"DftbpToTHz",
",",
"TurbomoleToTHz",
",",
"Hartree",
",",
"Bohr",
")",
"units",
"=",
"{",
"'factor'",
":",
"None",
",",
"'nac_factor'",
":",
"None",
",",
"'distance_to_A'",
":",
"None",
",",
"'force_constants_unit'",
":",
"None",
",",
"'length_unit'",
":",
"None",
"}",
"if",
"interface_mode",
"is",
"None",
"or",
"interface_mode",
"==",
"'vasp'",
":",
"units",
"[",
"'factor'",
"]",
"=",
"VaspToTHz",
"units",
"[",
"'nac_factor'",
"]",
"=",
"Hartree",
"*",
"Bohr",
"units",
"[",
"'distance_to_A'",
"]",
"=",
"1.0",
"units",
"[",
"'force_constants_unit'",
"]",
"=",
"'eV/Angstrom^2'",
"units",
"[",
"'length_unit'",
"]",
"=",
"'Angstrom'",
"elif",
"interface_mode",
"==",
"'abinit'",
":",
"units",
"[",
"'factor'",
"]",
"=",
"AbinitToTHz",
"units",
"[",
"'nac_factor'",
"]",
"=",
"Hartree",
"/",
"Bohr",
"units",
"[",
"'distance_to_A'",
"]",
"=",
"Bohr",
"units",
"[",
"'force_constants_unit'",
"]",
"=",
"'eV/Angstrom.au'",
"units",
"[",
"'length_unit'",
"]",
"=",
"'au'",
"elif",
"interface_mode",
"==",
"'qe'",
":",
"units",
"[",
"'factor'",
"]",
"=",
"PwscfToTHz",
"units",
"[",
"'nac_factor'",
"]",
"=",
"2.0",
"units",
"[",
"'distance_to_A'",
"]",
"=",
"Bohr",
"units",
"[",
"'force_constants_unit'",
"]",
"=",
"'Ry/au^2'",
"units",
"[",
"'length_unit'",
"]",
"=",
"'au'",
"elif",
"interface_mode",
"==",
"'wien2k'",
":",
"units",
"[",
"'factor'",
"]",
"=",
"Wien2kToTHz",
"units",
"[",
"'nac_factor'",
"]",
"=",
"2000.0",
"units",
"[",
"'distance_to_A'",
"]",
"=",
"Bohr",
"units",
"[",
"'force_constants_unit'",
"]",
"=",
"'mRy/au^2'",
"units",
"[",
"'length_unit'",
"]",
"=",
"'au'",
"elif",
"interface_mode",
"==",
"'elk'",
":",
"units",
"[",
"'factor'",
"]",
"=",
"ElkToTHz",
"units",
"[",
"'nac_factor'",
"]",
"=",
"1.0",
"units",
"[",
"'distance_to_A'",
"]",
"=",
"Bohr",
"units",
"[",
"'force_constants_unit'",
"]",
"=",
"'hartree/au^2'",
"units",
"[",
"'length_unit'",
"]",
"=",
"'au'",
"elif",
"interface_mode",
"==",
"'siesta'",
":",
"units",
"[",
"'factor'",
"]",
"=",
"SiestaToTHz",
"units",
"[",
"'nac_factor'",
"]",
"=",
"Hartree",
"/",
"Bohr",
"units",
"[",
"'distance_to_A'",
"]",
"=",
"Bohr",
"units",
"[",
"'force_constants_unit'",
"]",
"=",
"'eV/Angstrom.au'",
"units",
"[",
"'length_unit'",
"]",
"=",
"'au'",
"elif",
"interface_mode",
"==",
"'cp2k'",
":",
"units",
"[",
"'factor'",
"]",
"=",
"CP2KToTHz",
"units",
"[",
"'nac_factor'",
"]",
"=",
"Hartree",
"/",
"Bohr",
"# in a.u.",
"units",
"[",
"'distance_to_A'",
"]",
"=",
"Bohr",
"units",
"[",
"'force_constants_unit'",
"]",
"=",
"'hartree/au^2'",
"units",
"[",
"'length_unit'",
"]",
"=",
"'Angstrom'",
"elif",
"interface_mode",
"==",
"'crystal'",
":",
"units",
"[",
"'factor'",
"]",
"=",
"CrystalToTHz",
"units",
"[",
"'nac_factor'",
"]",
"=",
"Hartree",
"*",
"Bohr",
"units",
"[",
"'distance_to_A'",
"]",
"=",
"1.0",
"units",
"[",
"'force_constants_unit'",
"]",
"=",
"'eV/Angstrom^2'",
"units",
"[",
"'length_unit'",
"]",
"=",
"'Angstrom'",
"elif",
"interface_mode",
"==",
"'dftbp'",
":",
"units",
"[",
"'factor'",
"]",
"=",
"DftbpToTHz",
"units",
"[",
"'nac_factor'",
"]",
"=",
"Hartree",
"*",
"Bohr",
"units",
"[",
"'distance_to_A'",
"]",
"=",
"Bohr",
"units",
"[",
"'force_constants_unit'",
"]",
"=",
"'hartree/au^2'",
"units",
"[",
"'length_unit'",
"]",
"=",
"'au'",
"elif",
"interface_mode",
"==",
"'turbomole'",
":",
"units",
"[",
"'factor'",
"]",
"=",
"TurbomoleToTHz",
"units",
"[",
"'nac_factor'",
"]",
"=",
"1.0",
"units",
"[",
"'distance_to_A'",
"]",
"=",
"Bohr",
"units",
"[",
"'force_constants_unit'",
"]",
"=",
"'hartree/au^2'",
"units",
"[",
"'length_unit'",
"]",
"=",
"'au'",
"return",
"units"
] | Return physical units used for calculators
Physical units: energy, distance, atomic mass, force
vasp : eV, Angstrom, AMU, eV/Angstrom
wien2k : Ry, au(=borh), AMU, mRy/au
abinit : hartree, au, AMU, eV/Angstrom
elk : hartree, au, AMU, hartree/au
qe : Ry, au, AMU, Ry/au
siesta : eV, au, AMU, eV/Angstroem
CRYSTAL : eV, Angstrom, AMU, eV/Angstroem
DFTB+ : hartree, au, AMU hartree/au
TURBOMOLE : hartree, au, AMU, hartree/au | [
"Return",
"physical",
"units",
"used",
"for",
"calculators"
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/interface/__init__.py#L231-L318 |
227,601 | atztogo/phonopy | phonopy/structure/tetrahedron_method.py | get_tetrahedra_integration_weight | def get_tetrahedra_integration_weight(omegas,
tetrahedra_omegas,
function='I'):
"""Returns integration weights
Parameters
----------
omegas : float or list of float values
Energy(s) at which the integration weight(s) are computed.
tetrahedra_omegas : ndarray of list of list
Energies at vertices of 24 tetrahedra
shape=(24, 4)
dytpe='double'
function : str, 'I' or 'J'
'J' is for intetration and 'I' is for its derivative.
"""
if isinstance(omegas, float):
return phonoc.tetrahedra_integration_weight(
omegas,
np.array(tetrahedra_omegas, dtype='double', order='C'),
function)
else:
integration_weights = np.zeros(len(omegas), dtype='double')
phonoc.tetrahedra_integration_weight_at_omegas(
integration_weights,
np.array(omegas, dtype='double'),
np.array(tetrahedra_omegas, dtype='double', order='C'),
function)
return integration_weights | python | def get_tetrahedra_integration_weight(omegas,
tetrahedra_omegas,
function='I'):
"""Returns integration weights
Parameters
----------
omegas : float or list of float values
Energy(s) at which the integration weight(s) are computed.
tetrahedra_omegas : ndarray of list of list
Energies at vertices of 24 tetrahedra
shape=(24, 4)
dytpe='double'
function : str, 'I' or 'J'
'J' is for intetration and 'I' is for its derivative.
"""
if isinstance(omegas, float):
return phonoc.tetrahedra_integration_weight(
omegas,
np.array(tetrahedra_omegas, dtype='double', order='C'),
function)
else:
integration_weights = np.zeros(len(omegas), dtype='double')
phonoc.tetrahedra_integration_weight_at_omegas(
integration_weights,
np.array(omegas, dtype='double'),
np.array(tetrahedra_omegas, dtype='double', order='C'),
function)
return integration_weights | [
"def",
"get_tetrahedra_integration_weight",
"(",
"omegas",
",",
"tetrahedra_omegas",
",",
"function",
"=",
"'I'",
")",
":",
"if",
"isinstance",
"(",
"omegas",
",",
"float",
")",
":",
"return",
"phonoc",
".",
"tetrahedra_integration_weight",
"(",
"omegas",
",",
"np",
".",
"array",
"(",
"tetrahedra_omegas",
",",
"dtype",
"=",
"'double'",
",",
"order",
"=",
"'C'",
")",
",",
"function",
")",
"else",
":",
"integration_weights",
"=",
"np",
".",
"zeros",
"(",
"len",
"(",
"omegas",
")",
",",
"dtype",
"=",
"'double'",
")",
"phonoc",
".",
"tetrahedra_integration_weight_at_omegas",
"(",
"integration_weights",
",",
"np",
".",
"array",
"(",
"omegas",
",",
"dtype",
"=",
"'double'",
")",
",",
"np",
".",
"array",
"(",
"tetrahedra_omegas",
",",
"dtype",
"=",
"'double'",
",",
"order",
"=",
"'C'",
")",
",",
"function",
")",
"return",
"integration_weights"
] | Returns integration weights
Parameters
----------
omegas : float or list of float values
Energy(s) at which the integration weight(s) are computed.
tetrahedra_omegas : ndarray of list of list
Energies at vertices of 24 tetrahedra
shape=(24, 4)
dytpe='double'
function : str, 'I' or 'J'
'J' is for intetration and 'I' is for its derivative. | [
"Returns",
"integration",
"weights"
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/structure/tetrahedron_method.py#L95-L125 |
227,602 | atztogo/phonopy | phonopy/structure/tetrahedron_method.py | TetrahedronMethod._g_1 | def _g_1(self):
"""omega1 < omega < omega2"""
# return 3 * self._n_1() / (self._omega - self._vertices_omegas[0])
return (3 * self._f(1, 0) * self._f(2, 0) /
(self._vertices_omegas[3] - self._vertices_omegas[0])) | python | def _g_1(self):
"""omega1 < omega < omega2"""
# return 3 * self._n_1() / (self._omega - self._vertices_omegas[0])
return (3 * self._f(1, 0) * self._f(2, 0) /
(self._vertices_omegas[3] - self._vertices_omegas[0])) | [
"def",
"_g_1",
"(",
"self",
")",
":",
"# return 3 * self._n_1() / (self._omega - self._vertices_omegas[0])",
"return",
"(",
"3",
"*",
"self",
".",
"_f",
"(",
"1",
",",
"0",
")",
"*",
"self",
".",
"_f",
"(",
"2",
",",
"0",
")",
"/",
"(",
"self",
".",
"_vertices_omegas",
"[",
"3",
"]",
"-",
"self",
".",
"_vertices_omegas",
"[",
"0",
"]",
")",
")"
] | omega1 < omega < omega2 | [
"omega1",
"<",
"omega",
"<",
"omega2"
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/structure/tetrahedron_method.py#L438-L442 |
227,603 | atztogo/phonopy | phonopy/structure/tetrahedron_method.py | TetrahedronMethod._g_3 | def _g_3(self):
"""omega3 < omega < omega4"""
# return 3 * (1.0 - self._n_3()) / (self._vertices_omegas[3] - self._omega)
return (3 * self._f(1, 3) * self._f(2, 3) /
(self._vertices_omegas[3] - self._vertices_omegas[0])) | python | def _g_3(self):
"""omega3 < omega < omega4"""
# return 3 * (1.0 - self._n_3()) / (self._vertices_omegas[3] - self._omega)
return (3 * self._f(1, 3) * self._f(2, 3) /
(self._vertices_omegas[3] - self._vertices_omegas[0])) | [
"def",
"_g_3",
"(",
"self",
")",
":",
"# return 3 * (1.0 - self._n_3()) / (self._vertices_omegas[3] - self._omega)",
"return",
"(",
"3",
"*",
"self",
".",
"_f",
"(",
"1",
",",
"3",
")",
"*",
"self",
".",
"_f",
"(",
"2",
",",
"3",
")",
"/",
"(",
"self",
".",
"_vertices_omegas",
"[",
"3",
"]",
"-",
"self",
".",
"_vertices_omegas",
"[",
"0",
"]",
")",
")"
] | omega3 < omega < omega4 | [
"omega3",
"<",
"omega",
"<",
"omega4"
] | 869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/structure/tetrahedron_method.py#L450-L454 |
227,604 | mattupstate/flask-security | flask_security/datastore.py | UserDatastore.deactivate_user | def deactivate_user(self, user):
"""Deactivates a specified user. Returns `True` if a change was made.
:param user: The user to deactivate
"""
if user.active:
user.active = False
return True
return False | python | def deactivate_user(self, user):
"""Deactivates a specified user. Returns `True` if a change was made.
:param user: The user to deactivate
"""
if user.active:
user.active = False
return True
return False | [
"def",
"deactivate_user",
"(",
"self",
",",
"user",
")",
":",
"if",
"user",
".",
"active",
":",
"user",
".",
"active",
"=",
"False",
"return",
"True",
"return",
"False"
] | Deactivates a specified user. Returns `True` if a change was made.
:param user: The user to deactivate | [
"Deactivates",
"a",
"specified",
"user",
".",
"Returns",
"True",
"if",
"a",
"change",
"was",
"made",
"."
] | a401fb47018fbbbe0b899ea55afadfd0e3cd847a | https://github.com/mattupstate/flask-security/blob/a401fb47018fbbbe0b899ea55afadfd0e3cd847a/flask_security/datastore.py#L180-L188 |
227,605 | mattupstate/flask-security | flask_security/datastore.py | UserDatastore.activate_user | def activate_user(self, user):
"""Activates a specified user. Returns `True` if a change was made.
:param user: The user to activate
"""
if not user.active:
user.active = True
return True
return False | python | def activate_user(self, user):
"""Activates a specified user. Returns `True` if a change was made.
:param user: The user to activate
"""
if not user.active:
user.active = True
return True
return False | [
"def",
"activate_user",
"(",
"self",
",",
"user",
")",
":",
"if",
"not",
"user",
".",
"active",
":",
"user",
".",
"active",
"=",
"True",
"return",
"True",
"return",
"False"
] | Activates a specified user. Returns `True` if a change was made.
:param user: The user to activate | [
"Activates",
"a",
"specified",
"user",
".",
"Returns",
"True",
"if",
"a",
"change",
"was",
"made",
"."
] | a401fb47018fbbbe0b899ea55afadfd0e3cd847a | https://github.com/mattupstate/flask-security/blob/a401fb47018fbbbe0b899ea55afadfd0e3cd847a/flask_security/datastore.py#L190-L198 |
227,606 | mattupstate/flask-security | flask_security/datastore.py | UserDatastore.create_role | def create_role(self, **kwargs):
"""Creates and returns a new role from the given parameters."""
role = self.role_model(**kwargs)
return self.put(role) | python | def create_role(self, **kwargs):
"""Creates and returns a new role from the given parameters."""
role = self.role_model(**kwargs)
return self.put(role) | [
"def",
"create_role",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"role",
"=",
"self",
".",
"role_model",
"(",
"*",
"*",
"kwargs",
")",
"return",
"self",
".",
"put",
"(",
"role",
")"
] | Creates and returns a new role from the given parameters. | [
"Creates",
"and",
"returns",
"a",
"new",
"role",
"from",
"the",
"given",
"parameters",
"."
] | a401fb47018fbbbe0b899ea55afadfd0e3cd847a | https://github.com/mattupstate/flask-security/blob/a401fb47018fbbbe0b899ea55afadfd0e3cd847a/flask_security/datastore.py#L200-L204 |
227,607 | mattupstate/flask-security | flask_security/datastore.py | UserDatastore.find_or_create_role | def find_or_create_role(self, name, **kwargs):
"""Returns a role matching the given name or creates it with any
additionally provided parameters.
"""
kwargs["name"] = name
return self.find_role(name) or self.create_role(**kwargs) | python | def find_or_create_role(self, name, **kwargs):
"""Returns a role matching the given name or creates it with any
additionally provided parameters.
"""
kwargs["name"] = name
return self.find_role(name) or self.create_role(**kwargs) | [
"def",
"find_or_create_role",
"(",
"self",
",",
"name",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"\"name\"",
"]",
"=",
"name",
"return",
"self",
".",
"find_role",
"(",
"name",
")",
"or",
"self",
".",
"create_role",
"(",
"*",
"*",
"kwargs",
")"
] | Returns a role matching the given name or creates it with any
additionally provided parameters. | [
"Returns",
"a",
"role",
"matching",
"the",
"given",
"name",
"or",
"creates",
"it",
"with",
"any",
"additionally",
"provided",
"parameters",
"."
] | a401fb47018fbbbe0b899ea55afadfd0e3cd847a | https://github.com/mattupstate/flask-security/blob/a401fb47018fbbbe0b899ea55afadfd0e3cd847a/flask_security/datastore.py#L206-L211 |
227,608 | mattupstate/flask-security | flask_security/decorators.py | http_auth_required | def http_auth_required(realm):
"""Decorator that protects endpoints using Basic HTTP authentication.
:param realm: optional realm name"""
def decorator(fn):
@wraps(fn)
def wrapper(*args, **kwargs):
if _check_http_auth():
return fn(*args, **kwargs)
if _security._unauthorized_callback:
return _security._unauthorized_callback()
else:
r = _security.default_http_auth_realm \
if callable(realm) else realm
h = {'WWW-Authenticate': 'Basic realm="%s"' % r}
return _get_unauthorized_response(headers=h)
return wrapper
if callable(realm):
return decorator(realm)
return decorator | python | def http_auth_required(realm):
"""Decorator that protects endpoints using Basic HTTP authentication.
:param realm: optional realm name"""
def decorator(fn):
@wraps(fn)
def wrapper(*args, **kwargs):
if _check_http_auth():
return fn(*args, **kwargs)
if _security._unauthorized_callback:
return _security._unauthorized_callback()
else:
r = _security.default_http_auth_realm \
if callable(realm) else realm
h = {'WWW-Authenticate': 'Basic realm="%s"' % r}
return _get_unauthorized_response(headers=h)
return wrapper
if callable(realm):
return decorator(realm)
return decorator | [
"def",
"http_auth_required",
"(",
"realm",
")",
":",
"def",
"decorator",
"(",
"fn",
")",
":",
"@",
"wraps",
"(",
"fn",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"_check_http_auth",
"(",
")",
":",
"return",
"fn",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"if",
"_security",
".",
"_unauthorized_callback",
":",
"return",
"_security",
".",
"_unauthorized_callback",
"(",
")",
"else",
":",
"r",
"=",
"_security",
".",
"default_http_auth_realm",
"if",
"callable",
"(",
"realm",
")",
"else",
"realm",
"h",
"=",
"{",
"'WWW-Authenticate'",
":",
"'Basic realm=\"%s\"'",
"%",
"r",
"}",
"return",
"_get_unauthorized_response",
"(",
"headers",
"=",
"h",
")",
"return",
"wrapper",
"if",
"callable",
"(",
"realm",
")",
":",
"return",
"decorator",
"(",
"realm",
")",
"return",
"decorator"
] | Decorator that protects endpoints using Basic HTTP authentication.
:param realm: optional realm name | [
"Decorator",
"that",
"protects",
"endpoints",
"using",
"Basic",
"HTTP",
"authentication",
"."
] | a401fb47018fbbbe0b899ea55afadfd0e3cd847a | https://github.com/mattupstate/flask-security/blob/a401fb47018fbbbe0b899ea55afadfd0e3cd847a/flask_security/decorators.py#L93-L114 |
227,609 | mattupstate/flask-security | flask_security/decorators.py | auth_token_required | def auth_token_required(fn):
"""Decorator that protects endpoints using token authentication. The token
should be added to the request by the client by using a query string
variable with a name equal to the configuration value of
`SECURITY_TOKEN_AUTHENTICATION_KEY` or in a request header named that of
the configuration value of `SECURITY_TOKEN_AUTHENTICATION_HEADER`
"""
@wraps(fn)
def decorated(*args, **kwargs):
if _check_token():
return fn(*args, **kwargs)
if _security._unauthorized_callback:
return _security._unauthorized_callback()
else:
return _get_unauthorized_response()
return decorated | python | def auth_token_required(fn):
"""Decorator that protects endpoints using token authentication. The token
should be added to the request by the client by using a query string
variable with a name equal to the configuration value of
`SECURITY_TOKEN_AUTHENTICATION_KEY` or in a request header named that of
the configuration value of `SECURITY_TOKEN_AUTHENTICATION_HEADER`
"""
@wraps(fn)
def decorated(*args, **kwargs):
if _check_token():
return fn(*args, **kwargs)
if _security._unauthorized_callback:
return _security._unauthorized_callback()
else:
return _get_unauthorized_response()
return decorated | [
"def",
"auth_token_required",
"(",
"fn",
")",
":",
"@",
"wraps",
"(",
"fn",
")",
"def",
"decorated",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"_check_token",
"(",
")",
":",
"return",
"fn",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"if",
"_security",
".",
"_unauthorized_callback",
":",
"return",
"_security",
".",
"_unauthorized_callback",
"(",
")",
"else",
":",
"return",
"_get_unauthorized_response",
"(",
")",
"return",
"decorated"
] | Decorator that protects endpoints using token authentication. The token
should be added to the request by the client by using a query string
variable with a name equal to the configuration value of
`SECURITY_TOKEN_AUTHENTICATION_KEY` or in a request header named that of
the configuration value of `SECURITY_TOKEN_AUTHENTICATION_HEADER` | [
"Decorator",
"that",
"protects",
"endpoints",
"using",
"token",
"authentication",
".",
"The",
"token",
"should",
"be",
"added",
"to",
"the",
"request",
"by",
"the",
"client",
"by",
"using",
"a",
"query",
"string",
"variable",
"with",
"a",
"name",
"equal",
"to",
"the",
"configuration",
"value",
"of",
"SECURITY_TOKEN_AUTHENTICATION_KEY",
"or",
"in",
"a",
"request",
"header",
"named",
"that",
"of",
"the",
"configuration",
"value",
"of",
"SECURITY_TOKEN_AUTHENTICATION_HEADER"
] | a401fb47018fbbbe0b899ea55afadfd0e3cd847a | https://github.com/mattupstate/flask-security/blob/a401fb47018fbbbe0b899ea55afadfd0e3cd847a/flask_security/decorators.py#L117-L133 |
227,610 | mattupstate/flask-security | flask_security/confirmable.py | confirm_user | def confirm_user(user):
"""Confirms the specified user
:param user: The user to confirm
"""
if user.confirmed_at is not None:
return False
user.confirmed_at = _security.datetime_factory()
_datastore.put(user)
user_confirmed.send(app._get_current_object(), user=user)
return True | python | def confirm_user(user):
"""Confirms the specified user
:param user: The user to confirm
"""
if user.confirmed_at is not None:
return False
user.confirmed_at = _security.datetime_factory()
_datastore.put(user)
user_confirmed.send(app._get_current_object(), user=user)
return True | [
"def",
"confirm_user",
"(",
"user",
")",
":",
"if",
"user",
".",
"confirmed_at",
"is",
"not",
"None",
":",
"return",
"False",
"user",
".",
"confirmed_at",
"=",
"_security",
".",
"datetime_factory",
"(",
")",
"_datastore",
".",
"put",
"(",
"user",
")",
"user_confirmed",
".",
"send",
"(",
"app",
".",
"_get_current_object",
"(",
")",
",",
"user",
"=",
"user",
")",
"return",
"True"
] | Confirms the specified user
:param user: The user to confirm | [
"Confirms",
"the",
"specified",
"user"
] | a401fb47018fbbbe0b899ea55afadfd0e3cd847a | https://github.com/mattupstate/flask-security/blob/a401fb47018fbbbe0b899ea55afadfd0e3cd847a/flask_security/confirmable.py#L82-L92 |
227,611 | mattupstate/flask-security | flask_security/recoverable.py | send_password_reset_notice | def send_password_reset_notice(user):
"""Sends the password reset notice email for the specified user.
:param user: The user to send the notice to
"""
if config_value('SEND_PASSWORD_RESET_NOTICE_EMAIL'):
_security.send_mail(config_value('EMAIL_SUBJECT_PASSWORD_NOTICE'),
user.email, 'reset_notice', user=user) | python | def send_password_reset_notice(user):
"""Sends the password reset notice email for the specified user.
:param user: The user to send the notice to
"""
if config_value('SEND_PASSWORD_RESET_NOTICE_EMAIL'):
_security.send_mail(config_value('EMAIL_SUBJECT_PASSWORD_NOTICE'),
user.email, 'reset_notice', user=user) | [
"def",
"send_password_reset_notice",
"(",
"user",
")",
":",
"if",
"config_value",
"(",
"'SEND_PASSWORD_RESET_NOTICE_EMAIL'",
")",
":",
"_security",
".",
"send_mail",
"(",
"config_value",
"(",
"'EMAIL_SUBJECT_PASSWORD_NOTICE'",
")",
",",
"user",
".",
"email",
",",
"'reset_notice'",
",",
"user",
"=",
"user",
")"
] | Sends the password reset notice email for the specified user.
:param user: The user to send the notice to | [
"Sends",
"the",
"password",
"reset",
"notice",
"email",
"for",
"the",
"specified",
"user",
"."
] | a401fb47018fbbbe0b899ea55afadfd0e3cd847a | https://github.com/mattupstate/flask-security/blob/a401fb47018fbbbe0b899ea55afadfd0e3cd847a/flask_security/recoverable.py#L45-L52 |
227,612 | mattupstate/flask-security | flask_security/recoverable.py | update_password | def update_password(user, password):
"""Update the specified user's password
:param user: The user to update_password
:param password: The unhashed new password
"""
user.password = hash_password(password)
_datastore.put(user)
send_password_reset_notice(user)
password_reset.send(app._get_current_object(), user=user) | python | def update_password(user, password):
"""Update the specified user's password
:param user: The user to update_password
:param password: The unhashed new password
"""
user.password = hash_password(password)
_datastore.put(user)
send_password_reset_notice(user)
password_reset.send(app._get_current_object(), user=user) | [
"def",
"update_password",
"(",
"user",
",",
"password",
")",
":",
"user",
".",
"password",
"=",
"hash_password",
"(",
"password",
")",
"_datastore",
".",
"put",
"(",
"user",
")",
"send_password_reset_notice",
"(",
"user",
")",
"password_reset",
".",
"send",
"(",
"app",
".",
"_get_current_object",
"(",
")",
",",
"user",
"=",
"user",
")"
] | Update the specified user's password
:param user: The user to update_password
:param password: The unhashed new password | [
"Update",
"the",
"specified",
"user",
"s",
"password"
] | a401fb47018fbbbe0b899ea55afadfd0e3cd847a | https://github.com/mattupstate/flask-security/blob/a401fb47018fbbbe0b899ea55afadfd0e3cd847a/flask_security/recoverable.py#L84-L93 |
227,613 | mattupstate/flask-security | flask_security/core.py | Security.init_app | def init_app(self, app, datastore=None, register_blueprint=None, **kwargs):
"""Initializes the Flask-Security extension for the specified
application and datastore implementation.
:param app: The application.
:param datastore: An instance of a user datastore.
:param register_blueprint: to register the Security blueprint or not.
"""
self.app = app
if datastore is None:
datastore = self._datastore
if register_blueprint is None:
register_blueprint = self._register_blueprint
for key, value in self._kwargs.items():
kwargs.setdefault(key, value)
for key, value in _default_config.items():
app.config.setdefault('SECURITY_' + key, value)
for key, value in _default_messages.items():
app.config.setdefault('SECURITY_MSG_' + key, value)
identity_loaded.connect_via(app)(_on_identity_loaded)
self._state = state = _get_state(app, datastore, **kwargs)
if register_blueprint:
app.register_blueprint(create_blueprint(state, __name__))
app.context_processor(_context_processor)
@app.before_first_request
def _register_i18n():
if '_' not in app.jinja_env.globals:
app.jinja_env.globals['_'] = state.i18n_domain.gettext
state.render_template = self.render_template
state.send_mail = self.send_mail
app.extensions['security'] = state
if hasattr(app, 'cli'):
from .cli import users, roles
if state.cli_users_name:
app.cli.add_command(users, state.cli_users_name)
if state.cli_roles_name:
app.cli.add_command(roles, state.cli_roles_name)
return state | python | def init_app(self, app, datastore=None, register_blueprint=None, **kwargs):
"""Initializes the Flask-Security extension for the specified
application and datastore implementation.
:param app: The application.
:param datastore: An instance of a user datastore.
:param register_blueprint: to register the Security blueprint or not.
"""
self.app = app
if datastore is None:
datastore = self._datastore
if register_blueprint is None:
register_blueprint = self._register_blueprint
for key, value in self._kwargs.items():
kwargs.setdefault(key, value)
for key, value in _default_config.items():
app.config.setdefault('SECURITY_' + key, value)
for key, value in _default_messages.items():
app.config.setdefault('SECURITY_MSG_' + key, value)
identity_loaded.connect_via(app)(_on_identity_loaded)
self._state = state = _get_state(app, datastore, **kwargs)
if register_blueprint:
app.register_blueprint(create_blueprint(state, __name__))
app.context_processor(_context_processor)
@app.before_first_request
def _register_i18n():
if '_' not in app.jinja_env.globals:
app.jinja_env.globals['_'] = state.i18n_domain.gettext
state.render_template = self.render_template
state.send_mail = self.send_mail
app.extensions['security'] = state
if hasattr(app, 'cli'):
from .cli import users, roles
if state.cli_users_name:
app.cli.add_command(users, state.cli_users_name)
if state.cli_roles_name:
app.cli.add_command(roles, state.cli_roles_name)
return state | [
"def",
"init_app",
"(",
"self",
",",
"app",
",",
"datastore",
"=",
"None",
",",
"register_blueprint",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"app",
"=",
"app",
"if",
"datastore",
"is",
"None",
":",
"datastore",
"=",
"self",
".",
"_datastore",
"if",
"register_blueprint",
"is",
"None",
":",
"register_blueprint",
"=",
"self",
".",
"_register_blueprint",
"for",
"key",
",",
"value",
"in",
"self",
".",
"_kwargs",
".",
"items",
"(",
")",
":",
"kwargs",
".",
"setdefault",
"(",
"key",
",",
"value",
")",
"for",
"key",
",",
"value",
"in",
"_default_config",
".",
"items",
"(",
")",
":",
"app",
".",
"config",
".",
"setdefault",
"(",
"'SECURITY_'",
"+",
"key",
",",
"value",
")",
"for",
"key",
",",
"value",
"in",
"_default_messages",
".",
"items",
"(",
")",
":",
"app",
".",
"config",
".",
"setdefault",
"(",
"'SECURITY_MSG_'",
"+",
"key",
",",
"value",
")",
"identity_loaded",
".",
"connect_via",
"(",
"app",
")",
"(",
"_on_identity_loaded",
")",
"self",
".",
"_state",
"=",
"state",
"=",
"_get_state",
"(",
"app",
",",
"datastore",
",",
"*",
"*",
"kwargs",
")",
"if",
"register_blueprint",
":",
"app",
".",
"register_blueprint",
"(",
"create_blueprint",
"(",
"state",
",",
"__name__",
")",
")",
"app",
".",
"context_processor",
"(",
"_context_processor",
")",
"@",
"app",
".",
"before_first_request",
"def",
"_register_i18n",
"(",
")",
":",
"if",
"'_'",
"not",
"in",
"app",
".",
"jinja_env",
".",
"globals",
":",
"app",
".",
"jinja_env",
".",
"globals",
"[",
"'_'",
"]",
"=",
"state",
".",
"i18n_domain",
".",
"gettext",
"state",
".",
"render_template",
"=",
"self",
".",
"render_template",
"state",
".",
"send_mail",
"=",
"self",
".",
"send_mail",
"app",
".",
"extensions",
"[",
"'security'",
"]",
"=",
"state",
"if",
"hasattr",
"(",
"app",
",",
"'cli'",
")",
":",
"from",
".",
"cli",
"import",
"users",
",",
"roles",
"if",
"state",
".",
"cli_users_name",
":",
"app",
".",
"cli",
".",
"add_command",
"(",
"users",
",",
"state",
".",
"cli_users_name",
")",
"if",
"state",
".",
"cli_roles_name",
":",
"app",
".",
"cli",
".",
"add_command",
"(",
"roles",
",",
"state",
".",
"cli_roles_name",
")",
"return",
"state"
] | Initializes the Flask-Security extension for the specified
application and datastore implementation.
:param app: The application.
:param datastore: An instance of a user datastore.
:param register_blueprint: to register the Security blueprint or not. | [
"Initializes",
"the",
"Flask",
"-",
"Security",
"extension",
"for",
"the",
"specified",
"application",
"and",
"datastore",
"implementation",
"."
] | a401fb47018fbbbe0b899ea55afadfd0e3cd847a | https://github.com/mattupstate/flask-security/blob/a401fb47018fbbbe0b899ea55afadfd0e3cd847a/flask_security/core.py#L511-L560 |
227,614 | mattupstate/flask-security | flask_security/views.py | login | def login():
"""View function for login view"""
form_class = _security.login_form
if request.is_json:
form = form_class(MultiDict(request.get_json()))
else:
form = form_class(request.form)
if form.validate_on_submit():
login_user(form.user, remember=form.remember.data)
after_this_request(_commit)
if not request.is_json:
return redirect(get_post_login_redirect(form.next.data))
if request.is_json:
return _render_json(form, include_auth_token=True)
return _security.render_template(config_value('LOGIN_USER_TEMPLATE'),
login_user_form=form,
**_ctx('login')) | python | def login():
"""View function for login view"""
form_class = _security.login_form
if request.is_json:
form = form_class(MultiDict(request.get_json()))
else:
form = form_class(request.form)
if form.validate_on_submit():
login_user(form.user, remember=form.remember.data)
after_this_request(_commit)
if not request.is_json:
return redirect(get_post_login_redirect(form.next.data))
if request.is_json:
return _render_json(form, include_auth_token=True)
return _security.render_template(config_value('LOGIN_USER_TEMPLATE'),
login_user_form=form,
**_ctx('login')) | [
"def",
"login",
"(",
")",
":",
"form_class",
"=",
"_security",
".",
"login_form",
"if",
"request",
".",
"is_json",
":",
"form",
"=",
"form_class",
"(",
"MultiDict",
"(",
"request",
".",
"get_json",
"(",
")",
")",
")",
"else",
":",
"form",
"=",
"form_class",
"(",
"request",
".",
"form",
")",
"if",
"form",
".",
"validate_on_submit",
"(",
")",
":",
"login_user",
"(",
"form",
".",
"user",
",",
"remember",
"=",
"form",
".",
"remember",
".",
"data",
")",
"after_this_request",
"(",
"_commit",
")",
"if",
"not",
"request",
".",
"is_json",
":",
"return",
"redirect",
"(",
"get_post_login_redirect",
"(",
"form",
".",
"next",
".",
"data",
")",
")",
"if",
"request",
".",
"is_json",
":",
"return",
"_render_json",
"(",
"form",
",",
"include_auth_token",
"=",
"True",
")",
"return",
"_security",
".",
"render_template",
"(",
"config_value",
"(",
"'LOGIN_USER_TEMPLATE'",
")",
",",
"login_user_form",
"=",
"form",
",",
"*",
"*",
"_ctx",
"(",
"'login'",
")",
")"
] | View function for login view | [
"View",
"function",
"for",
"login",
"view"
] | a401fb47018fbbbe0b899ea55afadfd0e3cd847a | https://github.com/mattupstate/flask-security/blob/a401fb47018fbbbe0b899ea55afadfd0e3cd847a/flask_security/views.py#L67-L89 |
227,615 | mattupstate/flask-security | flask_security/views.py | register | def register():
"""View function which handles a registration request."""
if _security.confirmable or request.is_json:
form_class = _security.confirm_register_form
else:
form_class = _security.register_form
if request.is_json:
form_data = MultiDict(request.get_json())
else:
form_data = request.form
form = form_class(form_data)
if form.validate_on_submit():
user = register_user(**form.to_dict())
form.user = user
if not _security.confirmable or _security.login_without_confirmation:
after_this_request(_commit)
login_user(user)
if not request.is_json:
if 'next' in form:
redirect_url = get_post_register_redirect(form.next.data)
else:
redirect_url = get_post_register_redirect()
return redirect(redirect_url)
return _render_json(form, include_auth_token=True)
if request.is_json:
return _render_json(form)
return _security.render_template(config_value('REGISTER_USER_TEMPLATE'),
register_user_form=form,
**_ctx('register')) | python | def register():
"""View function which handles a registration request."""
if _security.confirmable or request.is_json:
form_class = _security.confirm_register_form
else:
form_class = _security.register_form
if request.is_json:
form_data = MultiDict(request.get_json())
else:
form_data = request.form
form = form_class(form_data)
if form.validate_on_submit():
user = register_user(**form.to_dict())
form.user = user
if not _security.confirmable or _security.login_without_confirmation:
after_this_request(_commit)
login_user(user)
if not request.is_json:
if 'next' in form:
redirect_url = get_post_register_redirect(form.next.data)
else:
redirect_url = get_post_register_redirect()
return redirect(redirect_url)
return _render_json(form, include_auth_token=True)
if request.is_json:
return _render_json(form)
return _security.render_template(config_value('REGISTER_USER_TEMPLATE'),
register_user_form=form,
**_ctx('register')) | [
"def",
"register",
"(",
")",
":",
"if",
"_security",
".",
"confirmable",
"or",
"request",
".",
"is_json",
":",
"form_class",
"=",
"_security",
".",
"confirm_register_form",
"else",
":",
"form_class",
"=",
"_security",
".",
"register_form",
"if",
"request",
".",
"is_json",
":",
"form_data",
"=",
"MultiDict",
"(",
"request",
".",
"get_json",
"(",
")",
")",
"else",
":",
"form_data",
"=",
"request",
".",
"form",
"form",
"=",
"form_class",
"(",
"form_data",
")",
"if",
"form",
".",
"validate_on_submit",
"(",
")",
":",
"user",
"=",
"register_user",
"(",
"*",
"*",
"form",
".",
"to_dict",
"(",
")",
")",
"form",
".",
"user",
"=",
"user",
"if",
"not",
"_security",
".",
"confirmable",
"or",
"_security",
".",
"login_without_confirmation",
":",
"after_this_request",
"(",
"_commit",
")",
"login_user",
"(",
"user",
")",
"if",
"not",
"request",
".",
"is_json",
":",
"if",
"'next'",
"in",
"form",
":",
"redirect_url",
"=",
"get_post_register_redirect",
"(",
"form",
".",
"next",
".",
"data",
")",
"else",
":",
"redirect_url",
"=",
"get_post_register_redirect",
"(",
")",
"return",
"redirect",
"(",
"redirect_url",
")",
"return",
"_render_json",
"(",
"form",
",",
"include_auth_token",
"=",
"True",
")",
"if",
"request",
".",
"is_json",
":",
"return",
"_render_json",
"(",
"form",
")",
"return",
"_security",
".",
"render_template",
"(",
"config_value",
"(",
"'REGISTER_USER_TEMPLATE'",
")",
",",
"register_user_form",
"=",
"form",
",",
"*",
"*",
"_ctx",
"(",
"'register'",
")",
")"
] | View function which handles a registration request. | [
"View",
"function",
"which",
"handles",
"a",
"registration",
"request",
"."
] | a401fb47018fbbbe0b899ea55afadfd0e3cd847a | https://github.com/mattupstate/flask-security/blob/a401fb47018fbbbe0b899ea55afadfd0e3cd847a/flask_security/views.py#L102-L139 |
227,616 | mattupstate/flask-security | flask_security/views.py | send_login | def send_login():
"""View function that sends login instructions for passwordless login"""
form_class = _security.passwordless_login_form
if request.is_json:
form = form_class(MultiDict(request.get_json()))
else:
form = form_class()
if form.validate_on_submit():
send_login_instructions(form.user)
if not request.is_json:
do_flash(*get_message('LOGIN_EMAIL_SENT', email=form.user.email))
if request.is_json:
return _render_json(form)
return _security.render_template(config_value('SEND_LOGIN_TEMPLATE'),
send_login_form=form,
**_ctx('send_login')) | python | def send_login():
"""View function that sends login instructions for passwordless login"""
form_class = _security.passwordless_login_form
if request.is_json:
form = form_class(MultiDict(request.get_json()))
else:
form = form_class()
if form.validate_on_submit():
send_login_instructions(form.user)
if not request.is_json:
do_flash(*get_message('LOGIN_EMAIL_SENT', email=form.user.email))
if request.is_json:
return _render_json(form)
return _security.render_template(config_value('SEND_LOGIN_TEMPLATE'),
send_login_form=form,
**_ctx('send_login')) | [
"def",
"send_login",
"(",
")",
":",
"form_class",
"=",
"_security",
".",
"passwordless_login_form",
"if",
"request",
".",
"is_json",
":",
"form",
"=",
"form_class",
"(",
"MultiDict",
"(",
"request",
".",
"get_json",
"(",
")",
")",
")",
"else",
":",
"form",
"=",
"form_class",
"(",
")",
"if",
"form",
".",
"validate_on_submit",
"(",
")",
":",
"send_login_instructions",
"(",
"form",
".",
"user",
")",
"if",
"not",
"request",
".",
"is_json",
":",
"do_flash",
"(",
"*",
"get_message",
"(",
"'LOGIN_EMAIL_SENT'",
",",
"email",
"=",
"form",
".",
"user",
".",
"email",
")",
")",
"if",
"request",
".",
"is_json",
":",
"return",
"_render_json",
"(",
"form",
")",
"return",
"_security",
".",
"render_template",
"(",
"config_value",
"(",
"'SEND_LOGIN_TEMPLATE'",
")",
",",
"send_login_form",
"=",
"form",
",",
"*",
"*",
"_ctx",
"(",
"'send_login'",
")",
")"
] | View function that sends login instructions for passwordless login | [
"View",
"function",
"that",
"sends",
"login",
"instructions",
"for",
"passwordless",
"login"
] | a401fb47018fbbbe0b899ea55afadfd0e3cd847a | https://github.com/mattupstate/flask-security/blob/a401fb47018fbbbe0b899ea55afadfd0e3cd847a/flask_security/views.py#L142-L162 |
227,617 | mattupstate/flask-security | flask_security/views.py | token_login | def token_login(token):
"""View function that handles passwordless login via a token"""
expired, invalid, user = login_token_status(token)
if invalid:
do_flash(*get_message('INVALID_LOGIN_TOKEN'))
if expired:
send_login_instructions(user)
do_flash(*get_message('LOGIN_EXPIRED', email=user.email,
within=_security.login_within))
if invalid or expired:
return redirect(url_for('login'))
login_user(user)
after_this_request(_commit)
do_flash(*get_message('PASSWORDLESS_LOGIN_SUCCESSFUL'))
return redirect(get_post_login_redirect()) | python | def token_login(token):
"""View function that handles passwordless login via a token"""
expired, invalid, user = login_token_status(token)
if invalid:
do_flash(*get_message('INVALID_LOGIN_TOKEN'))
if expired:
send_login_instructions(user)
do_flash(*get_message('LOGIN_EXPIRED', email=user.email,
within=_security.login_within))
if invalid or expired:
return redirect(url_for('login'))
login_user(user)
after_this_request(_commit)
do_flash(*get_message('PASSWORDLESS_LOGIN_SUCCESSFUL'))
return redirect(get_post_login_redirect()) | [
"def",
"token_login",
"(",
"token",
")",
":",
"expired",
",",
"invalid",
",",
"user",
"=",
"login_token_status",
"(",
"token",
")",
"if",
"invalid",
":",
"do_flash",
"(",
"*",
"get_message",
"(",
"'INVALID_LOGIN_TOKEN'",
")",
")",
"if",
"expired",
":",
"send_login_instructions",
"(",
"user",
")",
"do_flash",
"(",
"*",
"get_message",
"(",
"'LOGIN_EXPIRED'",
",",
"email",
"=",
"user",
".",
"email",
",",
"within",
"=",
"_security",
".",
"login_within",
")",
")",
"if",
"invalid",
"or",
"expired",
":",
"return",
"redirect",
"(",
"url_for",
"(",
"'login'",
")",
")",
"login_user",
"(",
"user",
")",
"after_this_request",
"(",
"_commit",
")",
"do_flash",
"(",
"*",
"get_message",
"(",
"'PASSWORDLESS_LOGIN_SUCCESSFUL'",
")",
")",
"return",
"redirect",
"(",
"get_post_login_redirect",
"(",
")",
")"
] | View function that handles passwordless login via a token | [
"View",
"function",
"that",
"handles",
"passwordless",
"login",
"via",
"a",
"token"
] | a401fb47018fbbbe0b899ea55afadfd0e3cd847a | https://github.com/mattupstate/flask-security/blob/a401fb47018fbbbe0b899ea55afadfd0e3cd847a/flask_security/views.py#L166-L184 |
227,618 | mattupstate/flask-security | flask_security/views.py | send_confirmation | def send_confirmation():
"""View function which sends confirmation instructions."""
form_class = _security.send_confirmation_form
if request.is_json:
form = form_class(MultiDict(request.get_json()))
else:
form = form_class()
if form.validate_on_submit():
send_confirmation_instructions(form.user)
if not request.is_json:
do_flash(*get_message('CONFIRMATION_REQUEST',
email=form.user.email))
if request.is_json:
return _render_json(form)
return _security.render_template(
config_value('SEND_CONFIRMATION_TEMPLATE'),
send_confirmation_form=form,
**_ctx('send_confirmation')
) | python | def send_confirmation():
"""View function which sends confirmation instructions."""
form_class = _security.send_confirmation_form
if request.is_json:
form = form_class(MultiDict(request.get_json()))
else:
form = form_class()
if form.validate_on_submit():
send_confirmation_instructions(form.user)
if not request.is_json:
do_flash(*get_message('CONFIRMATION_REQUEST',
email=form.user.email))
if request.is_json:
return _render_json(form)
return _security.render_template(
config_value('SEND_CONFIRMATION_TEMPLATE'),
send_confirmation_form=form,
**_ctx('send_confirmation')
) | [
"def",
"send_confirmation",
"(",
")",
":",
"form_class",
"=",
"_security",
".",
"send_confirmation_form",
"if",
"request",
".",
"is_json",
":",
"form",
"=",
"form_class",
"(",
"MultiDict",
"(",
"request",
".",
"get_json",
"(",
")",
")",
")",
"else",
":",
"form",
"=",
"form_class",
"(",
")",
"if",
"form",
".",
"validate_on_submit",
"(",
")",
":",
"send_confirmation_instructions",
"(",
"form",
".",
"user",
")",
"if",
"not",
"request",
".",
"is_json",
":",
"do_flash",
"(",
"*",
"get_message",
"(",
"'CONFIRMATION_REQUEST'",
",",
"email",
"=",
"form",
".",
"user",
".",
"email",
")",
")",
"if",
"request",
".",
"is_json",
":",
"return",
"_render_json",
"(",
"form",
")",
"return",
"_security",
".",
"render_template",
"(",
"config_value",
"(",
"'SEND_CONFIRMATION_TEMPLATE'",
")",
",",
"send_confirmation_form",
"=",
"form",
",",
"*",
"*",
"_ctx",
"(",
"'send_confirmation'",
")",
")"
] | View function which sends confirmation instructions. | [
"View",
"function",
"which",
"sends",
"confirmation",
"instructions",
"."
] | a401fb47018fbbbe0b899ea55afadfd0e3cd847a | https://github.com/mattupstate/flask-security/blob/a401fb47018fbbbe0b899ea55afadfd0e3cd847a/flask_security/views.py#L187-L210 |
227,619 | mattupstate/flask-security | flask_security/views.py | confirm_email | def confirm_email(token):
"""View function which handles a email confirmation request."""
expired, invalid, user = confirm_email_token_status(token)
if not user or invalid:
invalid = True
do_flash(*get_message('INVALID_CONFIRMATION_TOKEN'))
already_confirmed = user is not None and user.confirmed_at is not None
if expired and not already_confirmed:
send_confirmation_instructions(user)
do_flash(*get_message('CONFIRMATION_EXPIRED', email=user.email,
within=_security.confirm_email_within))
if invalid or (expired and not already_confirmed):
return redirect(get_url(_security.confirm_error_view) or
url_for('send_confirmation'))
if user != current_user:
logout_user()
if confirm_user(user):
after_this_request(_commit)
msg = 'EMAIL_CONFIRMED'
else:
msg = 'ALREADY_CONFIRMED'
do_flash(*get_message(msg))
return redirect(get_url(_security.post_confirm_view) or
get_url(_security.login_url)) | python | def confirm_email(token):
"""View function which handles a email confirmation request."""
expired, invalid, user = confirm_email_token_status(token)
if not user or invalid:
invalid = True
do_flash(*get_message('INVALID_CONFIRMATION_TOKEN'))
already_confirmed = user is not None and user.confirmed_at is not None
if expired and not already_confirmed:
send_confirmation_instructions(user)
do_flash(*get_message('CONFIRMATION_EXPIRED', email=user.email,
within=_security.confirm_email_within))
if invalid or (expired and not already_confirmed):
return redirect(get_url(_security.confirm_error_view) or
url_for('send_confirmation'))
if user != current_user:
logout_user()
if confirm_user(user):
after_this_request(_commit)
msg = 'EMAIL_CONFIRMED'
else:
msg = 'ALREADY_CONFIRMED'
do_flash(*get_message(msg))
return redirect(get_url(_security.post_confirm_view) or
get_url(_security.login_url)) | [
"def",
"confirm_email",
"(",
"token",
")",
":",
"expired",
",",
"invalid",
",",
"user",
"=",
"confirm_email_token_status",
"(",
"token",
")",
"if",
"not",
"user",
"or",
"invalid",
":",
"invalid",
"=",
"True",
"do_flash",
"(",
"*",
"get_message",
"(",
"'INVALID_CONFIRMATION_TOKEN'",
")",
")",
"already_confirmed",
"=",
"user",
"is",
"not",
"None",
"and",
"user",
".",
"confirmed_at",
"is",
"not",
"None",
"if",
"expired",
"and",
"not",
"already_confirmed",
":",
"send_confirmation_instructions",
"(",
"user",
")",
"do_flash",
"(",
"*",
"get_message",
"(",
"'CONFIRMATION_EXPIRED'",
",",
"email",
"=",
"user",
".",
"email",
",",
"within",
"=",
"_security",
".",
"confirm_email_within",
")",
")",
"if",
"invalid",
"or",
"(",
"expired",
"and",
"not",
"already_confirmed",
")",
":",
"return",
"redirect",
"(",
"get_url",
"(",
"_security",
".",
"confirm_error_view",
")",
"or",
"url_for",
"(",
"'send_confirmation'",
")",
")",
"if",
"user",
"!=",
"current_user",
":",
"logout_user",
"(",
")",
"if",
"confirm_user",
"(",
"user",
")",
":",
"after_this_request",
"(",
"_commit",
")",
"msg",
"=",
"'EMAIL_CONFIRMED'",
"else",
":",
"msg",
"=",
"'ALREADY_CONFIRMED'",
"do_flash",
"(",
"*",
"get_message",
"(",
"msg",
")",
")",
"return",
"redirect",
"(",
"get_url",
"(",
"_security",
".",
"post_confirm_view",
")",
"or",
"get_url",
"(",
"_security",
".",
"login_url",
")",
")"
] | View function which handles a email confirmation request. | [
"View",
"function",
"which",
"handles",
"a",
"email",
"confirmation",
"request",
"."
] | a401fb47018fbbbe0b899ea55afadfd0e3cd847a | https://github.com/mattupstate/flask-security/blob/a401fb47018fbbbe0b899ea55afadfd0e3cd847a/flask_security/views.py#L213-L244 |
227,620 | mattupstate/flask-security | flask_security/views.py | forgot_password | def forgot_password():
"""View function that handles a forgotten password request."""
form_class = _security.forgot_password_form
if request.is_json:
form = form_class(MultiDict(request.get_json()))
else:
form = form_class()
if form.validate_on_submit():
send_reset_password_instructions(form.user)
if not request.is_json:
do_flash(*get_message('PASSWORD_RESET_REQUEST',
email=form.user.email))
if request.is_json:
return _render_json(form, include_user=False)
return _security.render_template(config_value('FORGOT_PASSWORD_TEMPLATE'),
forgot_password_form=form,
**_ctx('forgot_password')) | python | def forgot_password():
"""View function that handles a forgotten password request."""
form_class = _security.forgot_password_form
if request.is_json:
form = form_class(MultiDict(request.get_json()))
else:
form = form_class()
if form.validate_on_submit():
send_reset_password_instructions(form.user)
if not request.is_json:
do_flash(*get_message('PASSWORD_RESET_REQUEST',
email=form.user.email))
if request.is_json:
return _render_json(form, include_user=False)
return _security.render_template(config_value('FORGOT_PASSWORD_TEMPLATE'),
forgot_password_form=form,
**_ctx('forgot_password')) | [
"def",
"forgot_password",
"(",
")",
":",
"form_class",
"=",
"_security",
".",
"forgot_password_form",
"if",
"request",
".",
"is_json",
":",
"form",
"=",
"form_class",
"(",
"MultiDict",
"(",
"request",
".",
"get_json",
"(",
")",
")",
")",
"else",
":",
"form",
"=",
"form_class",
"(",
")",
"if",
"form",
".",
"validate_on_submit",
"(",
")",
":",
"send_reset_password_instructions",
"(",
"form",
".",
"user",
")",
"if",
"not",
"request",
".",
"is_json",
":",
"do_flash",
"(",
"*",
"get_message",
"(",
"'PASSWORD_RESET_REQUEST'",
",",
"email",
"=",
"form",
".",
"user",
".",
"email",
")",
")",
"if",
"request",
".",
"is_json",
":",
"return",
"_render_json",
"(",
"form",
",",
"include_user",
"=",
"False",
")",
"return",
"_security",
".",
"render_template",
"(",
"config_value",
"(",
"'FORGOT_PASSWORD_TEMPLATE'",
")",
",",
"forgot_password_form",
"=",
"form",
",",
"*",
"*",
"_ctx",
"(",
"'forgot_password'",
")",
")"
] | View function that handles a forgotten password request. | [
"View",
"function",
"that",
"handles",
"a",
"forgotten",
"password",
"request",
"."
] | a401fb47018fbbbe0b899ea55afadfd0e3cd847a | https://github.com/mattupstate/flask-security/blob/a401fb47018fbbbe0b899ea55afadfd0e3cd847a/flask_security/views.py#L248-L269 |
227,621 | mattupstate/flask-security | flask_security/views.py | reset_password | def reset_password(token):
"""View function that handles a reset password request."""
expired, invalid, user = reset_password_token_status(token)
if not user or invalid:
invalid = True
do_flash(*get_message('INVALID_RESET_PASSWORD_TOKEN'))
if expired:
send_reset_password_instructions(user)
do_flash(*get_message('PASSWORD_RESET_EXPIRED', email=user.email,
within=_security.reset_password_within))
if invalid or expired:
return redirect(url_for('forgot_password'))
form = _security.reset_password_form()
if form.validate_on_submit():
after_this_request(_commit)
update_password(user, form.password.data)
do_flash(*get_message('PASSWORD_RESET'))
return redirect(get_url(_security.post_reset_view) or
get_url(_security.login_url))
return _security.render_template(
config_value('RESET_PASSWORD_TEMPLATE'),
reset_password_form=form,
reset_password_token=token,
**_ctx('reset_password')
) | python | def reset_password(token):
"""View function that handles a reset password request."""
expired, invalid, user = reset_password_token_status(token)
if not user or invalid:
invalid = True
do_flash(*get_message('INVALID_RESET_PASSWORD_TOKEN'))
if expired:
send_reset_password_instructions(user)
do_flash(*get_message('PASSWORD_RESET_EXPIRED', email=user.email,
within=_security.reset_password_within))
if invalid or expired:
return redirect(url_for('forgot_password'))
form = _security.reset_password_form()
if form.validate_on_submit():
after_this_request(_commit)
update_password(user, form.password.data)
do_flash(*get_message('PASSWORD_RESET'))
return redirect(get_url(_security.post_reset_view) or
get_url(_security.login_url))
return _security.render_template(
config_value('RESET_PASSWORD_TEMPLATE'),
reset_password_form=form,
reset_password_token=token,
**_ctx('reset_password')
) | [
"def",
"reset_password",
"(",
"token",
")",
":",
"expired",
",",
"invalid",
",",
"user",
"=",
"reset_password_token_status",
"(",
"token",
")",
"if",
"not",
"user",
"or",
"invalid",
":",
"invalid",
"=",
"True",
"do_flash",
"(",
"*",
"get_message",
"(",
"'INVALID_RESET_PASSWORD_TOKEN'",
")",
")",
"if",
"expired",
":",
"send_reset_password_instructions",
"(",
"user",
")",
"do_flash",
"(",
"*",
"get_message",
"(",
"'PASSWORD_RESET_EXPIRED'",
",",
"email",
"=",
"user",
".",
"email",
",",
"within",
"=",
"_security",
".",
"reset_password_within",
")",
")",
"if",
"invalid",
"or",
"expired",
":",
"return",
"redirect",
"(",
"url_for",
"(",
"'forgot_password'",
")",
")",
"form",
"=",
"_security",
".",
"reset_password_form",
"(",
")",
"if",
"form",
".",
"validate_on_submit",
"(",
")",
":",
"after_this_request",
"(",
"_commit",
")",
"update_password",
"(",
"user",
",",
"form",
".",
"password",
".",
"data",
")",
"do_flash",
"(",
"*",
"get_message",
"(",
"'PASSWORD_RESET'",
")",
")",
"return",
"redirect",
"(",
"get_url",
"(",
"_security",
".",
"post_reset_view",
")",
"or",
"get_url",
"(",
"_security",
".",
"login_url",
")",
")",
"return",
"_security",
".",
"render_template",
"(",
"config_value",
"(",
"'RESET_PASSWORD_TEMPLATE'",
")",
",",
"reset_password_form",
"=",
"form",
",",
"reset_password_token",
"=",
"token",
",",
"*",
"*",
"_ctx",
"(",
"'reset_password'",
")",
")"
] | View function that handles a reset password request. | [
"View",
"function",
"that",
"handles",
"a",
"reset",
"password",
"request",
"."
] | a401fb47018fbbbe0b899ea55afadfd0e3cd847a | https://github.com/mattupstate/flask-security/blob/a401fb47018fbbbe0b899ea55afadfd0e3cd847a/flask_security/views.py#L273-L303 |
227,622 | mattupstate/flask-security | flask_security/views.py | change_password | def change_password():
"""View function which handles a change password request."""
form_class = _security.change_password_form
if request.is_json:
form = form_class(MultiDict(request.get_json()))
else:
form = form_class()
if form.validate_on_submit():
after_this_request(_commit)
change_user_password(current_user._get_current_object(),
form.new_password.data)
if not request.is_json:
do_flash(*get_message('PASSWORD_CHANGE'))
return redirect(get_url(_security.post_change_view) or
get_url(_security.post_login_view))
if request.is_json:
form.user = current_user
return _render_json(form)
return _security.render_template(
config_value('CHANGE_PASSWORD_TEMPLATE'),
change_password_form=form,
**_ctx('change_password')
) | python | def change_password():
"""View function which handles a change password request."""
form_class = _security.change_password_form
if request.is_json:
form = form_class(MultiDict(request.get_json()))
else:
form = form_class()
if form.validate_on_submit():
after_this_request(_commit)
change_user_password(current_user._get_current_object(),
form.new_password.data)
if not request.is_json:
do_flash(*get_message('PASSWORD_CHANGE'))
return redirect(get_url(_security.post_change_view) or
get_url(_security.post_login_view))
if request.is_json:
form.user = current_user
return _render_json(form)
return _security.render_template(
config_value('CHANGE_PASSWORD_TEMPLATE'),
change_password_form=form,
**_ctx('change_password')
) | [
"def",
"change_password",
"(",
")",
":",
"form_class",
"=",
"_security",
".",
"change_password_form",
"if",
"request",
".",
"is_json",
":",
"form",
"=",
"form_class",
"(",
"MultiDict",
"(",
"request",
".",
"get_json",
"(",
")",
")",
")",
"else",
":",
"form",
"=",
"form_class",
"(",
")",
"if",
"form",
".",
"validate_on_submit",
"(",
")",
":",
"after_this_request",
"(",
"_commit",
")",
"change_user_password",
"(",
"current_user",
".",
"_get_current_object",
"(",
")",
",",
"form",
".",
"new_password",
".",
"data",
")",
"if",
"not",
"request",
".",
"is_json",
":",
"do_flash",
"(",
"*",
"get_message",
"(",
"'PASSWORD_CHANGE'",
")",
")",
"return",
"redirect",
"(",
"get_url",
"(",
"_security",
".",
"post_change_view",
")",
"or",
"get_url",
"(",
"_security",
".",
"post_login_view",
")",
")",
"if",
"request",
".",
"is_json",
":",
"form",
".",
"user",
"=",
"current_user",
"return",
"_render_json",
"(",
"form",
")",
"return",
"_security",
".",
"render_template",
"(",
"config_value",
"(",
"'CHANGE_PASSWORD_TEMPLATE'",
")",
",",
"change_password_form",
"=",
"form",
",",
"*",
"*",
"_ctx",
"(",
"'change_password'",
")",
")"
] | View function which handles a change password request. | [
"View",
"function",
"which",
"handles",
"a",
"change",
"password",
"request",
"."
] | a401fb47018fbbbe0b899ea55afadfd0e3cd847a | https://github.com/mattupstate/flask-security/blob/a401fb47018fbbbe0b899ea55afadfd0e3cd847a/flask_security/views.py#L307-L334 |
227,623 | mattupstate/flask-security | flask_security/views.py | create_blueprint | def create_blueprint(state, import_name):
"""Creates the security extension blueprint"""
bp = Blueprint(state.blueprint_name, import_name,
url_prefix=state.url_prefix,
subdomain=state.subdomain,
template_folder='templates')
bp.route(state.logout_url, endpoint='logout')(logout)
if state.passwordless:
bp.route(state.login_url,
methods=['GET', 'POST'],
endpoint='login')(send_login)
bp.route(state.login_url + slash_url_suffix(state.login_url,
'<token>'),
endpoint='token_login')(token_login)
else:
bp.route(state.login_url,
methods=['GET', 'POST'],
endpoint='login')(login)
if state.registerable:
bp.route(state.register_url,
methods=['GET', 'POST'],
endpoint='register')(register)
if state.recoverable:
bp.route(state.reset_url,
methods=['GET', 'POST'],
endpoint='forgot_password')(forgot_password)
bp.route(state.reset_url + slash_url_suffix(state.reset_url,
'<token>'),
methods=['GET', 'POST'],
endpoint='reset_password')(reset_password)
if state.changeable:
bp.route(state.change_url,
methods=['GET', 'POST'],
endpoint='change_password')(change_password)
if state.confirmable:
bp.route(state.confirm_url,
methods=['GET', 'POST'],
endpoint='send_confirmation')(send_confirmation)
bp.route(state.confirm_url + slash_url_suffix(state.confirm_url,
'<token>'),
methods=['GET', 'POST'],
endpoint='confirm_email')(confirm_email)
return bp | python | def create_blueprint(state, import_name):
"""Creates the security extension blueprint"""
bp = Blueprint(state.blueprint_name, import_name,
url_prefix=state.url_prefix,
subdomain=state.subdomain,
template_folder='templates')
bp.route(state.logout_url, endpoint='logout')(logout)
if state.passwordless:
bp.route(state.login_url,
methods=['GET', 'POST'],
endpoint='login')(send_login)
bp.route(state.login_url + slash_url_suffix(state.login_url,
'<token>'),
endpoint='token_login')(token_login)
else:
bp.route(state.login_url,
methods=['GET', 'POST'],
endpoint='login')(login)
if state.registerable:
bp.route(state.register_url,
methods=['GET', 'POST'],
endpoint='register')(register)
if state.recoverable:
bp.route(state.reset_url,
methods=['GET', 'POST'],
endpoint='forgot_password')(forgot_password)
bp.route(state.reset_url + slash_url_suffix(state.reset_url,
'<token>'),
methods=['GET', 'POST'],
endpoint='reset_password')(reset_password)
if state.changeable:
bp.route(state.change_url,
methods=['GET', 'POST'],
endpoint='change_password')(change_password)
if state.confirmable:
bp.route(state.confirm_url,
methods=['GET', 'POST'],
endpoint='send_confirmation')(send_confirmation)
bp.route(state.confirm_url + slash_url_suffix(state.confirm_url,
'<token>'),
methods=['GET', 'POST'],
endpoint='confirm_email')(confirm_email)
return bp | [
"def",
"create_blueprint",
"(",
"state",
",",
"import_name",
")",
":",
"bp",
"=",
"Blueprint",
"(",
"state",
".",
"blueprint_name",
",",
"import_name",
",",
"url_prefix",
"=",
"state",
".",
"url_prefix",
",",
"subdomain",
"=",
"state",
".",
"subdomain",
",",
"template_folder",
"=",
"'templates'",
")",
"bp",
".",
"route",
"(",
"state",
".",
"logout_url",
",",
"endpoint",
"=",
"'logout'",
")",
"(",
"logout",
")",
"if",
"state",
".",
"passwordless",
":",
"bp",
".",
"route",
"(",
"state",
".",
"login_url",
",",
"methods",
"=",
"[",
"'GET'",
",",
"'POST'",
"]",
",",
"endpoint",
"=",
"'login'",
")",
"(",
"send_login",
")",
"bp",
".",
"route",
"(",
"state",
".",
"login_url",
"+",
"slash_url_suffix",
"(",
"state",
".",
"login_url",
",",
"'<token>'",
")",
",",
"endpoint",
"=",
"'token_login'",
")",
"(",
"token_login",
")",
"else",
":",
"bp",
".",
"route",
"(",
"state",
".",
"login_url",
",",
"methods",
"=",
"[",
"'GET'",
",",
"'POST'",
"]",
",",
"endpoint",
"=",
"'login'",
")",
"(",
"login",
")",
"if",
"state",
".",
"registerable",
":",
"bp",
".",
"route",
"(",
"state",
".",
"register_url",
",",
"methods",
"=",
"[",
"'GET'",
",",
"'POST'",
"]",
",",
"endpoint",
"=",
"'register'",
")",
"(",
"register",
")",
"if",
"state",
".",
"recoverable",
":",
"bp",
".",
"route",
"(",
"state",
".",
"reset_url",
",",
"methods",
"=",
"[",
"'GET'",
",",
"'POST'",
"]",
",",
"endpoint",
"=",
"'forgot_password'",
")",
"(",
"forgot_password",
")",
"bp",
".",
"route",
"(",
"state",
".",
"reset_url",
"+",
"slash_url_suffix",
"(",
"state",
".",
"reset_url",
",",
"'<token>'",
")",
",",
"methods",
"=",
"[",
"'GET'",
",",
"'POST'",
"]",
",",
"endpoint",
"=",
"'reset_password'",
")",
"(",
"reset_password",
")",
"if",
"state",
".",
"changeable",
":",
"bp",
".",
"route",
"(",
"state",
".",
"change_url",
",",
"methods",
"=",
"[",
"'GET'",
",",
"'POST'",
"]",
",",
"endpoint",
"=",
"'change_password'",
")",
"(",
"change_password",
")",
"if",
"state",
".",
"confirmable",
":",
"bp",
".",
"route",
"(",
"state",
".",
"confirm_url",
",",
"methods",
"=",
"[",
"'GET'",
",",
"'POST'",
"]",
",",
"endpoint",
"=",
"'send_confirmation'",
")",
"(",
"send_confirmation",
")",
"bp",
".",
"route",
"(",
"state",
".",
"confirm_url",
"+",
"slash_url_suffix",
"(",
"state",
".",
"confirm_url",
",",
"'<token>'",
")",
",",
"methods",
"=",
"[",
"'GET'",
",",
"'POST'",
"]",
",",
"endpoint",
"=",
"'confirm_email'",
")",
"(",
"confirm_email",
")",
"return",
"bp"
] | Creates the security extension blueprint | [
"Creates",
"the",
"security",
"extension",
"blueprint"
] | a401fb47018fbbbe0b899ea55afadfd0e3cd847a | https://github.com/mattupstate/flask-security/blob/a401fb47018fbbbe0b899ea55afadfd0e3cd847a/flask_security/views.py#L337-L387 |
227,624 | mattupstate/flask-security | flask_security/utils.py | login_user | def login_user(user, remember=None):
"""Perform the login routine.
If SECURITY_TRACKABLE is used, make sure you commit changes after this
request (i.e. ``app.security.datastore.commit()``).
:param user: The user to login
:param remember: Flag specifying if the remember cookie should be set.
Defaults to ``False``
"""
if remember is None:
remember = config_value('DEFAULT_REMEMBER_ME')
if not _login_user(user, remember): # pragma: no cover
return False
if _security.trackable:
remote_addr = request.remote_addr or None # make sure it is None
old_current_login, new_current_login = (
user.current_login_at, _security.datetime_factory()
)
old_current_ip, new_current_ip = user.current_login_ip, remote_addr
user.last_login_at = old_current_login or new_current_login
user.current_login_at = new_current_login
user.last_login_ip = old_current_ip
user.current_login_ip = new_current_ip
user.login_count = user.login_count + 1 if user.login_count else 1
_datastore.put(user)
identity_changed.send(current_app._get_current_object(),
identity=Identity(user.id))
return True | python | def login_user(user, remember=None):
"""Perform the login routine.
If SECURITY_TRACKABLE is used, make sure you commit changes after this
request (i.e. ``app.security.datastore.commit()``).
:param user: The user to login
:param remember: Flag specifying if the remember cookie should be set.
Defaults to ``False``
"""
if remember is None:
remember = config_value('DEFAULT_REMEMBER_ME')
if not _login_user(user, remember): # pragma: no cover
return False
if _security.trackable:
remote_addr = request.remote_addr or None # make sure it is None
old_current_login, new_current_login = (
user.current_login_at, _security.datetime_factory()
)
old_current_ip, new_current_ip = user.current_login_ip, remote_addr
user.last_login_at = old_current_login or new_current_login
user.current_login_at = new_current_login
user.last_login_ip = old_current_ip
user.current_login_ip = new_current_ip
user.login_count = user.login_count + 1 if user.login_count else 1
_datastore.put(user)
identity_changed.send(current_app._get_current_object(),
identity=Identity(user.id))
return True | [
"def",
"login_user",
"(",
"user",
",",
"remember",
"=",
"None",
")",
":",
"if",
"remember",
"is",
"None",
":",
"remember",
"=",
"config_value",
"(",
"'DEFAULT_REMEMBER_ME'",
")",
"if",
"not",
"_login_user",
"(",
"user",
",",
"remember",
")",
":",
"# pragma: no cover",
"return",
"False",
"if",
"_security",
".",
"trackable",
":",
"remote_addr",
"=",
"request",
".",
"remote_addr",
"or",
"None",
"# make sure it is None",
"old_current_login",
",",
"new_current_login",
"=",
"(",
"user",
".",
"current_login_at",
",",
"_security",
".",
"datetime_factory",
"(",
")",
")",
"old_current_ip",
",",
"new_current_ip",
"=",
"user",
".",
"current_login_ip",
",",
"remote_addr",
"user",
".",
"last_login_at",
"=",
"old_current_login",
"or",
"new_current_login",
"user",
".",
"current_login_at",
"=",
"new_current_login",
"user",
".",
"last_login_ip",
"=",
"old_current_ip",
"user",
".",
"current_login_ip",
"=",
"new_current_ip",
"user",
".",
"login_count",
"=",
"user",
".",
"login_count",
"+",
"1",
"if",
"user",
".",
"login_count",
"else",
"1",
"_datastore",
".",
"put",
"(",
"user",
")",
"identity_changed",
".",
"send",
"(",
"current_app",
".",
"_get_current_object",
"(",
")",
",",
"identity",
"=",
"Identity",
"(",
"user",
".",
"id",
")",
")",
"return",
"True"
] | Perform the login routine.
If SECURITY_TRACKABLE is used, make sure you commit changes after this
request (i.e. ``app.security.datastore.commit()``).
:param user: The user to login
:param remember: Flag specifying if the remember cookie should be set.
Defaults to ``False`` | [
"Perform",
"the",
"login",
"routine",
"."
] | a401fb47018fbbbe0b899ea55afadfd0e3cd847a | https://github.com/mattupstate/flask-security/blob/a401fb47018fbbbe0b899ea55afadfd0e3cd847a/flask_security/utils.py#L63-L98 |
227,625 | mattupstate/flask-security | flask_security/utils.py | logout_user | def logout_user():
"""Logs out the current.
This will also clean up the remember me cookie if it exists.
"""
for key in ('identity.name', 'identity.auth_type'):
session.pop(key, None)
identity_changed.send(current_app._get_current_object(),
identity=AnonymousIdentity())
_logout_user() | python | def logout_user():
"""Logs out the current.
This will also clean up the remember me cookie if it exists.
"""
for key in ('identity.name', 'identity.auth_type'):
session.pop(key, None)
identity_changed.send(current_app._get_current_object(),
identity=AnonymousIdentity())
_logout_user() | [
"def",
"logout_user",
"(",
")",
":",
"for",
"key",
"in",
"(",
"'identity.name'",
",",
"'identity.auth_type'",
")",
":",
"session",
".",
"pop",
"(",
"key",
",",
"None",
")",
"identity_changed",
".",
"send",
"(",
"current_app",
".",
"_get_current_object",
"(",
")",
",",
"identity",
"=",
"AnonymousIdentity",
"(",
")",
")",
"_logout_user",
"(",
")"
] | Logs out the current.
This will also clean up the remember me cookie if it exists. | [
"Logs",
"out",
"the",
"current",
"."
] | a401fb47018fbbbe0b899ea55afadfd0e3cd847a | https://github.com/mattupstate/flask-security/blob/a401fb47018fbbbe0b899ea55afadfd0e3cd847a/flask_security/utils.py#L101-L111 |
227,626 | mattupstate/flask-security | flask_security/utils.py | verify_password | def verify_password(password, password_hash):
"""Returns ``True`` if the password matches the supplied hash.
:param password: A plaintext password to verify
:param password_hash: The expected hash value of the password
(usually from your database)
"""
if use_double_hash(password_hash):
password = get_hmac(password)
return _pwd_context.verify(password, password_hash) | python | def verify_password(password, password_hash):
"""Returns ``True`` if the password matches the supplied hash.
:param password: A plaintext password to verify
:param password_hash: The expected hash value of the password
(usually from your database)
"""
if use_double_hash(password_hash):
password = get_hmac(password)
return _pwd_context.verify(password, password_hash) | [
"def",
"verify_password",
"(",
"password",
",",
"password_hash",
")",
":",
"if",
"use_double_hash",
"(",
"password_hash",
")",
":",
"password",
"=",
"get_hmac",
"(",
"password",
")",
"return",
"_pwd_context",
".",
"verify",
"(",
"password",
",",
"password_hash",
")"
] | Returns ``True`` if the password matches the supplied hash.
:param password: A plaintext password to verify
:param password_hash: The expected hash value of the password
(usually from your database) | [
"Returns",
"True",
"if",
"the",
"password",
"matches",
"the",
"supplied",
"hash",
"."
] | a401fb47018fbbbe0b899ea55afadfd0e3cd847a | https://github.com/mattupstate/flask-security/blob/a401fb47018fbbbe0b899ea55afadfd0e3cd847a/flask_security/utils.py#L132-L142 |
227,627 | mattupstate/flask-security | flask_security/utils.py | find_redirect | def find_redirect(key):
"""Returns the URL to redirect to after a user logs in successfully.
:param key: The session or application configuration key to search for
"""
rv = (get_url(session.pop(key.lower(), None)) or
get_url(current_app.config[key.upper()] or None) or '/')
return rv | python | def find_redirect(key):
"""Returns the URL to redirect to after a user logs in successfully.
:param key: The session or application configuration key to search for
"""
rv = (get_url(session.pop(key.lower(), None)) or
get_url(current_app.config[key.upper()] or None) or '/')
return rv | [
"def",
"find_redirect",
"(",
"key",
")",
":",
"rv",
"=",
"(",
"get_url",
"(",
"session",
".",
"pop",
"(",
"key",
".",
"lower",
"(",
")",
",",
"None",
")",
")",
"or",
"get_url",
"(",
"current_app",
".",
"config",
"[",
"key",
".",
"upper",
"(",
")",
"]",
"or",
"None",
")",
"or",
"'/'",
")",
"return",
"rv"
] | Returns the URL to redirect to after a user logs in successfully.
:param key: The session or application configuration key to search for | [
"Returns",
"the",
"URL",
"to",
"redirect",
"to",
"after",
"a",
"user",
"logs",
"in",
"successfully",
"."
] | a401fb47018fbbbe0b899ea55afadfd0e3cd847a | https://github.com/mattupstate/flask-security/blob/a401fb47018fbbbe0b899ea55afadfd0e3cd847a/flask_security/utils.py#L306-L313 |
227,628 | mattupstate/flask-security | flask_security/utils.py | send_mail | def send_mail(subject, recipient, template, **context):
"""Send an email via the Flask-Mail extension.
:param subject: Email subject
:param recipient: Email recipient
:param template: The name of the email template
:param context: The context to render the template with
"""
context.setdefault('security', _security)
context.update(_security._run_ctx_processor('mail'))
sender = _security.email_sender
if isinstance(sender, LocalProxy):
sender = sender._get_current_object()
msg = Message(subject,
sender=sender,
recipients=[recipient])
ctx = ('security/email', template)
if config_value('EMAIL_PLAINTEXT'):
msg.body = _security.render_template('%s/%s.txt' % ctx, **context)
if config_value('EMAIL_HTML'):
msg.html = _security.render_template('%s/%s.html' % ctx, **context)
if _security._send_mail_task:
_security._send_mail_task(msg)
return
mail = current_app.extensions.get('mail')
mail.send(msg) | python | def send_mail(subject, recipient, template, **context):
"""Send an email via the Flask-Mail extension.
:param subject: Email subject
:param recipient: Email recipient
:param template: The name of the email template
:param context: The context to render the template with
"""
context.setdefault('security', _security)
context.update(_security._run_ctx_processor('mail'))
sender = _security.email_sender
if isinstance(sender, LocalProxy):
sender = sender._get_current_object()
msg = Message(subject,
sender=sender,
recipients=[recipient])
ctx = ('security/email', template)
if config_value('EMAIL_PLAINTEXT'):
msg.body = _security.render_template('%s/%s.txt' % ctx, **context)
if config_value('EMAIL_HTML'):
msg.html = _security.render_template('%s/%s.html' % ctx, **context)
if _security._send_mail_task:
_security._send_mail_task(msg)
return
mail = current_app.extensions.get('mail')
mail.send(msg) | [
"def",
"send_mail",
"(",
"subject",
",",
"recipient",
",",
"template",
",",
"*",
"*",
"context",
")",
":",
"context",
".",
"setdefault",
"(",
"'security'",
",",
"_security",
")",
"context",
".",
"update",
"(",
"_security",
".",
"_run_ctx_processor",
"(",
"'mail'",
")",
")",
"sender",
"=",
"_security",
".",
"email_sender",
"if",
"isinstance",
"(",
"sender",
",",
"LocalProxy",
")",
":",
"sender",
"=",
"sender",
".",
"_get_current_object",
"(",
")",
"msg",
"=",
"Message",
"(",
"subject",
",",
"sender",
"=",
"sender",
",",
"recipients",
"=",
"[",
"recipient",
"]",
")",
"ctx",
"=",
"(",
"'security/email'",
",",
"template",
")",
"if",
"config_value",
"(",
"'EMAIL_PLAINTEXT'",
")",
":",
"msg",
".",
"body",
"=",
"_security",
".",
"render_template",
"(",
"'%s/%s.txt'",
"%",
"ctx",
",",
"*",
"*",
"context",
")",
"if",
"config_value",
"(",
"'EMAIL_HTML'",
")",
":",
"msg",
".",
"html",
"=",
"_security",
".",
"render_template",
"(",
"'%s/%s.html'",
"%",
"ctx",
",",
"*",
"*",
"context",
")",
"if",
"_security",
".",
"_send_mail_task",
":",
"_security",
".",
"_send_mail_task",
"(",
"msg",
")",
"return",
"mail",
"=",
"current_app",
".",
"extensions",
".",
"get",
"(",
"'mail'",
")",
"mail",
".",
"send",
"(",
"msg",
")"
] | Send an email via the Flask-Mail extension.
:param subject: Email subject
:param recipient: Email recipient
:param template: The name of the email template
:param context: The context to render the template with | [
"Send",
"an",
"email",
"via",
"the",
"Flask",
"-",
"Mail",
"extension",
"."
] | a401fb47018fbbbe0b899ea55afadfd0e3cd847a | https://github.com/mattupstate/flask-security/blob/a401fb47018fbbbe0b899ea55afadfd0e3cd847a/flask_security/utils.py#L373-L404 |
227,629 | mattupstate/flask-security | flask_security/utils.py | capture_registrations | def capture_registrations():
"""Testing utility for capturing registrations.
:param confirmation_sent_at: An optional datetime object to set the
user's `confirmation_sent_at` to
"""
registrations = []
def _on(app, **data):
registrations.append(data)
user_registered.connect(_on)
try:
yield registrations
finally:
user_registered.disconnect(_on) | python | def capture_registrations():
"""Testing utility for capturing registrations.
:param confirmation_sent_at: An optional datetime object to set the
user's `confirmation_sent_at` to
"""
registrations = []
def _on(app, **data):
registrations.append(data)
user_registered.connect(_on)
try:
yield registrations
finally:
user_registered.disconnect(_on) | [
"def",
"capture_registrations",
"(",
")",
":",
"registrations",
"=",
"[",
"]",
"def",
"_on",
"(",
"app",
",",
"*",
"*",
"data",
")",
":",
"registrations",
".",
"append",
"(",
"data",
")",
"user_registered",
".",
"connect",
"(",
"_on",
")",
"try",
":",
"yield",
"registrations",
"finally",
":",
"user_registered",
".",
"disconnect",
"(",
"_on",
")"
] | Testing utility for capturing registrations.
:param confirmation_sent_at: An optional datetime object to set the
user's `confirmation_sent_at` to | [
"Testing",
"utility",
"for",
"capturing",
"registrations",
"."
] | a401fb47018fbbbe0b899ea55afadfd0e3cd847a | https://github.com/mattupstate/flask-security/blob/a401fb47018fbbbe0b899ea55afadfd0e3cd847a/flask_security/utils.py#L481-L497 |
227,630 | mattupstate/flask-security | flask_security/utils.py | capture_reset_password_requests | def capture_reset_password_requests(reset_password_sent_at=None):
"""Testing utility for capturing password reset requests.
:param reset_password_sent_at: An optional datetime object to set the
user's `reset_password_sent_at` to
"""
reset_requests = []
def _on(app, **data):
reset_requests.append(data)
reset_password_instructions_sent.connect(_on)
try:
yield reset_requests
finally:
reset_password_instructions_sent.disconnect(_on) | python | def capture_reset_password_requests(reset_password_sent_at=None):
"""Testing utility for capturing password reset requests.
:param reset_password_sent_at: An optional datetime object to set the
user's `reset_password_sent_at` to
"""
reset_requests = []
def _on(app, **data):
reset_requests.append(data)
reset_password_instructions_sent.connect(_on)
try:
yield reset_requests
finally:
reset_password_instructions_sent.disconnect(_on) | [
"def",
"capture_reset_password_requests",
"(",
"reset_password_sent_at",
"=",
"None",
")",
":",
"reset_requests",
"=",
"[",
"]",
"def",
"_on",
"(",
"app",
",",
"*",
"*",
"data",
")",
":",
"reset_requests",
".",
"append",
"(",
"data",
")",
"reset_password_instructions_sent",
".",
"connect",
"(",
"_on",
")",
"try",
":",
"yield",
"reset_requests",
"finally",
":",
"reset_password_instructions_sent",
".",
"disconnect",
"(",
"_on",
")"
] | Testing utility for capturing password reset requests.
:param reset_password_sent_at: An optional datetime object to set the
user's `reset_password_sent_at` to | [
"Testing",
"utility",
"for",
"capturing",
"password",
"reset",
"requests",
"."
] | a401fb47018fbbbe0b899ea55afadfd0e3cd847a | https://github.com/mattupstate/flask-security/blob/a401fb47018fbbbe0b899ea55afadfd0e3cd847a/flask_security/utils.py#L501-L517 |
227,631 | mattupstate/flask-security | flask_security/passwordless.py | send_login_instructions | def send_login_instructions(user):
"""Sends the login instructions email for the specified user.
:param user: The user to send the instructions to
:param token: The login token
"""
token = generate_login_token(user)
login_link = url_for_security('token_login', token=token, _external=True)
_security.send_mail(config_value('EMAIL_SUBJECT_PASSWORDLESS'), user.email,
'login_instructions', user=user, login_link=login_link)
login_instructions_sent.send(app._get_current_object(), user=user,
login_token=token) | python | def send_login_instructions(user):
"""Sends the login instructions email for the specified user.
:param user: The user to send the instructions to
:param token: The login token
"""
token = generate_login_token(user)
login_link = url_for_security('token_login', token=token, _external=True)
_security.send_mail(config_value('EMAIL_SUBJECT_PASSWORDLESS'), user.email,
'login_instructions', user=user, login_link=login_link)
login_instructions_sent.send(app._get_current_object(), user=user,
login_token=token) | [
"def",
"send_login_instructions",
"(",
"user",
")",
":",
"token",
"=",
"generate_login_token",
"(",
"user",
")",
"login_link",
"=",
"url_for_security",
"(",
"'token_login'",
",",
"token",
"=",
"token",
",",
"_external",
"=",
"True",
")",
"_security",
".",
"send_mail",
"(",
"config_value",
"(",
"'EMAIL_SUBJECT_PASSWORDLESS'",
")",
",",
"user",
".",
"email",
",",
"'login_instructions'",
",",
"user",
"=",
"user",
",",
"login_link",
"=",
"login_link",
")",
"login_instructions_sent",
".",
"send",
"(",
"app",
".",
"_get_current_object",
"(",
")",
",",
"user",
"=",
"user",
",",
"login_token",
"=",
"token",
")"
] | Sends the login instructions email for the specified user.
:param user: The user to send the instructions to
:param token: The login token | [
"Sends",
"the",
"login",
"instructions",
"email",
"for",
"the",
"specified",
"user",
"."
] | a401fb47018fbbbe0b899ea55afadfd0e3cd847a | https://github.com/mattupstate/flask-security/blob/a401fb47018fbbbe0b899ea55afadfd0e3cd847a/flask_security/passwordless.py#L24-L37 |
227,632 | mattupstate/flask-security | flask_security/cli.py | roles_add | def roles_add(user, role):
"""Add user to role."""
user, role = _datastore._prepare_role_modify_args(user, role)
if user is None:
raise click.UsageError('Cannot find user.')
if role is None:
raise click.UsageError('Cannot find role.')
if _datastore.add_role_to_user(user, role):
click.secho('Role "{0}" added to user "{1}" '
'successfully.'.format(role, user), fg='green')
else:
raise click.UsageError('Cannot add role to user.') | python | def roles_add(user, role):
"""Add user to role."""
user, role = _datastore._prepare_role_modify_args(user, role)
if user is None:
raise click.UsageError('Cannot find user.')
if role is None:
raise click.UsageError('Cannot find role.')
if _datastore.add_role_to_user(user, role):
click.secho('Role "{0}" added to user "{1}" '
'successfully.'.format(role, user), fg='green')
else:
raise click.UsageError('Cannot add role to user.') | [
"def",
"roles_add",
"(",
"user",
",",
"role",
")",
":",
"user",
",",
"role",
"=",
"_datastore",
".",
"_prepare_role_modify_args",
"(",
"user",
",",
"role",
")",
"if",
"user",
"is",
"None",
":",
"raise",
"click",
".",
"UsageError",
"(",
"'Cannot find user.'",
")",
"if",
"role",
"is",
"None",
":",
"raise",
"click",
".",
"UsageError",
"(",
"'Cannot find role.'",
")",
"if",
"_datastore",
".",
"add_role_to_user",
"(",
"user",
",",
"role",
")",
":",
"click",
".",
"secho",
"(",
"'Role \"{0}\" added to user \"{1}\" '",
"'successfully.'",
".",
"format",
"(",
"role",
",",
"user",
")",
",",
"fg",
"=",
"'green'",
")",
"else",
":",
"raise",
"click",
".",
"UsageError",
"(",
"'Cannot add role to user.'",
")"
] | Add user to role. | [
"Add",
"user",
"to",
"role",
"."
] | a401fb47018fbbbe0b899ea55afadfd0e3cd847a | https://github.com/mattupstate/flask-security/blob/a401fb47018fbbbe0b899ea55afadfd0e3cd847a/flask_security/cli.py#L93-L104 |
227,633 | mattupstate/flask-security | flask_security/cli.py | roles_remove | def roles_remove(user, role):
"""Remove user from role."""
user, role = _datastore._prepare_role_modify_args(user, role)
if user is None:
raise click.UsageError('Cannot find user.')
if role is None:
raise click.UsageError('Cannot find role.')
if _datastore.remove_role_from_user(user, role):
click.secho('Role "{0}" removed from user "{1}" '
'successfully.'.format(role, user), fg='green')
else:
raise click.UsageError('Cannot remove role from user.') | python | def roles_remove(user, role):
"""Remove user from role."""
user, role = _datastore._prepare_role_modify_args(user, role)
if user is None:
raise click.UsageError('Cannot find user.')
if role is None:
raise click.UsageError('Cannot find role.')
if _datastore.remove_role_from_user(user, role):
click.secho('Role "{0}" removed from user "{1}" '
'successfully.'.format(role, user), fg='green')
else:
raise click.UsageError('Cannot remove role from user.') | [
"def",
"roles_remove",
"(",
"user",
",",
"role",
")",
":",
"user",
",",
"role",
"=",
"_datastore",
".",
"_prepare_role_modify_args",
"(",
"user",
",",
"role",
")",
"if",
"user",
"is",
"None",
":",
"raise",
"click",
".",
"UsageError",
"(",
"'Cannot find user.'",
")",
"if",
"role",
"is",
"None",
":",
"raise",
"click",
".",
"UsageError",
"(",
"'Cannot find role.'",
")",
"if",
"_datastore",
".",
"remove_role_from_user",
"(",
"user",
",",
"role",
")",
":",
"click",
".",
"secho",
"(",
"'Role \"{0}\" removed from user \"{1}\" '",
"'successfully.'",
".",
"format",
"(",
"role",
",",
"user",
")",
",",
"fg",
"=",
"'green'",
")",
"else",
":",
"raise",
"click",
".",
"UsageError",
"(",
"'Cannot remove role from user.'",
")"
] | Remove user from role. | [
"Remove",
"user",
"from",
"role",
"."
] | a401fb47018fbbbe0b899ea55afadfd0e3cd847a | https://github.com/mattupstate/flask-security/blob/a401fb47018fbbbe0b899ea55afadfd0e3cd847a/flask_security/cli.py#L112-L123 |
227,634 | mattupstate/flask-security | flask_security/changeable.py | send_password_changed_notice | def send_password_changed_notice(user):
"""Sends the password changed notice email for the specified user.
:param user: The user to send the notice to
"""
if config_value('SEND_PASSWORD_CHANGE_EMAIL'):
subject = config_value('EMAIL_SUBJECT_PASSWORD_CHANGE_NOTICE')
_security.send_mail(subject, user.email, 'change_notice', user=user) | python | def send_password_changed_notice(user):
"""Sends the password changed notice email for the specified user.
:param user: The user to send the notice to
"""
if config_value('SEND_PASSWORD_CHANGE_EMAIL'):
subject = config_value('EMAIL_SUBJECT_PASSWORD_CHANGE_NOTICE')
_security.send_mail(subject, user.email, 'change_notice', user=user) | [
"def",
"send_password_changed_notice",
"(",
"user",
")",
":",
"if",
"config_value",
"(",
"'SEND_PASSWORD_CHANGE_EMAIL'",
")",
":",
"subject",
"=",
"config_value",
"(",
"'EMAIL_SUBJECT_PASSWORD_CHANGE_NOTICE'",
")",
"_security",
".",
"send_mail",
"(",
"subject",
",",
"user",
".",
"email",
",",
"'change_notice'",
",",
"user",
"=",
"user",
")"
] | Sends the password changed notice email for the specified user.
:param user: The user to send the notice to | [
"Sends",
"the",
"password",
"changed",
"notice",
"email",
"for",
"the",
"specified",
"user",
"."
] | a401fb47018fbbbe0b899ea55afadfd0e3cd847a | https://github.com/mattupstate/flask-security/blob/a401fb47018fbbbe0b899ea55afadfd0e3cd847a/flask_security/changeable.py#L25-L32 |
227,635 | mattupstate/flask-security | flask_security/changeable.py | change_user_password | def change_user_password(user, password):
"""Change the specified user's password
:param user: The user to change_password
:param password: The unhashed new password
"""
user.password = hash_password(password)
_datastore.put(user)
send_password_changed_notice(user)
password_changed.send(current_app._get_current_object(),
user=user) | python | def change_user_password(user, password):
"""Change the specified user's password
:param user: The user to change_password
:param password: The unhashed new password
"""
user.password = hash_password(password)
_datastore.put(user)
send_password_changed_notice(user)
password_changed.send(current_app._get_current_object(),
user=user) | [
"def",
"change_user_password",
"(",
"user",
",",
"password",
")",
":",
"user",
".",
"password",
"=",
"hash_password",
"(",
"password",
")",
"_datastore",
".",
"put",
"(",
"user",
")",
"send_password_changed_notice",
"(",
"user",
")",
"password_changed",
".",
"send",
"(",
"current_app",
".",
"_get_current_object",
"(",
")",
",",
"user",
"=",
"user",
")"
] | Change the specified user's password
:param user: The user to change_password
:param password: The unhashed new password | [
"Change",
"the",
"specified",
"user",
"s",
"password"
] | a401fb47018fbbbe0b899ea55afadfd0e3cd847a | https://github.com/mattupstate/flask-security/blob/a401fb47018fbbbe0b899ea55afadfd0e3cd847a/flask_security/changeable.py#L35-L45 |
227,636 | jd/tenacity | tenacity/after.py | after_log | def after_log(logger, log_level, sec_format="%0.3f"):
"""After call strategy that logs to some logger the finished attempt."""
log_tpl = ("Finished call to '%s' after " + str(sec_format) + "(s), "
"this was the %s time calling it.")
def log_it(retry_state):
logger.log(log_level, log_tpl,
_utils.get_callback_name(retry_state.fn),
retry_state.seconds_since_start,
_utils.to_ordinal(retry_state.attempt_number))
return log_it | python | def after_log(logger, log_level, sec_format="%0.3f"):
"""After call strategy that logs to some logger the finished attempt."""
log_tpl = ("Finished call to '%s' after " + str(sec_format) + "(s), "
"this was the %s time calling it.")
def log_it(retry_state):
logger.log(log_level, log_tpl,
_utils.get_callback_name(retry_state.fn),
retry_state.seconds_since_start,
_utils.to_ordinal(retry_state.attempt_number))
return log_it | [
"def",
"after_log",
"(",
"logger",
",",
"log_level",
",",
"sec_format",
"=",
"\"%0.3f\"",
")",
":",
"log_tpl",
"=",
"(",
"\"Finished call to '%s' after \"",
"+",
"str",
"(",
"sec_format",
")",
"+",
"\"(s), \"",
"\"this was the %s time calling it.\"",
")",
"def",
"log_it",
"(",
"retry_state",
")",
":",
"logger",
".",
"log",
"(",
"log_level",
",",
"log_tpl",
",",
"_utils",
".",
"get_callback_name",
"(",
"retry_state",
".",
"fn",
")",
",",
"retry_state",
".",
"seconds_since_start",
",",
"_utils",
".",
"to_ordinal",
"(",
"retry_state",
".",
"attempt_number",
")",
")",
"return",
"log_it"
] | After call strategy that logs to some logger the finished attempt. | [
"After",
"call",
"strategy",
"that",
"logs",
"to",
"some",
"logger",
"the",
"finished",
"attempt",
"."
] | 354c40b7dc8e728c438668100dd020b65c84dfc6 | https://github.com/jd/tenacity/blob/354c40b7dc8e728c438668100dd020b65c84dfc6/tenacity/after.py#L24-L35 |
227,637 | jd/tenacity | tenacity/__init__.py | retry | def retry(*dargs, **dkw):
"""Wrap a function with a new `Retrying` object.
:param dargs: positional arguments passed to Retrying object
:param dkw: keyword arguments passed to the Retrying object
"""
# support both @retry and @retry() as valid syntax
if len(dargs) == 1 and callable(dargs[0]):
return retry()(dargs[0])
else:
def wrap(f):
if asyncio and asyncio.iscoroutinefunction(f):
r = AsyncRetrying(*dargs, **dkw)
elif tornado and hasattr(tornado.gen, 'is_coroutine_function') \
and tornado.gen.is_coroutine_function(f):
r = TornadoRetrying(*dargs, **dkw)
else:
r = Retrying(*dargs, **dkw)
return r.wraps(f)
return wrap | python | def retry(*dargs, **dkw):
"""Wrap a function with a new `Retrying` object.
:param dargs: positional arguments passed to Retrying object
:param dkw: keyword arguments passed to the Retrying object
"""
# support both @retry and @retry() as valid syntax
if len(dargs) == 1 and callable(dargs[0]):
return retry()(dargs[0])
else:
def wrap(f):
if asyncio and asyncio.iscoroutinefunction(f):
r = AsyncRetrying(*dargs, **dkw)
elif tornado and hasattr(tornado.gen, 'is_coroutine_function') \
and tornado.gen.is_coroutine_function(f):
r = TornadoRetrying(*dargs, **dkw)
else:
r = Retrying(*dargs, **dkw)
return r.wraps(f)
return wrap | [
"def",
"retry",
"(",
"*",
"dargs",
",",
"*",
"*",
"dkw",
")",
":",
"# support both @retry and @retry() as valid syntax",
"if",
"len",
"(",
"dargs",
")",
"==",
"1",
"and",
"callable",
"(",
"dargs",
"[",
"0",
"]",
")",
":",
"return",
"retry",
"(",
")",
"(",
"dargs",
"[",
"0",
"]",
")",
"else",
":",
"def",
"wrap",
"(",
"f",
")",
":",
"if",
"asyncio",
"and",
"asyncio",
".",
"iscoroutinefunction",
"(",
"f",
")",
":",
"r",
"=",
"AsyncRetrying",
"(",
"*",
"dargs",
",",
"*",
"*",
"dkw",
")",
"elif",
"tornado",
"and",
"hasattr",
"(",
"tornado",
".",
"gen",
",",
"'is_coroutine_function'",
")",
"and",
"tornado",
".",
"gen",
".",
"is_coroutine_function",
"(",
"f",
")",
":",
"r",
"=",
"TornadoRetrying",
"(",
"*",
"dargs",
",",
"*",
"*",
"dkw",
")",
"else",
":",
"r",
"=",
"Retrying",
"(",
"*",
"dargs",
",",
"*",
"*",
"dkw",
")",
"return",
"r",
".",
"wraps",
"(",
"f",
")",
"return",
"wrap"
] | Wrap a function with a new `Retrying` object.
:param dargs: positional arguments passed to Retrying object
:param dkw: keyword arguments passed to the Retrying object | [
"Wrap",
"a",
"function",
"with",
"a",
"new",
"Retrying",
"object",
"."
] | 354c40b7dc8e728c438668100dd020b65c84dfc6 | https://github.com/jd/tenacity/blob/354c40b7dc8e728c438668100dd020b65c84dfc6/tenacity/__init__.py#L88-L109 |
227,638 | jd/tenacity | tenacity/__init__.py | BaseRetrying.copy | def copy(self, sleep=_unset, stop=_unset, wait=_unset,
retry=_unset, before=_unset, after=_unset, before_sleep=_unset,
reraise=_unset):
"""Copy this object with some parameters changed if needed."""
if before_sleep is _unset:
before_sleep = self.before_sleep
return self.__class__(
sleep=self.sleep if sleep is _unset else sleep,
stop=self.stop if stop is _unset else stop,
wait=self.wait if wait is _unset else wait,
retry=self.retry if retry is _unset else retry,
before=self.before if before is _unset else before,
after=self.after if after is _unset else after,
before_sleep=before_sleep,
reraise=self.reraise if after is _unset else reraise,
) | python | def copy(self, sleep=_unset, stop=_unset, wait=_unset,
retry=_unset, before=_unset, after=_unset, before_sleep=_unset,
reraise=_unset):
"""Copy this object with some parameters changed if needed."""
if before_sleep is _unset:
before_sleep = self.before_sleep
return self.__class__(
sleep=self.sleep if sleep is _unset else sleep,
stop=self.stop if stop is _unset else stop,
wait=self.wait if wait is _unset else wait,
retry=self.retry if retry is _unset else retry,
before=self.before if before is _unset else before,
after=self.after if after is _unset else after,
before_sleep=before_sleep,
reraise=self.reraise if after is _unset else reraise,
) | [
"def",
"copy",
"(",
"self",
",",
"sleep",
"=",
"_unset",
",",
"stop",
"=",
"_unset",
",",
"wait",
"=",
"_unset",
",",
"retry",
"=",
"_unset",
",",
"before",
"=",
"_unset",
",",
"after",
"=",
"_unset",
",",
"before_sleep",
"=",
"_unset",
",",
"reraise",
"=",
"_unset",
")",
":",
"if",
"before_sleep",
"is",
"_unset",
":",
"before_sleep",
"=",
"self",
".",
"before_sleep",
"return",
"self",
".",
"__class__",
"(",
"sleep",
"=",
"self",
".",
"sleep",
"if",
"sleep",
"is",
"_unset",
"else",
"sleep",
",",
"stop",
"=",
"self",
".",
"stop",
"if",
"stop",
"is",
"_unset",
"else",
"stop",
",",
"wait",
"=",
"self",
".",
"wait",
"if",
"wait",
"is",
"_unset",
"else",
"wait",
",",
"retry",
"=",
"self",
".",
"retry",
"if",
"retry",
"is",
"_unset",
"else",
"retry",
",",
"before",
"=",
"self",
".",
"before",
"if",
"before",
"is",
"_unset",
"else",
"before",
",",
"after",
"=",
"self",
".",
"after",
"if",
"after",
"is",
"_unset",
"else",
"after",
",",
"before_sleep",
"=",
"before_sleep",
",",
"reraise",
"=",
"self",
".",
"reraise",
"if",
"after",
"is",
"_unset",
"else",
"reraise",
",",
")"
] | Copy this object with some parameters changed if needed. | [
"Copy",
"this",
"object",
"with",
"some",
"parameters",
"changed",
"if",
"needed",
"."
] | 354c40b7dc8e728c438668100dd020b65c84dfc6 | https://github.com/jd/tenacity/blob/354c40b7dc8e728c438668100dd020b65c84dfc6/tenacity/__init__.py#L231-L246 |
227,639 | jd/tenacity | tenacity/__init__.py | BaseRetrying.statistics | def statistics(self):
"""Return a dictionary of runtime statistics.
This dictionary will be empty when the controller has never been
ran. When it is running or has ran previously it should have (but
may not) have useful and/or informational keys and values when
running is underway and/or completed.
.. warning:: The keys in this dictionary **should** be some what
stable (not changing), but there existence **may**
change between major releases as new statistics are
gathered or removed so before accessing keys ensure that
they actually exist and handle when they do not.
.. note:: The values in this dictionary are local to the thread
running call (so if multiple threads share the same retrying
object - either directly or indirectly) they will each have
there own view of statistics they have collected (in the
future we may provide a way to aggregate the various
statistics from each thread).
"""
try:
return self._local.statistics
except AttributeError:
self._local.statistics = {}
return self._local.statistics | python | def statistics(self):
"""Return a dictionary of runtime statistics.
This dictionary will be empty when the controller has never been
ran. When it is running or has ran previously it should have (but
may not) have useful and/or informational keys and values when
running is underway and/or completed.
.. warning:: The keys in this dictionary **should** be some what
stable (not changing), but there existence **may**
change between major releases as new statistics are
gathered or removed so before accessing keys ensure that
they actually exist and handle when they do not.
.. note:: The values in this dictionary are local to the thread
running call (so if multiple threads share the same retrying
object - either directly or indirectly) they will each have
there own view of statistics they have collected (in the
future we may provide a way to aggregate the various
statistics from each thread).
"""
try:
return self._local.statistics
except AttributeError:
self._local.statistics = {}
return self._local.statistics | [
"def",
"statistics",
"(",
"self",
")",
":",
"try",
":",
"return",
"self",
".",
"_local",
".",
"statistics",
"except",
"AttributeError",
":",
"self",
".",
"_local",
".",
"statistics",
"=",
"{",
"}",
"return",
"self",
".",
"_local",
".",
"statistics"
] | Return a dictionary of runtime statistics.
This dictionary will be empty when the controller has never been
ran. When it is running or has ran previously it should have (but
may not) have useful and/or informational keys and values when
running is underway and/or completed.
.. warning:: The keys in this dictionary **should** be some what
stable (not changing), but there existence **may**
change between major releases as new statistics are
gathered or removed so before accessing keys ensure that
they actually exist and handle when they do not.
.. note:: The values in this dictionary are local to the thread
running call (so if multiple threads share the same retrying
object - either directly or indirectly) they will each have
there own view of statistics they have collected (in the
future we may provide a way to aggregate the various
statistics from each thread). | [
"Return",
"a",
"dictionary",
"of",
"runtime",
"statistics",
"."
] | 354c40b7dc8e728c438668100dd020b65c84dfc6 | https://github.com/jd/tenacity/blob/354c40b7dc8e728c438668100dd020b65c84dfc6/tenacity/__init__.py#L258-L283 |
227,640 | jd/tenacity | tenacity/__init__.py | BaseRetrying.wraps | def wraps(self, f):
"""Wrap a function for retrying.
:param f: A function to wraps for retrying.
"""
@_utils.wraps(f)
def wrapped_f(*args, **kw):
return self.call(f, *args, **kw)
def retry_with(*args, **kwargs):
return self.copy(*args, **kwargs).wraps(f)
wrapped_f.retry = self
wrapped_f.retry_with = retry_with
return wrapped_f | python | def wraps(self, f):
"""Wrap a function for retrying.
:param f: A function to wraps for retrying.
"""
@_utils.wraps(f)
def wrapped_f(*args, **kw):
return self.call(f, *args, **kw)
def retry_with(*args, **kwargs):
return self.copy(*args, **kwargs).wraps(f)
wrapped_f.retry = self
wrapped_f.retry_with = retry_with
return wrapped_f | [
"def",
"wraps",
"(",
"self",
",",
"f",
")",
":",
"@",
"_utils",
".",
"wraps",
"(",
"f",
")",
"def",
"wrapped_f",
"(",
"*",
"args",
",",
"*",
"*",
"kw",
")",
":",
"return",
"self",
".",
"call",
"(",
"f",
",",
"*",
"args",
",",
"*",
"*",
"kw",
")",
"def",
"retry_with",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"copy",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
".",
"wraps",
"(",
"f",
")",
"wrapped_f",
".",
"retry",
"=",
"self",
"wrapped_f",
".",
"retry_with",
"=",
"retry_with",
"return",
"wrapped_f"
] | Wrap a function for retrying.
:param f: A function to wraps for retrying. | [
"Wrap",
"a",
"function",
"for",
"retrying",
"."
] | 354c40b7dc8e728c438668100dd020b65c84dfc6 | https://github.com/jd/tenacity/blob/354c40b7dc8e728c438668100dd020b65c84dfc6/tenacity/__init__.py#L285-L300 |
227,641 | jd/tenacity | tenacity/__init__.py | Future.construct | def construct(cls, attempt_number, value, has_exception):
"""Construct a new Future object."""
fut = cls(attempt_number)
if has_exception:
fut.set_exception(value)
else:
fut.set_result(value)
return fut | python | def construct(cls, attempt_number, value, has_exception):
"""Construct a new Future object."""
fut = cls(attempt_number)
if has_exception:
fut.set_exception(value)
else:
fut.set_result(value)
return fut | [
"def",
"construct",
"(",
"cls",
",",
"attempt_number",
",",
"value",
",",
"has_exception",
")",
":",
"fut",
"=",
"cls",
"(",
"attempt_number",
")",
"if",
"has_exception",
":",
"fut",
".",
"set_exception",
"(",
"value",
")",
"else",
":",
"fut",
".",
"set_result",
"(",
"value",
")",
"return",
"fut"
] | Construct a new Future object. | [
"Construct",
"a",
"new",
"Future",
"object",
"."
] | 354c40b7dc8e728c438668100dd020b65c84dfc6 | https://github.com/jd/tenacity/blob/354c40b7dc8e728c438668100dd020b65c84dfc6/tenacity/__init__.py#L388-L395 |
227,642 | jd/tenacity | tenacity/_utils.py | get_callback_name | def get_callback_name(cb):
"""Get a callback fully-qualified name.
If no name can be produced ``repr(cb)`` is called and returned.
"""
segments = []
try:
segments.append(cb.__qualname__)
except AttributeError:
try:
segments.append(cb.__name__)
if inspect.ismethod(cb):
try:
# This attribute doesn't exist on py3.x or newer, so
# we optionally ignore it... (on those versions of
# python `__qualname__` should have been found anyway).
segments.insert(0, cb.im_class.__name__)
except AttributeError:
pass
except AttributeError:
pass
if not segments:
return repr(cb)
else:
try:
# When running under sphinx it appears this can be none?
if cb.__module__:
segments.insert(0, cb.__module__)
except AttributeError:
pass
return ".".join(segments) | python | def get_callback_name(cb):
"""Get a callback fully-qualified name.
If no name can be produced ``repr(cb)`` is called and returned.
"""
segments = []
try:
segments.append(cb.__qualname__)
except AttributeError:
try:
segments.append(cb.__name__)
if inspect.ismethod(cb):
try:
# This attribute doesn't exist on py3.x or newer, so
# we optionally ignore it... (on those versions of
# python `__qualname__` should have been found anyway).
segments.insert(0, cb.im_class.__name__)
except AttributeError:
pass
except AttributeError:
pass
if not segments:
return repr(cb)
else:
try:
# When running under sphinx it appears this can be none?
if cb.__module__:
segments.insert(0, cb.__module__)
except AttributeError:
pass
return ".".join(segments) | [
"def",
"get_callback_name",
"(",
"cb",
")",
":",
"segments",
"=",
"[",
"]",
"try",
":",
"segments",
".",
"append",
"(",
"cb",
".",
"__qualname__",
")",
"except",
"AttributeError",
":",
"try",
":",
"segments",
".",
"append",
"(",
"cb",
".",
"__name__",
")",
"if",
"inspect",
".",
"ismethod",
"(",
"cb",
")",
":",
"try",
":",
"# This attribute doesn't exist on py3.x or newer, so",
"# we optionally ignore it... (on those versions of",
"# python `__qualname__` should have been found anyway).",
"segments",
".",
"insert",
"(",
"0",
",",
"cb",
".",
"im_class",
".",
"__name__",
")",
"except",
"AttributeError",
":",
"pass",
"except",
"AttributeError",
":",
"pass",
"if",
"not",
"segments",
":",
"return",
"repr",
"(",
"cb",
")",
"else",
":",
"try",
":",
"# When running under sphinx it appears this can be none?",
"if",
"cb",
".",
"__module__",
":",
"segments",
".",
"insert",
"(",
"0",
",",
"cb",
".",
"__module__",
")",
"except",
"AttributeError",
":",
"pass",
"return",
"\".\"",
".",
"join",
"(",
"segments",
")"
] | Get a callback fully-qualified name.
If no name can be produced ``repr(cb)`` is called and returned. | [
"Get",
"a",
"callback",
"fully",
"-",
"qualified",
"name",
"."
] | 354c40b7dc8e728c438668100dd020b65c84dfc6 | https://github.com/jd/tenacity/blob/354c40b7dc8e728c438668100dd020b65c84dfc6/tenacity/_utils.py#L98-L128 |
227,643 | jd/tenacity | tenacity/compat.py | make_retry_state | def make_retry_state(previous_attempt_number, delay_since_first_attempt,
last_result=None):
"""Construct RetryCallState for given attempt number & delay.
Only used in testing and thus is extra careful about timestamp arithmetics.
"""
required_parameter_unset = (previous_attempt_number is _unset or
delay_since_first_attempt is _unset)
if required_parameter_unset:
raise _make_unset_exception(
'wait/stop',
previous_attempt_number=previous_attempt_number,
delay_since_first_attempt=delay_since_first_attempt)
from tenacity import RetryCallState
retry_state = RetryCallState(None, None, (), {})
retry_state.attempt_number = previous_attempt_number
if last_result is not None:
retry_state.outcome = last_result
else:
retry_state.set_result(None)
_set_delay_since_start(retry_state, delay_since_first_attempt)
return retry_state | python | def make_retry_state(previous_attempt_number, delay_since_first_attempt,
last_result=None):
"""Construct RetryCallState for given attempt number & delay.
Only used in testing and thus is extra careful about timestamp arithmetics.
"""
required_parameter_unset = (previous_attempt_number is _unset or
delay_since_first_attempt is _unset)
if required_parameter_unset:
raise _make_unset_exception(
'wait/stop',
previous_attempt_number=previous_attempt_number,
delay_since_first_attempt=delay_since_first_attempt)
from tenacity import RetryCallState
retry_state = RetryCallState(None, None, (), {})
retry_state.attempt_number = previous_attempt_number
if last_result is not None:
retry_state.outcome = last_result
else:
retry_state.set_result(None)
_set_delay_since_start(retry_state, delay_since_first_attempt)
return retry_state | [
"def",
"make_retry_state",
"(",
"previous_attempt_number",
",",
"delay_since_first_attempt",
",",
"last_result",
"=",
"None",
")",
":",
"required_parameter_unset",
"=",
"(",
"previous_attempt_number",
"is",
"_unset",
"or",
"delay_since_first_attempt",
"is",
"_unset",
")",
"if",
"required_parameter_unset",
":",
"raise",
"_make_unset_exception",
"(",
"'wait/stop'",
",",
"previous_attempt_number",
"=",
"previous_attempt_number",
",",
"delay_since_first_attempt",
"=",
"delay_since_first_attempt",
")",
"from",
"tenacity",
"import",
"RetryCallState",
"retry_state",
"=",
"RetryCallState",
"(",
"None",
",",
"None",
",",
"(",
")",
",",
"{",
"}",
")",
"retry_state",
".",
"attempt_number",
"=",
"previous_attempt_number",
"if",
"last_result",
"is",
"not",
"None",
":",
"retry_state",
".",
"outcome",
"=",
"last_result",
"else",
":",
"retry_state",
".",
"set_result",
"(",
"None",
")",
"_set_delay_since_start",
"(",
"retry_state",
",",
"delay_since_first_attempt",
")",
"return",
"retry_state"
] | Construct RetryCallState for given attempt number & delay.
Only used in testing and thus is extra careful about timestamp arithmetics. | [
"Construct",
"RetryCallState",
"for",
"given",
"attempt",
"number",
"&",
"delay",
"."
] | 354c40b7dc8e728c438668100dd020b65c84dfc6 | https://github.com/jd/tenacity/blob/354c40b7dc8e728c438668100dd020b65c84dfc6/tenacity/compat.py#L57-L79 |
227,644 | jd/tenacity | tenacity/compat.py | func_takes_last_result | def func_takes_last_result(waiter):
"""Check if function has a "last_result" parameter.
Needed to provide backward compatibility for wait functions that didn't
take "last_result" in the beginning.
"""
if not six.callable(waiter):
return False
if not inspect.isfunction(waiter) and not inspect.ismethod(waiter):
# waiter is a class, check dunder-call rather than dunder-init.
waiter = waiter.__call__
waiter_spec = _utils.getargspec(waiter)
return 'last_result' in waiter_spec.args | python | def func_takes_last_result(waiter):
"""Check if function has a "last_result" parameter.
Needed to provide backward compatibility for wait functions that didn't
take "last_result" in the beginning.
"""
if not six.callable(waiter):
return False
if not inspect.isfunction(waiter) and not inspect.ismethod(waiter):
# waiter is a class, check dunder-call rather than dunder-init.
waiter = waiter.__call__
waiter_spec = _utils.getargspec(waiter)
return 'last_result' in waiter_spec.args | [
"def",
"func_takes_last_result",
"(",
"waiter",
")",
":",
"if",
"not",
"six",
".",
"callable",
"(",
"waiter",
")",
":",
"return",
"False",
"if",
"not",
"inspect",
".",
"isfunction",
"(",
"waiter",
")",
"and",
"not",
"inspect",
".",
"ismethod",
"(",
"waiter",
")",
":",
"# waiter is a class, check dunder-call rather than dunder-init.",
"waiter",
"=",
"waiter",
".",
"__call__",
"waiter_spec",
"=",
"_utils",
".",
"getargspec",
"(",
"waiter",
")",
"return",
"'last_result'",
"in",
"waiter_spec",
".",
"args"
] | Check if function has a "last_result" parameter.
Needed to provide backward compatibility for wait functions that didn't
take "last_result" in the beginning. | [
"Check",
"if",
"function",
"has",
"a",
"last_result",
"parameter",
"."
] | 354c40b7dc8e728c438668100dd020b65c84dfc6 | https://github.com/jd/tenacity/blob/354c40b7dc8e728c438668100dd020b65c84dfc6/tenacity/compat.py#L82-L94 |
227,645 | jd/tenacity | tenacity/compat.py | stop_func_accept_retry_state | def stop_func_accept_retry_state(stop_func):
"""Wrap "stop" function to accept "retry_state" parameter."""
if not six.callable(stop_func):
return stop_func
if func_takes_retry_state(stop_func):
return stop_func
@_utils.wraps(stop_func)
def wrapped_stop_func(retry_state):
warn_about_non_retry_state_deprecation(
'stop', stop_func, stacklevel=4)
return stop_func(
retry_state.attempt_number,
retry_state.seconds_since_start,
)
return wrapped_stop_func | python | def stop_func_accept_retry_state(stop_func):
"""Wrap "stop" function to accept "retry_state" parameter."""
if not six.callable(stop_func):
return stop_func
if func_takes_retry_state(stop_func):
return stop_func
@_utils.wraps(stop_func)
def wrapped_stop_func(retry_state):
warn_about_non_retry_state_deprecation(
'stop', stop_func, stacklevel=4)
return stop_func(
retry_state.attempt_number,
retry_state.seconds_since_start,
)
return wrapped_stop_func | [
"def",
"stop_func_accept_retry_state",
"(",
"stop_func",
")",
":",
"if",
"not",
"six",
".",
"callable",
"(",
"stop_func",
")",
":",
"return",
"stop_func",
"if",
"func_takes_retry_state",
"(",
"stop_func",
")",
":",
"return",
"stop_func",
"@",
"_utils",
".",
"wraps",
"(",
"stop_func",
")",
"def",
"wrapped_stop_func",
"(",
"retry_state",
")",
":",
"warn_about_non_retry_state_deprecation",
"(",
"'stop'",
",",
"stop_func",
",",
"stacklevel",
"=",
"4",
")",
"return",
"stop_func",
"(",
"retry_state",
".",
"attempt_number",
",",
"retry_state",
".",
"seconds_since_start",
",",
")",
"return",
"wrapped_stop_func"
] | Wrap "stop" function to accept "retry_state" parameter. | [
"Wrap",
"stop",
"function",
"to",
"accept",
"retry_state",
"parameter",
"."
] | 354c40b7dc8e728c438668100dd020b65c84dfc6 | https://github.com/jd/tenacity/blob/354c40b7dc8e728c438668100dd020b65c84dfc6/tenacity/compat.py#L120-L136 |
227,646 | jd/tenacity | tenacity/compat.py | wait_func_accept_retry_state | def wait_func_accept_retry_state(wait_func):
"""Wrap wait function to accept "retry_state" parameter."""
if not six.callable(wait_func):
return wait_func
if func_takes_retry_state(wait_func):
return wait_func
if func_takes_last_result(wait_func):
@_utils.wraps(wait_func)
def wrapped_wait_func(retry_state):
warn_about_non_retry_state_deprecation(
'wait', wait_func, stacklevel=4)
return wait_func(
retry_state.attempt_number,
retry_state.seconds_since_start,
last_result=retry_state.outcome,
)
else:
@_utils.wraps(wait_func)
def wrapped_wait_func(retry_state):
warn_about_non_retry_state_deprecation(
'wait', wait_func, stacklevel=4)
return wait_func(
retry_state.attempt_number,
retry_state.seconds_since_start,
)
return wrapped_wait_func | python | def wait_func_accept_retry_state(wait_func):
"""Wrap wait function to accept "retry_state" parameter."""
if not six.callable(wait_func):
return wait_func
if func_takes_retry_state(wait_func):
return wait_func
if func_takes_last_result(wait_func):
@_utils.wraps(wait_func)
def wrapped_wait_func(retry_state):
warn_about_non_retry_state_deprecation(
'wait', wait_func, stacklevel=4)
return wait_func(
retry_state.attempt_number,
retry_state.seconds_since_start,
last_result=retry_state.outcome,
)
else:
@_utils.wraps(wait_func)
def wrapped_wait_func(retry_state):
warn_about_non_retry_state_deprecation(
'wait', wait_func, stacklevel=4)
return wait_func(
retry_state.attempt_number,
retry_state.seconds_since_start,
)
return wrapped_wait_func | [
"def",
"wait_func_accept_retry_state",
"(",
"wait_func",
")",
":",
"if",
"not",
"six",
".",
"callable",
"(",
"wait_func",
")",
":",
"return",
"wait_func",
"if",
"func_takes_retry_state",
"(",
"wait_func",
")",
":",
"return",
"wait_func",
"if",
"func_takes_last_result",
"(",
"wait_func",
")",
":",
"@",
"_utils",
".",
"wraps",
"(",
"wait_func",
")",
"def",
"wrapped_wait_func",
"(",
"retry_state",
")",
":",
"warn_about_non_retry_state_deprecation",
"(",
"'wait'",
",",
"wait_func",
",",
"stacklevel",
"=",
"4",
")",
"return",
"wait_func",
"(",
"retry_state",
".",
"attempt_number",
",",
"retry_state",
".",
"seconds_since_start",
",",
"last_result",
"=",
"retry_state",
".",
"outcome",
",",
")",
"else",
":",
"@",
"_utils",
".",
"wraps",
"(",
"wait_func",
")",
"def",
"wrapped_wait_func",
"(",
"retry_state",
")",
":",
"warn_about_non_retry_state_deprecation",
"(",
"'wait'",
",",
"wait_func",
",",
"stacklevel",
"=",
"4",
")",
"return",
"wait_func",
"(",
"retry_state",
".",
"attempt_number",
",",
"retry_state",
".",
"seconds_since_start",
",",
")",
"return",
"wrapped_wait_func"
] | Wrap wait function to accept "retry_state" parameter. | [
"Wrap",
"wait",
"function",
"to",
"accept",
"retry_state",
"parameter",
"."
] | 354c40b7dc8e728c438668100dd020b65c84dfc6 | https://github.com/jd/tenacity/blob/354c40b7dc8e728c438668100dd020b65c84dfc6/tenacity/compat.py#L164-L191 |
227,647 | jd/tenacity | tenacity/compat.py | retry_func_accept_retry_state | def retry_func_accept_retry_state(retry_func):
"""Wrap "retry" function to accept "retry_state" parameter."""
if not six.callable(retry_func):
return retry_func
if func_takes_retry_state(retry_func):
return retry_func
@_utils.wraps(retry_func)
def wrapped_retry_func(retry_state):
warn_about_non_retry_state_deprecation(
'retry', retry_func, stacklevel=4)
return retry_func(retry_state.outcome)
return wrapped_retry_func | python | def retry_func_accept_retry_state(retry_func):
"""Wrap "retry" function to accept "retry_state" parameter."""
if not six.callable(retry_func):
return retry_func
if func_takes_retry_state(retry_func):
return retry_func
@_utils.wraps(retry_func)
def wrapped_retry_func(retry_state):
warn_about_non_retry_state_deprecation(
'retry', retry_func, stacklevel=4)
return retry_func(retry_state.outcome)
return wrapped_retry_func | [
"def",
"retry_func_accept_retry_state",
"(",
"retry_func",
")",
":",
"if",
"not",
"six",
".",
"callable",
"(",
"retry_func",
")",
":",
"return",
"retry_func",
"if",
"func_takes_retry_state",
"(",
"retry_func",
")",
":",
"return",
"retry_func",
"@",
"_utils",
".",
"wraps",
"(",
"retry_func",
")",
"def",
"wrapped_retry_func",
"(",
"retry_state",
")",
":",
"warn_about_non_retry_state_deprecation",
"(",
"'retry'",
",",
"retry_func",
",",
"stacklevel",
"=",
"4",
")",
"return",
"retry_func",
"(",
"retry_state",
".",
"outcome",
")",
"return",
"wrapped_retry_func"
] | Wrap "retry" function to accept "retry_state" parameter. | [
"Wrap",
"retry",
"function",
"to",
"accept",
"retry_state",
"parameter",
"."
] | 354c40b7dc8e728c438668100dd020b65c84dfc6 | https://github.com/jd/tenacity/blob/354c40b7dc8e728c438668100dd020b65c84dfc6/tenacity/compat.py#L215-L228 |
227,648 | jd/tenacity | tenacity/compat.py | before_func_accept_retry_state | def before_func_accept_retry_state(fn):
"""Wrap "before" function to accept "retry_state"."""
if not six.callable(fn):
return fn
if func_takes_retry_state(fn):
return fn
@_utils.wraps(fn)
def wrapped_before_func(retry_state):
# func, trial_number, trial_time_taken
warn_about_non_retry_state_deprecation('before', fn, stacklevel=4)
return fn(
retry_state.fn,
retry_state.attempt_number,
)
return wrapped_before_func | python | def before_func_accept_retry_state(fn):
"""Wrap "before" function to accept "retry_state"."""
if not six.callable(fn):
return fn
if func_takes_retry_state(fn):
return fn
@_utils.wraps(fn)
def wrapped_before_func(retry_state):
# func, trial_number, trial_time_taken
warn_about_non_retry_state_deprecation('before', fn, stacklevel=4)
return fn(
retry_state.fn,
retry_state.attempt_number,
)
return wrapped_before_func | [
"def",
"before_func_accept_retry_state",
"(",
"fn",
")",
":",
"if",
"not",
"six",
".",
"callable",
"(",
"fn",
")",
":",
"return",
"fn",
"if",
"func_takes_retry_state",
"(",
"fn",
")",
":",
"return",
"fn",
"@",
"_utils",
".",
"wraps",
"(",
"fn",
")",
"def",
"wrapped_before_func",
"(",
"retry_state",
")",
":",
"# func, trial_number, trial_time_taken",
"warn_about_non_retry_state_deprecation",
"(",
"'before'",
",",
"fn",
",",
"stacklevel",
"=",
"4",
")",
"return",
"fn",
"(",
"retry_state",
".",
"fn",
",",
"retry_state",
".",
"attempt_number",
",",
")",
"return",
"wrapped_before_func"
] | Wrap "before" function to accept "retry_state". | [
"Wrap",
"before",
"function",
"to",
"accept",
"retry_state",
"."
] | 354c40b7dc8e728c438668100dd020b65c84dfc6 | https://github.com/jd/tenacity/blob/354c40b7dc8e728c438668100dd020b65c84dfc6/tenacity/compat.py#L231-L247 |
227,649 | jd/tenacity | tenacity/compat.py | after_func_accept_retry_state | def after_func_accept_retry_state(fn):
"""Wrap "after" function to accept "retry_state"."""
if not six.callable(fn):
return fn
if func_takes_retry_state(fn):
return fn
@_utils.wraps(fn)
def wrapped_after_sleep_func(retry_state):
# func, trial_number, trial_time_taken
warn_about_non_retry_state_deprecation('after', fn, stacklevel=4)
return fn(
retry_state.fn,
retry_state.attempt_number,
retry_state.seconds_since_start)
return wrapped_after_sleep_func | python | def after_func_accept_retry_state(fn):
"""Wrap "after" function to accept "retry_state"."""
if not six.callable(fn):
return fn
if func_takes_retry_state(fn):
return fn
@_utils.wraps(fn)
def wrapped_after_sleep_func(retry_state):
# func, trial_number, trial_time_taken
warn_about_non_retry_state_deprecation('after', fn, stacklevel=4)
return fn(
retry_state.fn,
retry_state.attempt_number,
retry_state.seconds_since_start)
return wrapped_after_sleep_func | [
"def",
"after_func_accept_retry_state",
"(",
"fn",
")",
":",
"if",
"not",
"six",
".",
"callable",
"(",
"fn",
")",
":",
"return",
"fn",
"if",
"func_takes_retry_state",
"(",
"fn",
")",
":",
"return",
"fn",
"@",
"_utils",
".",
"wraps",
"(",
"fn",
")",
"def",
"wrapped_after_sleep_func",
"(",
"retry_state",
")",
":",
"# func, trial_number, trial_time_taken",
"warn_about_non_retry_state_deprecation",
"(",
"'after'",
",",
"fn",
",",
"stacklevel",
"=",
"4",
")",
"return",
"fn",
"(",
"retry_state",
".",
"fn",
",",
"retry_state",
".",
"attempt_number",
",",
"retry_state",
".",
"seconds_since_start",
")",
"return",
"wrapped_after_sleep_func"
] | Wrap "after" function to accept "retry_state". | [
"Wrap",
"after",
"function",
"to",
"accept",
"retry_state",
"."
] | 354c40b7dc8e728c438668100dd020b65c84dfc6 | https://github.com/jd/tenacity/blob/354c40b7dc8e728c438668100dd020b65c84dfc6/tenacity/compat.py#L250-L266 |
227,650 | jd/tenacity | tenacity/compat.py | before_sleep_func_accept_retry_state | def before_sleep_func_accept_retry_state(fn):
"""Wrap "before_sleep" function to accept "retry_state"."""
if not six.callable(fn):
return fn
if func_takes_retry_state(fn):
return fn
@_utils.wraps(fn)
def wrapped_before_sleep_func(retry_state):
# retry_object, sleep, last_result
warn_about_non_retry_state_deprecation(
'before_sleep', fn, stacklevel=4)
return fn(
retry_state.retry_object,
sleep=getattr(retry_state.next_action, 'sleep'),
last_result=retry_state.outcome)
return wrapped_before_sleep_func | python | def before_sleep_func_accept_retry_state(fn):
"""Wrap "before_sleep" function to accept "retry_state"."""
if not six.callable(fn):
return fn
if func_takes_retry_state(fn):
return fn
@_utils.wraps(fn)
def wrapped_before_sleep_func(retry_state):
# retry_object, sleep, last_result
warn_about_non_retry_state_deprecation(
'before_sleep', fn, stacklevel=4)
return fn(
retry_state.retry_object,
sleep=getattr(retry_state.next_action, 'sleep'),
last_result=retry_state.outcome)
return wrapped_before_sleep_func | [
"def",
"before_sleep_func_accept_retry_state",
"(",
"fn",
")",
":",
"if",
"not",
"six",
".",
"callable",
"(",
"fn",
")",
":",
"return",
"fn",
"if",
"func_takes_retry_state",
"(",
"fn",
")",
":",
"return",
"fn",
"@",
"_utils",
".",
"wraps",
"(",
"fn",
")",
"def",
"wrapped_before_sleep_func",
"(",
"retry_state",
")",
":",
"# retry_object, sleep, last_result",
"warn_about_non_retry_state_deprecation",
"(",
"'before_sleep'",
",",
"fn",
",",
"stacklevel",
"=",
"4",
")",
"return",
"fn",
"(",
"retry_state",
".",
"retry_object",
",",
"sleep",
"=",
"getattr",
"(",
"retry_state",
".",
"next_action",
",",
"'sleep'",
")",
",",
"last_result",
"=",
"retry_state",
".",
"outcome",
")",
"return",
"wrapped_before_sleep_func"
] | Wrap "before_sleep" function to accept "retry_state". | [
"Wrap",
"before_sleep",
"function",
"to",
"accept",
"retry_state",
"."
] | 354c40b7dc8e728c438668100dd020b65c84dfc6 | https://github.com/jd/tenacity/blob/354c40b7dc8e728c438668100dd020b65c84dfc6/tenacity/compat.py#L269-L286 |
227,651 | divio/django-filer | filer/admin/patched/admin_utils.py | NestedObjects.nested | def nested(self, format_callback=None):
"""
Return the graph as a nested list.
"""
seen = set()
roots = []
for root in self.edges.get(None, ()):
roots.extend(self._nested(root, seen, format_callback))
return roots | python | def nested(self, format_callback=None):
"""
Return the graph as a nested list.
"""
seen = set()
roots = []
for root in self.edges.get(None, ()):
roots.extend(self._nested(root, seen, format_callback))
return roots | [
"def",
"nested",
"(",
"self",
",",
"format_callback",
"=",
"None",
")",
":",
"seen",
"=",
"set",
"(",
")",
"roots",
"=",
"[",
"]",
"for",
"root",
"in",
"self",
".",
"edges",
".",
"get",
"(",
"None",
",",
"(",
")",
")",
":",
"roots",
".",
"extend",
"(",
"self",
".",
"_nested",
"(",
"root",
",",
"seen",
",",
"format_callback",
")",
")",
"return",
"roots"
] | Return the graph as a nested list. | [
"Return",
"the",
"graph",
"as",
"a",
"nested",
"list",
"."
] | 946629087943d41eff290f07bfdf240b8853dd88 | https://github.com/divio/django-filer/blob/946629087943d41eff290f07bfdf240b8853dd88/filer/admin/patched/admin_utils.py#L132-L140 |
227,652 | divio/django-filer | filer/utils/files.py | get_valid_filename | def get_valid_filename(s):
"""
like the regular get_valid_filename, but also slugifies away
umlauts and stuff.
"""
s = get_valid_filename_django(s)
filename, ext = os.path.splitext(s)
filename = slugify(filename)
ext = slugify(ext)
if ext:
return "%s.%s" % (filename, ext)
else:
return "%s" % (filename,) | python | def get_valid_filename(s):
"""
like the regular get_valid_filename, but also slugifies away
umlauts and stuff.
"""
s = get_valid_filename_django(s)
filename, ext = os.path.splitext(s)
filename = slugify(filename)
ext = slugify(ext)
if ext:
return "%s.%s" % (filename, ext)
else:
return "%s" % (filename,) | [
"def",
"get_valid_filename",
"(",
"s",
")",
":",
"s",
"=",
"get_valid_filename_django",
"(",
"s",
")",
"filename",
",",
"ext",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"s",
")",
"filename",
"=",
"slugify",
"(",
"filename",
")",
"ext",
"=",
"slugify",
"(",
"ext",
")",
"if",
"ext",
":",
"return",
"\"%s.%s\"",
"%",
"(",
"filename",
",",
"ext",
")",
"else",
":",
"return",
"\"%s\"",
"%",
"(",
"filename",
",",
")"
] | like the regular get_valid_filename, but also slugifies away
umlauts and stuff. | [
"like",
"the",
"regular",
"get_valid_filename",
"but",
"also",
"slugifies",
"away",
"umlauts",
"and",
"stuff",
"."
] | 946629087943d41eff290f07bfdf240b8853dd88 | https://github.com/divio/django-filer/blob/946629087943d41eff290f07bfdf240b8853dd88/filer/utils/files.py#L122-L134 |
227,653 | divio/django-filer | filer/management/commands/import_files.py | FileImporter.walker | def walker(self, path=None, base_folder=None):
"""
This method walk a directory structure and create the
Folders and Files as they appear.
"""
path = path or self.path or ''
base_folder = base_folder or self.base_folder
# prevent trailing slashes and other inconsistencies on path.
path = os.path.normpath(upath(path))
if base_folder:
base_folder = os.path.normpath(upath(base_folder))
print("The directory structure will be imported in %s" % (base_folder,))
if self.verbosity >= 1:
print("Import the folders and files in %s" % (path,))
root_folder_name = os.path.basename(path)
for root, dirs, files in os.walk(path):
rel_folders = root.partition(path)[2].strip(os.path.sep).split(os.path.sep)
while '' in rel_folders:
rel_folders.remove('')
if base_folder:
folder_names = base_folder.split('/') + [root_folder_name] + rel_folders
else:
folder_names = [root_folder_name] + rel_folders
folder = self.get_or_create_folder(folder_names)
for file_obj in files:
dj_file = DjangoFile(open(os.path.join(root, file_obj), mode='rb'),
name=file_obj)
self.import_file(file_obj=dj_file, folder=folder)
if self.verbosity >= 1:
print(('folder_created #%s / file_created #%s / ' + 'image_created #%s') % (self.folder_created, self.file_created, self.image_created)) | python | def walker(self, path=None, base_folder=None):
"""
This method walk a directory structure and create the
Folders and Files as they appear.
"""
path = path or self.path or ''
base_folder = base_folder or self.base_folder
# prevent trailing slashes and other inconsistencies on path.
path = os.path.normpath(upath(path))
if base_folder:
base_folder = os.path.normpath(upath(base_folder))
print("The directory structure will be imported in %s" % (base_folder,))
if self.verbosity >= 1:
print("Import the folders and files in %s" % (path,))
root_folder_name = os.path.basename(path)
for root, dirs, files in os.walk(path):
rel_folders = root.partition(path)[2].strip(os.path.sep).split(os.path.sep)
while '' in rel_folders:
rel_folders.remove('')
if base_folder:
folder_names = base_folder.split('/') + [root_folder_name] + rel_folders
else:
folder_names = [root_folder_name] + rel_folders
folder = self.get_or_create_folder(folder_names)
for file_obj in files:
dj_file = DjangoFile(open(os.path.join(root, file_obj), mode='rb'),
name=file_obj)
self.import_file(file_obj=dj_file, folder=folder)
if self.verbosity >= 1:
print(('folder_created #%s / file_created #%s / ' + 'image_created #%s') % (self.folder_created, self.file_created, self.image_created)) | [
"def",
"walker",
"(",
"self",
",",
"path",
"=",
"None",
",",
"base_folder",
"=",
"None",
")",
":",
"path",
"=",
"path",
"or",
"self",
".",
"path",
"or",
"''",
"base_folder",
"=",
"base_folder",
"or",
"self",
".",
"base_folder",
"# prevent trailing slashes and other inconsistencies on path.",
"path",
"=",
"os",
".",
"path",
".",
"normpath",
"(",
"upath",
"(",
"path",
")",
")",
"if",
"base_folder",
":",
"base_folder",
"=",
"os",
".",
"path",
".",
"normpath",
"(",
"upath",
"(",
"base_folder",
")",
")",
"print",
"(",
"\"The directory structure will be imported in %s\"",
"%",
"(",
"base_folder",
",",
")",
")",
"if",
"self",
".",
"verbosity",
">=",
"1",
":",
"print",
"(",
"\"Import the folders and files in %s\"",
"%",
"(",
"path",
",",
")",
")",
"root_folder_name",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"path",
")",
"for",
"root",
",",
"dirs",
",",
"files",
"in",
"os",
".",
"walk",
"(",
"path",
")",
":",
"rel_folders",
"=",
"root",
".",
"partition",
"(",
"path",
")",
"[",
"2",
"]",
".",
"strip",
"(",
"os",
".",
"path",
".",
"sep",
")",
".",
"split",
"(",
"os",
".",
"path",
".",
"sep",
")",
"while",
"''",
"in",
"rel_folders",
":",
"rel_folders",
".",
"remove",
"(",
"''",
")",
"if",
"base_folder",
":",
"folder_names",
"=",
"base_folder",
".",
"split",
"(",
"'/'",
")",
"+",
"[",
"root_folder_name",
"]",
"+",
"rel_folders",
"else",
":",
"folder_names",
"=",
"[",
"root_folder_name",
"]",
"+",
"rel_folders",
"folder",
"=",
"self",
".",
"get_or_create_folder",
"(",
"folder_names",
")",
"for",
"file_obj",
"in",
"files",
":",
"dj_file",
"=",
"DjangoFile",
"(",
"open",
"(",
"os",
".",
"path",
".",
"join",
"(",
"root",
",",
"file_obj",
")",
",",
"mode",
"=",
"'rb'",
")",
",",
"name",
"=",
"file_obj",
")",
"self",
".",
"import_file",
"(",
"file_obj",
"=",
"dj_file",
",",
"folder",
"=",
"folder",
")",
"if",
"self",
".",
"verbosity",
">=",
"1",
":",
"print",
"(",
"(",
"'folder_created #%s / file_created #%s / '",
"+",
"'image_created #%s'",
")",
"%",
"(",
"self",
".",
"folder_created",
",",
"self",
".",
"file_created",
",",
"self",
".",
"image_created",
")",
")"
] | This method walk a directory structure and create the
Folders and Files as they appear. | [
"This",
"method",
"walk",
"a",
"directory",
"structure",
"and",
"create",
"the",
"Folders",
"and",
"Files",
"as",
"they",
"appear",
"."
] | 946629087943d41eff290f07bfdf240b8853dd88 | https://github.com/divio/django-filer/blob/946629087943d41eff290f07bfdf240b8853dd88/filer/management/commands/import_files.py#L79-L108 |
227,654 | divio/django-filer | filer/utils/zip.py | unzip | def unzip(file_obj):
"""
Take a path to a zipfile and checks if it is a valid zip file
and returns...
"""
files = []
# TODO: implement try-except here
zip = ZipFile(file_obj)
bad_file = zip.testzip()
if bad_file:
raise Exception('"%s" in the .zip archive is corrupt.' % bad_file)
infolist = zip.infolist()
for zipinfo in infolist:
if zipinfo.filename.startswith('__'): # do not process meta files
continue
file_obj = SimpleUploadedFile(name=zipinfo.filename, content=zip.read(zipinfo))
files.append((file_obj, zipinfo.filename))
zip.close()
return files | python | def unzip(file_obj):
"""
Take a path to a zipfile and checks if it is a valid zip file
and returns...
"""
files = []
# TODO: implement try-except here
zip = ZipFile(file_obj)
bad_file = zip.testzip()
if bad_file:
raise Exception('"%s" in the .zip archive is corrupt.' % bad_file)
infolist = zip.infolist()
for zipinfo in infolist:
if zipinfo.filename.startswith('__'): # do not process meta files
continue
file_obj = SimpleUploadedFile(name=zipinfo.filename, content=zip.read(zipinfo))
files.append((file_obj, zipinfo.filename))
zip.close()
return files | [
"def",
"unzip",
"(",
"file_obj",
")",
":",
"files",
"=",
"[",
"]",
"# TODO: implement try-except here",
"zip",
"=",
"ZipFile",
"(",
"file_obj",
")",
"bad_file",
"=",
"zip",
".",
"testzip",
"(",
")",
"if",
"bad_file",
":",
"raise",
"Exception",
"(",
"'\"%s\" in the .zip archive is corrupt.'",
"%",
"bad_file",
")",
"infolist",
"=",
"zip",
".",
"infolist",
"(",
")",
"for",
"zipinfo",
"in",
"infolist",
":",
"if",
"zipinfo",
".",
"filename",
".",
"startswith",
"(",
"'__'",
")",
":",
"# do not process meta files",
"continue",
"file_obj",
"=",
"SimpleUploadedFile",
"(",
"name",
"=",
"zipinfo",
".",
"filename",
",",
"content",
"=",
"zip",
".",
"read",
"(",
"zipinfo",
")",
")",
"files",
".",
"append",
"(",
"(",
"file_obj",
",",
"zipinfo",
".",
"filename",
")",
")",
"zip",
".",
"close",
"(",
")",
"return",
"files"
] | Take a path to a zipfile and checks if it is a valid zip file
and returns... | [
"Take",
"a",
"path",
"to",
"a",
"zipfile",
"and",
"checks",
"if",
"it",
"is",
"a",
"valid",
"zip",
"file",
"and",
"returns",
"..."
] | 946629087943d41eff290f07bfdf240b8853dd88 | https://github.com/divio/django-filer/blob/946629087943d41eff290f07bfdf240b8853dd88/filer/utils/zip.py#L9-L27 |
227,655 | divio/django-filer | filer/utils/filer_easy_thumbnails.py | ThumbnailerNameMixin.get_thumbnail_name | def get_thumbnail_name(self, thumbnail_options, transparent=False,
high_resolution=False):
"""
A version of ``Thumbnailer.get_thumbnail_name`` that produces a
reproducible thumbnail name that can be converted back to the original
filename.
"""
path, source_filename = os.path.split(self.name)
source_extension = os.path.splitext(source_filename)[1][1:]
if self.thumbnail_preserve_extensions is True or \
(self.thumbnail_preserve_extensions and source_extension.lower()
in self.thumbnail_preserve_extensions):
extension = source_extension
elif transparent:
extension = self.thumbnail_transparency_extension
else:
extension = self.thumbnail_extension
extension = extension or 'jpg'
thumbnail_options = thumbnail_options.copy()
size = tuple(thumbnail_options.pop('size'))
quality = thumbnail_options.pop('quality', self.thumbnail_quality)
initial_opts = ['%sx%s' % size, 'q%s' % quality]
opts = list(thumbnail_options.items())
opts.sort() # Sort the options so the file name is consistent.
opts = ['%s' % (v is not True and '%s-%s' % (k, v) or k)
for k, v in opts if v]
all_opts = '_'.join(initial_opts + opts)
basedir = self.thumbnail_basedir
subdir = self.thumbnail_subdir
# make sure our magic delimiter is not used in all_opts
all_opts = all_opts.replace('__', '_')
if high_resolution:
try:
all_opts += self.thumbnail_highres_infix
except AttributeError:
all_opts += '@2x'
filename = '%s__%s.%s' % (source_filename, all_opts, extension)
return os.path.join(basedir, path, subdir, filename) | python | def get_thumbnail_name(self, thumbnail_options, transparent=False,
high_resolution=False):
"""
A version of ``Thumbnailer.get_thumbnail_name`` that produces a
reproducible thumbnail name that can be converted back to the original
filename.
"""
path, source_filename = os.path.split(self.name)
source_extension = os.path.splitext(source_filename)[1][1:]
if self.thumbnail_preserve_extensions is True or \
(self.thumbnail_preserve_extensions and source_extension.lower()
in self.thumbnail_preserve_extensions):
extension = source_extension
elif transparent:
extension = self.thumbnail_transparency_extension
else:
extension = self.thumbnail_extension
extension = extension or 'jpg'
thumbnail_options = thumbnail_options.copy()
size = tuple(thumbnail_options.pop('size'))
quality = thumbnail_options.pop('quality', self.thumbnail_quality)
initial_opts = ['%sx%s' % size, 'q%s' % quality]
opts = list(thumbnail_options.items())
opts.sort() # Sort the options so the file name is consistent.
opts = ['%s' % (v is not True and '%s-%s' % (k, v) or k)
for k, v in opts if v]
all_opts = '_'.join(initial_opts + opts)
basedir = self.thumbnail_basedir
subdir = self.thumbnail_subdir
# make sure our magic delimiter is not used in all_opts
all_opts = all_opts.replace('__', '_')
if high_resolution:
try:
all_opts += self.thumbnail_highres_infix
except AttributeError:
all_opts += '@2x'
filename = '%s__%s.%s' % (source_filename, all_opts, extension)
return os.path.join(basedir, path, subdir, filename) | [
"def",
"get_thumbnail_name",
"(",
"self",
",",
"thumbnail_options",
",",
"transparent",
"=",
"False",
",",
"high_resolution",
"=",
"False",
")",
":",
"path",
",",
"source_filename",
"=",
"os",
".",
"path",
".",
"split",
"(",
"self",
".",
"name",
")",
"source_extension",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"source_filename",
")",
"[",
"1",
"]",
"[",
"1",
":",
"]",
"if",
"self",
".",
"thumbnail_preserve_extensions",
"is",
"True",
"or",
"(",
"self",
".",
"thumbnail_preserve_extensions",
"and",
"source_extension",
".",
"lower",
"(",
")",
"in",
"self",
".",
"thumbnail_preserve_extensions",
")",
":",
"extension",
"=",
"source_extension",
"elif",
"transparent",
":",
"extension",
"=",
"self",
".",
"thumbnail_transparency_extension",
"else",
":",
"extension",
"=",
"self",
".",
"thumbnail_extension",
"extension",
"=",
"extension",
"or",
"'jpg'",
"thumbnail_options",
"=",
"thumbnail_options",
".",
"copy",
"(",
")",
"size",
"=",
"tuple",
"(",
"thumbnail_options",
".",
"pop",
"(",
"'size'",
")",
")",
"quality",
"=",
"thumbnail_options",
".",
"pop",
"(",
"'quality'",
",",
"self",
".",
"thumbnail_quality",
")",
"initial_opts",
"=",
"[",
"'%sx%s'",
"%",
"size",
",",
"'q%s'",
"%",
"quality",
"]",
"opts",
"=",
"list",
"(",
"thumbnail_options",
".",
"items",
"(",
")",
")",
"opts",
".",
"sort",
"(",
")",
"# Sort the options so the file name is consistent.",
"opts",
"=",
"[",
"'%s'",
"%",
"(",
"v",
"is",
"not",
"True",
"and",
"'%s-%s'",
"%",
"(",
"k",
",",
"v",
")",
"or",
"k",
")",
"for",
"k",
",",
"v",
"in",
"opts",
"if",
"v",
"]",
"all_opts",
"=",
"'_'",
".",
"join",
"(",
"initial_opts",
"+",
"opts",
")",
"basedir",
"=",
"self",
".",
"thumbnail_basedir",
"subdir",
"=",
"self",
".",
"thumbnail_subdir",
"# make sure our magic delimiter is not used in all_opts",
"all_opts",
"=",
"all_opts",
".",
"replace",
"(",
"'__'",
",",
"'_'",
")",
"if",
"high_resolution",
":",
"try",
":",
"all_opts",
"+=",
"self",
".",
"thumbnail_highres_infix",
"except",
"AttributeError",
":",
"all_opts",
"+=",
"'@2x'",
"filename",
"=",
"'%s__%s.%s'",
"%",
"(",
"source_filename",
",",
"all_opts",
",",
"extension",
")",
"return",
"os",
".",
"path",
".",
"join",
"(",
"basedir",
",",
"path",
",",
"subdir",
",",
"filename",
")"
] | A version of ``Thumbnailer.get_thumbnail_name`` that produces a
reproducible thumbnail name that can be converted back to the original
filename. | [
"A",
"version",
"of",
"Thumbnailer",
".",
"get_thumbnail_name",
"that",
"produces",
"a",
"reproducible",
"thumbnail",
"name",
"that",
"can",
"be",
"converted",
"back",
"to",
"the",
"original",
"filename",
"."
] | 946629087943d41eff290f07bfdf240b8853dd88 | https://github.com/divio/django-filer/blob/946629087943d41eff290f07bfdf240b8853dd88/filer/utils/filer_easy_thumbnails.py#L29-L72 |
227,656 | divio/django-filer | filer/utils/filer_easy_thumbnails.py | ActionThumbnailerMixin.get_thumbnail_name | def get_thumbnail_name(self, thumbnail_options, transparent=False,
high_resolution=False):
"""
A version of ``Thumbnailer.get_thumbnail_name`` that returns the original
filename to resize.
"""
path, filename = os.path.split(self.name)
basedir = self.thumbnail_basedir
subdir = self.thumbnail_subdir
return os.path.join(basedir, path, subdir, filename) | python | def get_thumbnail_name(self, thumbnail_options, transparent=False,
high_resolution=False):
"""
A version of ``Thumbnailer.get_thumbnail_name`` that returns the original
filename to resize.
"""
path, filename = os.path.split(self.name)
basedir = self.thumbnail_basedir
subdir = self.thumbnail_subdir
return os.path.join(basedir, path, subdir, filename) | [
"def",
"get_thumbnail_name",
"(",
"self",
",",
"thumbnail_options",
",",
"transparent",
"=",
"False",
",",
"high_resolution",
"=",
"False",
")",
":",
"path",
",",
"filename",
"=",
"os",
".",
"path",
".",
"split",
"(",
"self",
".",
"name",
")",
"basedir",
"=",
"self",
".",
"thumbnail_basedir",
"subdir",
"=",
"self",
".",
"thumbnail_subdir",
"return",
"os",
".",
"path",
".",
"join",
"(",
"basedir",
",",
"path",
",",
"subdir",
",",
"filename",
")"
] | A version of ``Thumbnailer.get_thumbnail_name`` that returns the original
filename to resize. | [
"A",
"version",
"of",
"Thumbnailer",
".",
"get_thumbnail_name",
"that",
"returns",
"the",
"original",
"filename",
"to",
"resize",
"."
] | 946629087943d41eff290f07bfdf240b8853dd88 | https://github.com/divio/django-filer/blob/946629087943d41eff290f07bfdf240b8853dd88/filer/utils/filer_easy_thumbnails.py#L80-L91 |
227,657 | divio/django-filer | filer/admin/folderadmin.py | FolderAdmin.owner_search_fields | def owner_search_fields(self):
"""
Returns all the fields that are CharFields except for password from the
User model. For the built-in User model, that means username,
first_name, last_name, and email.
"""
try:
from django.contrib.auth import get_user_model
except ImportError: # Django < 1.5
from django.contrib.auth.models import User
else:
User = get_user_model()
return [
field.name for field in User._meta.fields
if isinstance(field, models.CharField) and field.name != 'password'
] | python | def owner_search_fields(self):
"""
Returns all the fields that are CharFields except for password from the
User model. For the built-in User model, that means username,
first_name, last_name, and email.
"""
try:
from django.contrib.auth import get_user_model
except ImportError: # Django < 1.5
from django.contrib.auth.models import User
else:
User = get_user_model()
return [
field.name for field in User._meta.fields
if isinstance(field, models.CharField) and field.name != 'password'
] | [
"def",
"owner_search_fields",
"(",
"self",
")",
":",
"try",
":",
"from",
"django",
".",
"contrib",
".",
"auth",
"import",
"get_user_model",
"except",
"ImportError",
":",
"# Django < 1.5",
"from",
"django",
".",
"contrib",
".",
"auth",
".",
"models",
"import",
"User",
"else",
":",
"User",
"=",
"get_user_model",
"(",
")",
"return",
"[",
"field",
".",
"name",
"for",
"field",
"in",
"User",
".",
"_meta",
".",
"fields",
"if",
"isinstance",
"(",
"field",
",",
"models",
".",
"CharField",
")",
"and",
"field",
".",
"name",
"!=",
"'password'",
"]"
] | Returns all the fields that are CharFields except for password from the
User model. For the built-in User model, that means username,
first_name, last_name, and email. | [
"Returns",
"all",
"the",
"fields",
"that",
"are",
"CharFields",
"except",
"for",
"password",
"from",
"the",
"User",
"model",
".",
"For",
"the",
"built",
"-",
"in",
"User",
"model",
"that",
"means",
"username",
"first_name",
"last_name",
"and",
"email",
"."
] | 946629087943d41eff290f07bfdf240b8853dd88 | https://github.com/divio/django-filer/blob/946629087943d41eff290f07bfdf240b8853dd88/filer/admin/folderadmin.py#L481-L496 |
227,658 | divio/django-filer | filer/admin/folderadmin.py | FolderAdmin.move_to_clipboard | def move_to_clipboard(self, request, files_queryset, folders_queryset):
"""
Action which moves the selected files and files in selected folders
to clipboard.
"""
if not self.has_change_permission(request):
raise PermissionDenied
if request.method != 'POST':
return None
clipboard = tools.get_user_clipboard(request.user)
check_files_edit_permissions(request, files_queryset)
check_folder_edit_permissions(request, folders_queryset)
# TODO: Display a confirmation page if moving more than X files to
# clipboard?
# We define it like that so that we can modify it inside the
# move_files function
files_count = [0]
def move_files(files):
files_count[0] += tools.move_file_to_clipboard(files, clipboard)
def move_folders(folders):
for f in folders:
move_files(f.files)
move_folders(f.children.all())
move_files(files_queryset)
move_folders(folders_queryset)
self.message_user(request, _("Successfully moved %(count)d files to "
"clipboard.") % {"count": files_count[0]})
return None | python | def move_to_clipboard(self, request, files_queryset, folders_queryset):
"""
Action which moves the selected files and files in selected folders
to clipboard.
"""
if not self.has_change_permission(request):
raise PermissionDenied
if request.method != 'POST':
return None
clipboard = tools.get_user_clipboard(request.user)
check_files_edit_permissions(request, files_queryset)
check_folder_edit_permissions(request, folders_queryset)
# TODO: Display a confirmation page if moving more than X files to
# clipboard?
# We define it like that so that we can modify it inside the
# move_files function
files_count = [0]
def move_files(files):
files_count[0] += tools.move_file_to_clipboard(files, clipboard)
def move_folders(folders):
for f in folders:
move_files(f.files)
move_folders(f.children.all())
move_files(files_queryset)
move_folders(folders_queryset)
self.message_user(request, _("Successfully moved %(count)d files to "
"clipboard.") % {"count": files_count[0]})
return None | [
"def",
"move_to_clipboard",
"(",
"self",
",",
"request",
",",
"files_queryset",
",",
"folders_queryset",
")",
":",
"if",
"not",
"self",
".",
"has_change_permission",
"(",
"request",
")",
":",
"raise",
"PermissionDenied",
"if",
"request",
".",
"method",
"!=",
"'POST'",
":",
"return",
"None",
"clipboard",
"=",
"tools",
".",
"get_user_clipboard",
"(",
"request",
".",
"user",
")",
"check_files_edit_permissions",
"(",
"request",
",",
"files_queryset",
")",
"check_folder_edit_permissions",
"(",
"request",
",",
"folders_queryset",
")",
"# TODO: Display a confirmation page if moving more than X files to",
"# clipboard?",
"# We define it like that so that we can modify it inside the",
"# move_files function",
"files_count",
"=",
"[",
"0",
"]",
"def",
"move_files",
"(",
"files",
")",
":",
"files_count",
"[",
"0",
"]",
"+=",
"tools",
".",
"move_file_to_clipboard",
"(",
"files",
",",
"clipboard",
")",
"def",
"move_folders",
"(",
"folders",
")",
":",
"for",
"f",
"in",
"folders",
":",
"move_files",
"(",
"f",
".",
"files",
")",
"move_folders",
"(",
"f",
".",
"children",
".",
"all",
"(",
")",
")",
"move_files",
"(",
"files_queryset",
")",
"move_folders",
"(",
"folders_queryset",
")",
"self",
".",
"message_user",
"(",
"request",
",",
"_",
"(",
"\"Successfully moved %(count)d files to \"",
"\"clipboard.\"",
")",
"%",
"{",
"\"count\"",
":",
"files_count",
"[",
"0",
"]",
"}",
")",
"return",
"None"
] | Action which moves the selected files and files in selected folders
to clipboard. | [
"Action",
"which",
"moves",
"the",
"selected",
"files",
"and",
"files",
"in",
"selected",
"folders",
"to",
"clipboard",
"."
] | 946629087943d41eff290f07bfdf240b8853dd88 | https://github.com/divio/django-filer/blob/946629087943d41eff290f07bfdf240b8853dd88/filer/admin/folderadmin.py#L596-L634 |
227,659 | divio/django-filer | filer/admin/tools.py | admin_url_params | def admin_url_params(request, params=None):
"""
given a request, looks at GET and POST values to determine which params
should be added. Is used to keep the context of popup and picker mode.
"""
params = params or {}
if popup_status(request):
params[IS_POPUP_VAR] = '1'
pick_type = popup_pick_type(request)
if pick_type:
params['_pick'] = pick_type
return params | python | def admin_url_params(request, params=None):
"""
given a request, looks at GET and POST values to determine which params
should be added. Is used to keep the context of popup and picker mode.
"""
params = params or {}
if popup_status(request):
params[IS_POPUP_VAR] = '1'
pick_type = popup_pick_type(request)
if pick_type:
params['_pick'] = pick_type
return params | [
"def",
"admin_url_params",
"(",
"request",
",",
"params",
"=",
"None",
")",
":",
"params",
"=",
"params",
"or",
"{",
"}",
"if",
"popup_status",
"(",
"request",
")",
":",
"params",
"[",
"IS_POPUP_VAR",
"]",
"=",
"'1'",
"pick_type",
"=",
"popup_pick_type",
"(",
"request",
")",
"if",
"pick_type",
":",
"params",
"[",
"'_pick'",
"]",
"=",
"pick_type",
"return",
"params"
] | given a request, looks at GET and POST values to determine which params
should be added. Is used to keep the context of popup and picker mode. | [
"given",
"a",
"request",
"looks",
"at",
"GET",
"and",
"POST",
"values",
"to",
"determine",
"which",
"params",
"should",
"be",
"added",
".",
"Is",
"used",
"to",
"keep",
"the",
"context",
"of",
"popup",
"and",
"picker",
"mode",
"."
] | 946629087943d41eff290f07bfdf240b8853dd88 | https://github.com/divio/django-filer/blob/946629087943d41eff290f07bfdf240b8853dd88/filer/admin/tools.py#L70-L81 |
227,660 | divio/django-filer | filer/admin/imageadmin.py | ImageAdminForm.clean_subject_location | def clean_subject_location(self):
"""
Validate subject_location preserving last saved value.
Last valid value of the subject_location field is shown to the user
for subject location widget to receive valid coordinates on field
validation errors.
"""
cleaned_data = super(ImageAdminForm, self).clean()
subject_location = cleaned_data['subject_location']
if not subject_location:
# if supplied subject location is empty, do not check it
return subject_location
# use thumbnail's helper function to check the format
coordinates = normalize_subject_location(subject_location)
if not coordinates:
err_msg = ugettext_lazy('Invalid subject location format. ')
err_code = 'invalid_subject_format'
elif (
coordinates[0] > self.instance.width
or coordinates[1] > self.instance.height
):
err_msg = ugettext_lazy(
'Subject location is outside of the image. ')
err_code = 'subject_out_of_bounds'
else:
return subject_location
self._set_previous_subject_location(cleaned_data)
raise forms.ValidationError(
string_concat(
err_msg,
ugettext_lazy('Your input: "{subject_location}". '.format(
subject_location=subject_location)),
'Previous value is restored.'),
code=err_code) | python | def clean_subject_location(self):
"""
Validate subject_location preserving last saved value.
Last valid value of the subject_location field is shown to the user
for subject location widget to receive valid coordinates on field
validation errors.
"""
cleaned_data = super(ImageAdminForm, self).clean()
subject_location = cleaned_data['subject_location']
if not subject_location:
# if supplied subject location is empty, do not check it
return subject_location
# use thumbnail's helper function to check the format
coordinates = normalize_subject_location(subject_location)
if not coordinates:
err_msg = ugettext_lazy('Invalid subject location format. ')
err_code = 'invalid_subject_format'
elif (
coordinates[0] > self.instance.width
or coordinates[1] > self.instance.height
):
err_msg = ugettext_lazy(
'Subject location is outside of the image. ')
err_code = 'subject_out_of_bounds'
else:
return subject_location
self._set_previous_subject_location(cleaned_data)
raise forms.ValidationError(
string_concat(
err_msg,
ugettext_lazy('Your input: "{subject_location}". '.format(
subject_location=subject_location)),
'Previous value is restored.'),
code=err_code) | [
"def",
"clean_subject_location",
"(",
"self",
")",
":",
"cleaned_data",
"=",
"super",
"(",
"ImageAdminForm",
",",
"self",
")",
".",
"clean",
"(",
")",
"subject_location",
"=",
"cleaned_data",
"[",
"'subject_location'",
"]",
"if",
"not",
"subject_location",
":",
"# if supplied subject location is empty, do not check it",
"return",
"subject_location",
"# use thumbnail's helper function to check the format",
"coordinates",
"=",
"normalize_subject_location",
"(",
"subject_location",
")",
"if",
"not",
"coordinates",
":",
"err_msg",
"=",
"ugettext_lazy",
"(",
"'Invalid subject location format. '",
")",
"err_code",
"=",
"'invalid_subject_format'",
"elif",
"(",
"coordinates",
"[",
"0",
"]",
">",
"self",
".",
"instance",
".",
"width",
"or",
"coordinates",
"[",
"1",
"]",
">",
"self",
".",
"instance",
".",
"height",
")",
":",
"err_msg",
"=",
"ugettext_lazy",
"(",
"'Subject location is outside of the image. '",
")",
"err_code",
"=",
"'subject_out_of_bounds'",
"else",
":",
"return",
"subject_location",
"self",
".",
"_set_previous_subject_location",
"(",
"cleaned_data",
")",
"raise",
"forms",
".",
"ValidationError",
"(",
"string_concat",
"(",
"err_msg",
",",
"ugettext_lazy",
"(",
"'Your input: \"{subject_location}\". '",
".",
"format",
"(",
"subject_location",
"=",
"subject_location",
")",
")",
",",
"'Previous value is restored.'",
")",
",",
"code",
"=",
"err_code",
")"
] | Validate subject_location preserving last saved value.
Last valid value of the subject_location field is shown to the user
for subject location widget to receive valid coordinates on field
validation errors. | [
"Validate",
"subject_location",
"preserving",
"last",
"saved",
"value",
"."
] | 946629087943d41eff290f07bfdf240b8853dd88 | https://github.com/divio/django-filer/blob/946629087943d41eff290f07bfdf240b8853dd88/filer/admin/imageadmin.py#L42-L80 |
227,661 | divio/django-filer | filer/utils/loader.py | load_object | def load_object(import_path):
"""
Loads an object from an 'import_path', like in MIDDLEWARE_CLASSES and the
likes.
Import paths should be: "mypackage.mymodule.MyObject". It then imports the
module up until the last dot and tries to get the attribute after that dot
from the imported module.
If the import path does not contain any dots, a TypeError is raised.
If the module cannot be imported, an ImportError is raised.
If the attribute does not exist in the module, a AttributeError is raised.
"""
if not isinstance(import_path, six.string_types):
return import_path
if '.' not in import_path:
raise TypeError(
"'import_path' argument to 'django_load.core.load_object' must "
"contain at least one dot.")
module_name, object_name = import_path.rsplit('.', 1)
module = import_module(module_name)
return getattr(module, object_name) | python | def load_object(import_path):
"""
Loads an object from an 'import_path', like in MIDDLEWARE_CLASSES and the
likes.
Import paths should be: "mypackage.mymodule.MyObject". It then imports the
module up until the last dot and tries to get the attribute after that dot
from the imported module.
If the import path does not contain any dots, a TypeError is raised.
If the module cannot be imported, an ImportError is raised.
If the attribute does not exist in the module, a AttributeError is raised.
"""
if not isinstance(import_path, six.string_types):
return import_path
if '.' not in import_path:
raise TypeError(
"'import_path' argument to 'django_load.core.load_object' must "
"contain at least one dot.")
module_name, object_name = import_path.rsplit('.', 1)
module = import_module(module_name)
return getattr(module, object_name) | [
"def",
"load_object",
"(",
"import_path",
")",
":",
"if",
"not",
"isinstance",
"(",
"import_path",
",",
"six",
".",
"string_types",
")",
":",
"return",
"import_path",
"if",
"'.'",
"not",
"in",
"import_path",
":",
"raise",
"TypeError",
"(",
"\"'import_path' argument to 'django_load.core.load_object' must \"",
"\"contain at least one dot.\"",
")",
"module_name",
",",
"object_name",
"=",
"import_path",
".",
"rsplit",
"(",
"'.'",
",",
"1",
")",
"module",
"=",
"import_module",
"(",
"module_name",
")",
"return",
"getattr",
"(",
"module",
",",
"object_name",
")"
] | Loads an object from an 'import_path', like in MIDDLEWARE_CLASSES and the
likes.
Import paths should be: "mypackage.mymodule.MyObject". It then imports the
module up until the last dot and tries to get the attribute after that dot
from the imported module.
If the import path does not contain any dots, a TypeError is raised.
If the module cannot be imported, an ImportError is raised.
If the attribute does not exist in the module, a AttributeError is raised. | [
"Loads",
"an",
"object",
"from",
"an",
"import_path",
"like",
"in",
"MIDDLEWARE_CLASSES",
"and",
"the",
"likes",
"."
] | 946629087943d41eff290f07bfdf240b8853dd88 | https://github.com/divio/django-filer/blob/946629087943d41eff290f07bfdf240b8853dd88/filer/utils/loader.py#L18-L41 |
227,662 | divio/django-filer | filer/management/commands/generate_thumbnails.py | Command.handle | def handle(self, *args, **options):
"""
Generates image thumbnails
NOTE: To keep memory consumption stable avoid iteration over the Image queryset
"""
pks = Image.objects.all().values_list('id', flat=True)
total = len(pks)
for idx, pk in enumerate(pks):
image = None
try:
image = Image.objects.get(pk=pk)
self.stdout.write(u'Processing image {0} / {1} {2}'.format(idx + 1, total, image))
self.stdout.flush()
image.thumbnails
image.icons
except IOError as e:
self.stderr.write('Failed to generate thumbnails: {0}'.format(str(e)))
self.stderr.flush()
finally:
del image | python | def handle(self, *args, **options):
"""
Generates image thumbnails
NOTE: To keep memory consumption stable avoid iteration over the Image queryset
"""
pks = Image.objects.all().values_list('id', flat=True)
total = len(pks)
for idx, pk in enumerate(pks):
image = None
try:
image = Image.objects.get(pk=pk)
self.stdout.write(u'Processing image {0} / {1} {2}'.format(idx + 1, total, image))
self.stdout.flush()
image.thumbnails
image.icons
except IOError as e:
self.stderr.write('Failed to generate thumbnails: {0}'.format(str(e)))
self.stderr.flush()
finally:
del image | [
"def",
"handle",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"options",
")",
":",
"pks",
"=",
"Image",
".",
"objects",
".",
"all",
"(",
")",
".",
"values_list",
"(",
"'id'",
",",
"flat",
"=",
"True",
")",
"total",
"=",
"len",
"(",
"pks",
")",
"for",
"idx",
",",
"pk",
"in",
"enumerate",
"(",
"pks",
")",
":",
"image",
"=",
"None",
"try",
":",
"image",
"=",
"Image",
".",
"objects",
".",
"get",
"(",
"pk",
"=",
"pk",
")",
"self",
".",
"stdout",
".",
"write",
"(",
"u'Processing image {0} / {1} {2}'",
".",
"format",
"(",
"idx",
"+",
"1",
",",
"total",
",",
"image",
")",
")",
"self",
".",
"stdout",
".",
"flush",
"(",
")",
"image",
".",
"thumbnails",
"image",
".",
"icons",
"except",
"IOError",
"as",
"e",
":",
"self",
".",
"stderr",
".",
"write",
"(",
"'Failed to generate thumbnails: {0}'",
".",
"format",
"(",
"str",
"(",
"e",
")",
")",
")",
"self",
".",
"stderr",
".",
"flush",
"(",
")",
"finally",
":",
"del",
"image"
] | Generates image thumbnails
NOTE: To keep memory consumption stable avoid iteration over the Image queryset | [
"Generates",
"image",
"thumbnails"
] | 946629087943d41eff290f07bfdf240b8853dd88 | https://github.com/divio/django-filer/blob/946629087943d41eff290f07bfdf240b8853dd88/filer/management/commands/generate_thumbnails.py#L9-L29 |
227,663 | divio/django-filer | filer/utils/compatibility.py | upath | def upath(path):
"""
Always return a unicode path.
"""
if six.PY2 and not isinstance(path, six.text_type):
return path.decode(fs_encoding)
return path | python | def upath(path):
"""
Always return a unicode path.
"""
if six.PY2 and not isinstance(path, six.text_type):
return path.decode(fs_encoding)
return path | [
"def",
"upath",
"(",
"path",
")",
":",
"if",
"six",
".",
"PY2",
"and",
"not",
"isinstance",
"(",
"path",
",",
"six",
".",
"text_type",
")",
":",
"return",
"path",
".",
"decode",
"(",
"fs_encoding",
")",
"return",
"path"
] | Always return a unicode path. | [
"Always",
"return",
"a",
"unicode",
"path",
"."
] | 946629087943d41eff290f07bfdf240b8853dd88 | https://github.com/divio/django-filer/blob/946629087943d41eff290f07bfdf240b8853dd88/filer/utils/compatibility.py#L60-L66 |
227,664 | divio/django-filer | filer/utils/model_label.py | get_model_label | def get_model_label(model):
"""
Take a model class or model label and return its model label.
>>> get_model_label(MyModel)
"myapp.MyModel"
>>> get_model_label("myapp.MyModel")
"myapp.MyModel"
"""
if isinstance(model, six.string_types):
return model
else:
return "%s.%s" % (
model._meta.app_label,
model.__name__
) | python | def get_model_label(model):
"""
Take a model class or model label and return its model label.
>>> get_model_label(MyModel)
"myapp.MyModel"
>>> get_model_label("myapp.MyModel")
"myapp.MyModel"
"""
if isinstance(model, six.string_types):
return model
else:
return "%s.%s" % (
model._meta.app_label,
model.__name__
) | [
"def",
"get_model_label",
"(",
"model",
")",
":",
"if",
"isinstance",
"(",
"model",
",",
"six",
".",
"string_types",
")",
":",
"return",
"model",
"else",
":",
"return",
"\"%s.%s\"",
"%",
"(",
"model",
".",
"_meta",
".",
"app_label",
",",
"model",
".",
"__name__",
")"
] | Take a model class or model label and return its model label.
>>> get_model_label(MyModel)
"myapp.MyModel"
>>> get_model_label("myapp.MyModel")
"myapp.MyModel" | [
"Take",
"a",
"model",
"class",
"or",
"model",
"label",
"and",
"return",
"its",
"model",
"label",
"."
] | 946629087943d41eff290f07bfdf240b8853dd88 | https://github.com/divio/django-filer/blob/946629087943d41eff290f07bfdf240b8853dd88/filer/utils/model_label.py#L8-L24 |
227,665 | divio/django-filer | filer/admin/clipboardadmin.py | ajax_upload | def ajax_upload(request, folder_id=None):
"""
Receives an upload from the uploader. Receives only one file at a time.
"""
folder = None
if folder_id:
try:
# Get folder
folder = Folder.objects.get(pk=folder_id)
except Folder.DoesNotExist:
return JsonResponse({'error': NO_FOLDER_ERROR})
# check permissions
if folder and not folder.has_add_children_permission(request):
return JsonResponse({'error': NO_PERMISSIONS_FOR_FOLDER})
try:
if len(request.FILES) == 1:
# dont check if request is ajax or not, just grab the file
upload, filename, is_raw = handle_request_files_upload(request)
else:
# else process the request as usual
upload, filename, is_raw = handle_upload(request)
# TODO: Deprecated/refactor
# Get clipboad
# clipboard = Clipboard.objects.get_or_create(user=request.user)[0]
# find the file type
for filer_class in filer_settings.FILER_FILE_MODELS:
FileSubClass = load_model(filer_class)
# TODO: What if there are more than one that qualify?
if FileSubClass.matches_file_type(filename, upload, request):
FileForm = modelform_factory(
model=FileSubClass,
fields=('original_filename', 'owner', 'file')
)
break
uploadform = FileForm({'original_filename': filename,
'owner': request.user.pk},
{'file': upload})
if uploadform.is_valid():
file_obj = uploadform.save(commit=False)
# Enforce the FILER_IS_PUBLIC_DEFAULT
file_obj.is_public = filer_settings.FILER_IS_PUBLIC_DEFAULT
file_obj.folder = folder
file_obj.save()
# TODO: Deprecated/refactor
# clipboard_item = ClipboardItem(
# clipboard=clipboard, file=file_obj)
# clipboard_item.save()
# Try to generate thumbnails.
if not file_obj.icons:
# There is no point to continue, as we can't generate
# thumbnails for this file. Usual reasons: bad format or
# filename.
file_obj.delete()
# This would be logged in BaseImage._generate_thumbnails()
# if FILER_ENABLE_LOGGING is on.
return JsonResponse(
{'error': 'failed to generate icons for file'},
status=500,
)
thumbnail = None
# Backwards compatibility: try to get specific icon size (32px)
# first. Then try medium icon size (they are already sorted),
# fallback to the first (smallest) configured icon.
for size in (['32']
+ filer_settings.FILER_ADMIN_ICON_SIZES[1::-1]):
try:
thumbnail = file_obj.icons[size]
break
except KeyError:
continue
data = {
'thumbnail': thumbnail,
'alt_text': '',
'label': str(file_obj),
'file_id': file_obj.pk,
}
# prepare preview thumbnail
if type(file_obj) == Image:
thumbnail_180_options = {
'size': (180, 180),
'crop': True,
'upscale': True,
}
thumbnail_180 = file_obj.file.get_thumbnail(
thumbnail_180_options)
data['thumbnail_180'] = thumbnail_180.url
data['original_image'] = file_obj.url
return JsonResponse(data)
else:
form_errors = '; '.join(['%s: %s' % (
field,
', '.join(errors)) for field, errors in list(
uploadform.errors.items())
])
raise UploadException(
"AJAX request not valid: form invalid '%s'" % (
form_errors,))
except UploadException as e:
return JsonResponse({'error': str(e)}, status=500) | python | def ajax_upload(request, folder_id=None):
"""
Receives an upload from the uploader. Receives only one file at a time.
"""
folder = None
if folder_id:
try:
# Get folder
folder = Folder.objects.get(pk=folder_id)
except Folder.DoesNotExist:
return JsonResponse({'error': NO_FOLDER_ERROR})
# check permissions
if folder and not folder.has_add_children_permission(request):
return JsonResponse({'error': NO_PERMISSIONS_FOR_FOLDER})
try:
if len(request.FILES) == 1:
# dont check if request is ajax or not, just grab the file
upload, filename, is_raw = handle_request_files_upload(request)
else:
# else process the request as usual
upload, filename, is_raw = handle_upload(request)
# TODO: Deprecated/refactor
# Get clipboad
# clipboard = Clipboard.objects.get_or_create(user=request.user)[0]
# find the file type
for filer_class in filer_settings.FILER_FILE_MODELS:
FileSubClass = load_model(filer_class)
# TODO: What if there are more than one that qualify?
if FileSubClass.matches_file_type(filename, upload, request):
FileForm = modelform_factory(
model=FileSubClass,
fields=('original_filename', 'owner', 'file')
)
break
uploadform = FileForm({'original_filename': filename,
'owner': request.user.pk},
{'file': upload})
if uploadform.is_valid():
file_obj = uploadform.save(commit=False)
# Enforce the FILER_IS_PUBLIC_DEFAULT
file_obj.is_public = filer_settings.FILER_IS_PUBLIC_DEFAULT
file_obj.folder = folder
file_obj.save()
# TODO: Deprecated/refactor
# clipboard_item = ClipboardItem(
# clipboard=clipboard, file=file_obj)
# clipboard_item.save()
# Try to generate thumbnails.
if not file_obj.icons:
# There is no point to continue, as we can't generate
# thumbnails for this file. Usual reasons: bad format or
# filename.
file_obj.delete()
# This would be logged in BaseImage._generate_thumbnails()
# if FILER_ENABLE_LOGGING is on.
return JsonResponse(
{'error': 'failed to generate icons for file'},
status=500,
)
thumbnail = None
# Backwards compatibility: try to get specific icon size (32px)
# first. Then try medium icon size (they are already sorted),
# fallback to the first (smallest) configured icon.
for size in (['32']
+ filer_settings.FILER_ADMIN_ICON_SIZES[1::-1]):
try:
thumbnail = file_obj.icons[size]
break
except KeyError:
continue
data = {
'thumbnail': thumbnail,
'alt_text': '',
'label': str(file_obj),
'file_id': file_obj.pk,
}
# prepare preview thumbnail
if type(file_obj) == Image:
thumbnail_180_options = {
'size': (180, 180),
'crop': True,
'upscale': True,
}
thumbnail_180 = file_obj.file.get_thumbnail(
thumbnail_180_options)
data['thumbnail_180'] = thumbnail_180.url
data['original_image'] = file_obj.url
return JsonResponse(data)
else:
form_errors = '; '.join(['%s: %s' % (
field,
', '.join(errors)) for field, errors in list(
uploadform.errors.items())
])
raise UploadException(
"AJAX request not valid: form invalid '%s'" % (
form_errors,))
except UploadException as e:
return JsonResponse({'error': str(e)}, status=500) | [
"def",
"ajax_upload",
"(",
"request",
",",
"folder_id",
"=",
"None",
")",
":",
"folder",
"=",
"None",
"if",
"folder_id",
":",
"try",
":",
"# Get folder",
"folder",
"=",
"Folder",
".",
"objects",
".",
"get",
"(",
"pk",
"=",
"folder_id",
")",
"except",
"Folder",
".",
"DoesNotExist",
":",
"return",
"JsonResponse",
"(",
"{",
"'error'",
":",
"NO_FOLDER_ERROR",
"}",
")",
"# check permissions",
"if",
"folder",
"and",
"not",
"folder",
".",
"has_add_children_permission",
"(",
"request",
")",
":",
"return",
"JsonResponse",
"(",
"{",
"'error'",
":",
"NO_PERMISSIONS_FOR_FOLDER",
"}",
")",
"try",
":",
"if",
"len",
"(",
"request",
".",
"FILES",
")",
"==",
"1",
":",
"# dont check if request is ajax or not, just grab the file",
"upload",
",",
"filename",
",",
"is_raw",
"=",
"handle_request_files_upload",
"(",
"request",
")",
"else",
":",
"# else process the request as usual",
"upload",
",",
"filename",
",",
"is_raw",
"=",
"handle_upload",
"(",
"request",
")",
"# TODO: Deprecated/refactor",
"# Get clipboad",
"# clipboard = Clipboard.objects.get_or_create(user=request.user)[0]",
"# find the file type",
"for",
"filer_class",
"in",
"filer_settings",
".",
"FILER_FILE_MODELS",
":",
"FileSubClass",
"=",
"load_model",
"(",
"filer_class",
")",
"# TODO: What if there are more than one that qualify?",
"if",
"FileSubClass",
".",
"matches_file_type",
"(",
"filename",
",",
"upload",
",",
"request",
")",
":",
"FileForm",
"=",
"modelform_factory",
"(",
"model",
"=",
"FileSubClass",
",",
"fields",
"=",
"(",
"'original_filename'",
",",
"'owner'",
",",
"'file'",
")",
")",
"break",
"uploadform",
"=",
"FileForm",
"(",
"{",
"'original_filename'",
":",
"filename",
",",
"'owner'",
":",
"request",
".",
"user",
".",
"pk",
"}",
",",
"{",
"'file'",
":",
"upload",
"}",
")",
"if",
"uploadform",
".",
"is_valid",
"(",
")",
":",
"file_obj",
"=",
"uploadform",
".",
"save",
"(",
"commit",
"=",
"False",
")",
"# Enforce the FILER_IS_PUBLIC_DEFAULT",
"file_obj",
".",
"is_public",
"=",
"filer_settings",
".",
"FILER_IS_PUBLIC_DEFAULT",
"file_obj",
".",
"folder",
"=",
"folder",
"file_obj",
".",
"save",
"(",
")",
"# TODO: Deprecated/refactor",
"# clipboard_item = ClipboardItem(",
"# clipboard=clipboard, file=file_obj)",
"# clipboard_item.save()",
"# Try to generate thumbnails.",
"if",
"not",
"file_obj",
".",
"icons",
":",
"# There is no point to continue, as we can't generate",
"# thumbnails for this file. Usual reasons: bad format or",
"# filename.",
"file_obj",
".",
"delete",
"(",
")",
"# This would be logged in BaseImage._generate_thumbnails()",
"# if FILER_ENABLE_LOGGING is on.",
"return",
"JsonResponse",
"(",
"{",
"'error'",
":",
"'failed to generate icons for file'",
"}",
",",
"status",
"=",
"500",
",",
")",
"thumbnail",
"=",
"None",
"# Backwards compatibility: try to get specific icon size (32px)",
"# first. Then try medium icon size (they are already sorted),",
"# fallback to the first (smallest) configured icon.",
"for",
"size",
"in",
"(",
"[",
"'32'",
"]",
"+",
"filer_settings",
".",
"FILER_ADMIN_ICON_SIZES",
"[",
"1",
":",
":",
"-",
"1",
"]",
")",
":",
"try",
":",
"thumbnail",
"=",
"file_obj",
".",
"icons",
"[",
"size",
"]",
"break",
"except",
"KeyError",
":",
"continue",
"data",
"=",
"{",
"'thumbnail'",
":",
"thumbnail",
",",
"'alt_text'",
":",
"''",
",",
"'label'",
":",
"str",
"(",
"file_obj",
")",
",",
"'file_id'",
":",
"file_obj",
".",
"pk",
",",
"}",
"# prepare preview thumbnail",
"if",
"type",
"(",
"file_obj",
")",
"==",
"Image",
":",
"thumbnail_180_options",
"=",
"{",
"'size'",
":",
"(",
"180",
",",
"180",
")",
",",
"'crop'",
":",
"True",
",",
"'upscale'",
":",
"True",
",",
"}",
"thumbnail_180",
"=",
"file_obj",
".",
"file",
".",
"get_thumbnail",
"(",
"thumbnail_180_options",
")",
"data",
"[",
"'thumbnail_180'",
"]",
"=",
"thumbnail_180",
".",
"url",
"data",
"[",
"'original_image'",
"]",
"=",
"file_obj",
".",
"url",
"return",
"JsonResponse",
"(",
"data",
")",
"else",
":",
"form_errors",
"=",
"'; '",
".",
"join",
"(",
"[",
"'%s: %s'",
"%",
"(",
"field",
",",
"', '",
".",
"join",
"(",
"errors",
")",
")",
"for",
"field",
",",
"errors",
"in",
"list",
"(",
"uploadform",
".",
"errors",
".",
"items",
"(",
")",
")",
"]",
")",
"raise",
"UploadException",
"(",
"\"AJAX request not valid: form invalid '%s'\"",
"%",
"(",
"form_errors",
",",
")",
")",
"except",
"UploadException",
"as",
"e",
":",
"return",
"JsonResponse",
"(",
"{",
"'error'",
":",
"str",
"(",
"e",
")",
"}",
",",
"status",
"=",
"500",
")"
] | Receives an upload from the uploader. Receives only one file at a time. | [
"Receives",
"an",
"upload",
"from",
"the",
"uploader",
".",
"Receives",
"only",
"one",
"file",
"at",
"a",
"time",
"."
] | 946629087943d41eff290f07bfdf240b8853dd88 | https://github.com/divio/django-filer/blob/946629087943d41eff290f07bfdf240b8853dd88/filer/admin/clipboardadmin.py#L72-L174 |
227,666 | pyeve/cerberus | cerberus/validator.py | BareValidator.__store_config | def __store_config(self, args, kwargs):
""" Assign args to kwargs and store configuration. """
signature = (
'schema',
'ignore_none_values',
'allow_unknown',
'require_all',
'purge_unknown',
'purge_readonly',
)
for i, p in enumerate(signature[: len(args)]):
if p in kwargs:
raise TypeError("__init__ got multiple values for argument " "'%s'" % p)
else:
kwargs[p] = args[i]
self._config = kwargs
""" This dictionary holds the configuration arguments that were used to
initialize the :class:`Validator` instance except the
``error_handler``. """ | python | def __store_config(self, args, kwargs):
""" Assign args to kwargs and store configuration. """
signature = (
'schema',
'ignore_none_values',
'allow_unknown',
'require_all',
'purge_unknown',
'purge_readonly',
)
for i, p in enumerate(signature[: len(args)]):
if p in kwargs:
raise TypeError("__init__ got multiple values for argument " "'%s'" % p)
else:
kwargs[p] = args[i]
self._config = kwargs
""" This dictionary holds the configuration arguments that were used to
initialize the :class:`Validator` instance except the
``error_handler``. """ | [
"def",
"__store_config",
"(",
"self",
",",
"args",
",",
"kwargs",
")",
":",
"signature",
"=",
"(",
"'schema'",
",",
"'ignore_none_values'",
",",
"'allow_unknown'",
",",
"'require_all'",
",",
"'purge_unknown'",
",",
"'purge_readonly'",
",",
")",
"for",
"i",
",",
"p",
"in",
"enumerate",
"(",
"signature",
"[",
":",
"len",
"(",
"args",
")",
"]",
")",
":",
"if",
"p",
"in",
"kwargs",
":",
"raise",
"TypeError",
"(",
"\"__init__ got multiple values for argument \"",
"\"'%s'\"",
"%",
"p",
")",
"else",
":",
"kwargs",
"[",
"p",
"]",
"=",
"args",
"[",
"i",
"]",
"self",
".",
"_config",
"=",
"kwargs",
"\"\"\" This dictionary holds the configuration arguments that were used to\n initialize the :class:`Validator` instance except the\n ``error_handler``. \"\"\""
] | Assign args to kwargs and store configuration. | [
"Assign",
"args",
"to",
"kwargs",
"and",
"store",
"configuration",
"."
] | 688a67a4069e88042ed424bda7be0f4fa5fc3910 | https://github.com/pyeve/cerberus/blob/688a67a4069e88042ed424bda7be0f4fa5fc3910/cerberus/validator.py#L207-L225 |
227,667 | pyeve/cerberus | cerberus/validator.py | BareValidator._error | def _error(self, *args):
""" Creates and adds one or multiple errors.
:param args: Accepts different argument's signatures.
*1. Bulk addition of errors:*
- :term:`iterable` of
:class:`~cerberus.errors.ValidationError`-instances
The errors will be added to
:attr:`~cerberus.Validator._errors`.
*2. Custom error:*
- the invalid field's name
- the error message
A custom error containing the message will be created and
added to :attr:`~cerberus.Validator._errors`.
There will however be fewer information contained in the
error (no reference to the violated rule and its
constraint).
*3. Defined error:*
- the invalid field's name
- the error-reference, see :mod:`cerberus.errors`
- arbitrary, supplemental information about the error
A :class:`~cerberus.errors.ValidationError` instance will
be created and added to
:attr:`~cerberus.Validator._errors`.
"""
if len(args) == 1:
self._errors.extend(args[0])
self._errors.sort()
for error in args[0]:
self.document_error_tree.add(error)
self.schema_error_tree.add(error)
self.error_handler.emit(error)
elif len(args) == 2 and isinstance(args[1], _str_type):
self._error(args[0], errors.CUSTOM, args[1])
elif len(args) >= 2:
field = args[0]
code = args[1].code
rule = args[1].rule
info = args[2:]
document_path = self.document_path + (field,)
schema_path = self.schema_path
if code != errors.UNKNOWN_FIELD.code and rule is not None:
schema_path += (field, rule)
if not rule:
constraint = None
else:
field_definitions = self._resolve_rules_set(self.schema[field])
if rule == 'nullable':
constraint = field_definitions.get(rule, False)
elif rule == 'required':
constraint = field_definitions.get(rule, self.require_all)
if rule not in field_definitions:
schema_path = "__require_all__"
else:
constraint = field_definitions[rule]
value = self.document.get(field)
self.recent_error = errors.ValidationError(
document_path, schema_path, code, rule, constraint, value, info
)
self._error([self.recent_error]) | python | def _error(self, *args):
""" Creates and adds one or multiple errors.
:param args: Accepts different argument's signatures.
*1. Bulk addition of errors:*
- :term:`iterable` of
:class:`~cerberus.errors.ValidationError`-instances
The errors will be added to
:attr:`~cerberus.Validator._errors`.
*2. Custom error:*
- the invalid field's name
- the error message
A custom error containing the message will be created and
added to :attr:`~cerberus.Validator._errors`.
There will however be fewer information contained in the
error (no reference to the violated rule and its
constraint).
*3. Defined error:*
- the invalid field's name
- the error-reference, see :mod:`cerberus.errors`
- arbitrary, supplemental information about the error
A :class:`~cerberus.errors.ValidationError` instance will
be created and added to
:attr:`~cerberus.Validator._errors`.
"""
if len(args) == 1:
self._errors.extend(args[0])
self._errors.sort()
for error in args[0]:
self.document_error_tree.add(error)
self.schema_error_tree.add(error)
self.error_handler.emit(error)
elif len(args) == 2 and isinstance(args[1], _str_type):
self._error(args[0], errors.CUSTOM, args[1])
elif len(args) >= 2:
field = args[0]
code = args[1].code
rule = args[1].rule
info = args[2:]
document_path = self.document_path + (field,)
schema_path = self.schema_path
if code != errors.UNKNOWN_FIELD.code and rule is not None:
schema_path += (field, rule)
if not rule:
constraint = None
else:
field_definitions = self._resolve_rules_set(self.schema[field])
if rule == 'nullable':
constraint = field_definitions.get(rule, False)
elif rule == 'required':
constraint = field_definitions.get(rule, self.require_all)
if rule not in field_definitions:
schema_path = "__require_all__"
else:
constraint = field_definitions[rule]
value = self.document.get(field)
self.recent_error = errors.ValidationError(
document_path, schema_path, code, rule, constraint, value, info
)
self._error([self.recent_error]) | [
"def",
"_error",
"(",
"self",
",",
"*",
"args",
")",
":",
"if",
"len",
"(",
"args",
")",
"==",
"1",
":",
"self",
".",
"_errors",
".",
"extend",
"(",
"args",
"[",
"0",
"]",
")",
"self",
".",
"_errors",
".",
"sort",
"(",
")",
"for",
"error",
"in",
"args",
"[",
"0",
"]",
":",
"self",
".",
"document_error_tree",
".",
"add",
"(",
"error",
")",
"self",
".",
"schema_error_tree",
".",
"add",
"(",
"error",
")",
"self",
".",
"error_handler",
".",
"emit",
"(",
"error",
")",
"elif",
"len",
"(",
"args",
")",
"==",
"2",
"and",
"isinstance",
"(",
"args",
"[",
"1",
"]",
",",
"_str_type",
")",
":",
"self",
".",
"_error",
"(",
"args",
"[",
"0",
"]",
",",
"errors",
".",
"CUSTOM",
",",
"args",
"[",
"1",
"]",
")",
"elif",
"len",
"(",
"args",
")",
">=",
"2",
":",
"field",
"=",
"args",
"[",
"0",
"]",
"code",
"=",
"args",
"[",
"1",
"]",
".",
"code",
"rule",
"=",
"args",
"[",
"1",
"]",
".",
"rule",
"info",
"=",
"args",
"[",
"2",
":",
"]",
"document_path",
"=",
"self",
".",
"document_path",
"+",
"(",
"field",
",",
")",
"schema_path",
"=",
"self",
".",
"schema_path",
"if",
"code",
"!=",
"errors",
".",
"UNKNOWN_FIELD",
".",
"code",
"and",
"rule",
"is",
"not",
"None",
":",
"schema_path",
"+=",
"(",
"field",
",",
"rule",
")",
"if",
"not",
"rule",
":",
"constraint",
"=",
"None",
"else",
":",
"field_definitions",
"=",
"self",
".",
"_resolve_rules_set",
"(",
"self",
".",
"schema",
"[",
"field",
"]",
")",
"if",
"rule",
"==",
"'nullable'",
":",
"constraint",
"=",
"field_definitions",
".",
"get",
"(",
"rule",
",",
"False",
")",
"elif",
"rule",
"==",
"'required'",
":",
"constraint",
"=",
"field_definitions",
".",
"get",
"(",
"rule",
",",
"self",
".",
"require_all",
")",
"if",
"rule",
"not",
"in",
"field_definitions",
":",
"schema_path",
"=",
"\"__require_all__\"",
"else",
":",
"constraint",
"=",
"field_definitions",
"[",
"rule",
"]",
"value",
"=",
"self",
".",
"document",
".",
"get",
"(",
"field",
")",
"self",
".",
"recent_error",
"=",
"errors",
".",
"ValidationError",
"(",
"document_path",
",",
"schema_path",
",",
"code",
",",
"rule",
",",
"constraint",
",",
"value",
",",
"info",
")",
"self",
".",
"_error",
"(",
"[",
"self",
".",
"recent_error",
"]",
")"
] | Creates and adds one or multiple errors.
:param args: Accepts different argument's signatures.
*1. Bulk addition of errors:*
- :term:`iterable` of
:class:`~cerberus.errors.ValidationError`-instances
The errors will be added to
:attr:`~cerberus.Validator._errors`.
*2. Custom error:*
- the invalid field's name
- the error message
A custom error containing the message will be created and
added to :attr:`~cerberus.Validator._errors`.
There will however be fewer information contained in the
error (no reference to the violated rule and its
constraint).
*3. Defined error:*
- the invalid field's name
- the error-reference, see :mod:`cerberus.errors`
- arbitrary, supplemental information about the error
A :class:`~cerberus.errors.ValidationError` instance will
be created and added to
:attr:`~cerberus.Validator._errors`. | [
"Creates",
"and",
"adds",
"one",
"or",
"multiple",
"errors",
"."
] | 688a67a4069e88042ed424bda7be0f4fa5fc3910 | https://github.com/pyeve/cerberus/blob/688a67a4069e88042ed424bda7be0f4fa5fc3910/cerberus/validator.py#L232-L308 |
227,668 | pyeve/cerberus | cerberus/validator.py | BareValidator.__validate_definitions | def __validate_definitions(self, definitions, field):
""" Validate a field's value against its defined rules. """
def validate_rule(rule):
validator = self.__get_rule_handler('validate', rule)
return validator(definitions.get(rule, None), field, value)
definitions = self._resolve_rules_set(definitions)
value = self.document[field]
rules_queue = [
x
for x in self.priority_validations
if x in definitions or x in self.mandatory_validations
]
rules_queue.extend(
x for x in self.mandatory_validations if x not in rules_queue
)
rules_queue.extend(
x
for x in definitions
if x not in rules_queue
and x not in self.normalization_rules
and x not in ('allow_unknown', 'require_all', 'meta', 'required')
)
self._remaining_rules = rules_queue
while self._remaining_rules:
rule = self._remaining_rules.pop(0)
try:
result = validate_rule(rule)
# TODO remove on next breaking release
if result:
break
except _SchemaRuleTypeError:
break
self._drop_remaining_rules() | python | def __validate_definitions(self, definitions, field):
""" Validate a field's value against its defined rules. """
def validate_rule(rule):
validator = self.__get_rule_handler('validate', rule)
return validator(definitions.get(rule, None), field, value)
definitions = self._resolve_rules_set(definitions)
value = self.document[field]
rules_queue = [
x
for x in self.priority_validations
if x in definitions or x in self.mandatory_validations
]
rules_queue.extend(
x for x in self.mandatory_validations if x not in rules_queue
)
rules_queue.extend(
x
for x in definitions
if x not in rules_queue
and x not in self.normalization_rules
and x not in ('allow_unknown', 'require_all', 'meta', 'required')
)
self._remaining_rules = rules_queue
while self._remaining_rules:
rule = self._remaining_rules.pop(0)
try:
result = validate_rule(rule)
# TODO remove on next breaking release
if result:
break
except _SchemaRuleTypeError:
break
self._drop_remaining_rules() | [
"def",
"__validate_definitions",
"(",
"self",
",",
"definitions",
",",
"field",
")",
":",
"def",
"validate_rule",
"(",
"rule",
")",
":",
"validator",
"=",
"self",
".",
"__get_rule_handler",
"(",
"'validate'",
",",
"rule",
")",
"return",
"validator",
"(",
"definitions",
".",
"get",
"(",
"rule",
",",
"None",
")",
",",
"field",
",",
"value",
")",
"definitions",
"=",
"self",
".",
"_resolve_rules_set",
"(",
"definitions",
")",
"value",
"=",
"self",
".",
"document",
"[",
"field",
"]",
"rules_queue",
"=",
"[",
"x",
"for",
"x",
"in",
"self",
".",
"priority_validations",
"if",
"x",
"in",
"definitions",
"or",
"x",
"in",
"self",
".",
"mandatory_validations",
"]",
"rules_queue",
".",
"extend",
"(",
"x",
"for",
"x",
"in",
"self",
".",
"mandatory_validations",
"if",
"x",
"not",
"in",
"rules_queue",
")",
"rules_queue",
".",
"extend",
"(",
"x",
"for",
"x",
"in",
"definitions",
"if",
"x",
"not",
"in",
"rules_queue",
"and",
"x",
"not",
"in",
"self",
".",
"normalization_rules",
"and",
"x",
"not",
"in",
"(",
"'allow_unknown'",
",",
"'require_all'",
",",
"'meta'",
",",
"'required'",
")",
")",
"self",
".",
"_remaining_rules",
"=",
"rules_queue",
"while",
"self",
".",
"_remaining_rules",
":",
"rule",
"=",
"self",
".",
"_remaining_rules",
".",
"pop",
"(",
"0",
")",
"try",
":",
"result",
"=",
"validate_rule",
"(",
"rule",
")",
"# TODO remove on next breaking release",
"if",
"result",
":",
"break",
"except",
"_SchemaRuleTypeError",
":",
"break",
"self",
".",
"_drop_remaining_rules",
"(",
")"
] | Validate a field's value against its defined rules. | [
"Validate",
"a",
"field",
"s",
"value",
"against",
"its",
"defined",
"rules",
"."
] | 688a67a4069e88042ed424bda7be0f4fa5fc3910 | https://github.com/pyeve/cerberus/blob/688a67a4069e88042ed424bda7be0f4fa5fc3910/cerberus/validator.py#L1036-L1073 |
227,669 | mobolic/facebook-sdk | facebook/__init__.py | get_user_from_cookie | def get_user_from_cookie(cookies, app_id, app_secret):
"""Parses the cookie set by the official Facebook JavaScript SDK.
cookies should be a dictionary-like object mapping cookie names to
cookie values.
If the user is logged in via Facebook, we return a dictionary with
the keys "uid" and "access_token". The former is the user's
Facebook ID, and the latter can be used to make authenticated
requests to the Graph API. If the user is not logged in, we
return None.
Read more about Facebook authentication at
https://developers.facebook.com/docs/facebook-login.
"""
cookie = cookies.get("fbsr_" + app_id, "")
if not cookie:
return None
parsed_request = parse_signed_request(cookie, app_secret)
if not parsed_request:
return None
try:
result = GraphAPI().get_access_token_from_code(
parsed_request["code"], "", app_id, app_secret
)
except GraphAPIError:
return None
result["uid"] = parsed_request["user_id"]
return result | python | def get_user_from_cookie(cookies, app_id, app_secret):
"""Parses the cookie set by the official Facebook JavaScript SDK.
cookies should be a dictionary-like object mapping cookie names to
cookie values.
If the user is logged in via Facebook, we return a dictionary with
the keys "uid" and "access_token". The former is the user's
Facebook ID, and the latter can be used to make authenticated
requests to the Graph API. If the user is not logged in, we
return None.
Read more about Facebook authentication at
https://developers.facebook.com/docs/facebook-login.
"""
cookie = cookies.get("fbsr_" + app_id, "")
if not cookie:
return None
parsed_request = parse_signed_request(cookie, app_secret)
if not parsed_request:
return None
try:
result = GraphAPI().get_access_token_from_code(
parsed_request["code"], "", app_id, app_secret
)
except GraphAPIError:
return None
result["uid"] = parsed_request["user_id"]
return result | [
"def",
"get_user_from_cookie",
"(",
"cookies",
",",
"app_id",
",",
"app_secret",
")",
":",
"cookie",
"=",
"cookies",
".",
"get",
"(",
"\"fbsr_\"",
"+",
"app_id",
",",
"\"\"",
")",
"if",
"not",
"cookie",
":",
"return",
"None",
"parsed_request",
"=",
"parse_signed_request",
"(",
"cookie",
",",
"app_secret",
")",
"if",
"not",
"parsed_request",
":",
"return",
"None",
"try",
":",
"result",
"=",
"GraphAPI",
"(",
")",
".",
"get_access_token_from_code",
"(",
"parsed_request",
"[",
"\"code\"",
"]",
",",
"\"\"",
",",
"app_id",
",",
"app_secret",
")",
"except",
"GraphAPIError",
":",
"return",
"None",
"result",
"[",
"\"uid\"",
"]",
"=",
"parsed_request",
"[",
"\"user_id\"",
"]",
"return",
"result"
] | Parses the cookie set by the official Facebook JavaScript SDK.
cookies should be a dictionary-like object mapping cookie names to
cookie values.
If the user is logged in via Facebook, we return a dictionary with
the keys "uid" and "access_token". The former is the user's
Facebook ID, and the latter can be used to make authenticated
requests to the Graph API. If the user is not logged in, we
return None.
Read more about Facebook authentication at
https://developers.facebook.com/docs/facebook-login. | [
"Parses",
"the",
"cookie",
"set",
"by",
"the",
"official",
"Facebook",
"JavaScript",
"SDK",
"."
] | 65ff582e77f7ed68b6e9643a7490e5dee2a1031b | https://github.com/mobolic/facebook-sdk/blob/65ff582e77f7ed68b6e9643a7490e5dee2a1031b/facebook/__init__.py#L443-L472 |
227,670 | mobolic/facebook-sdk | facebook/__init__.py | parse_signed_request | def parse_signed_request(signed_request, app_secret):
""" Return dictionary with signed request data.
We return a dictionary containing the information in the
signed_request. This includes a user_id if the user has authorised
your application, as well as any information requested.
If the signed_request is malformed or corrupted, False is returned.
"""
try:
encoded_sig, payload = map(str, signed_request.split(".", 1))
sig = base64.urlsafe_b64decode(
encoded_sig + "=" * ((4 - len(encoded_sig) % 4) % 4)
)
data = base64.urlsafe_b64decode(
payload + "=" * ((4 - len(payload) % 4) % 4)
)
except IndexError:
# Signed request was malformed.
return False
except TypeError:
# Signed request had a corrupted payload.
return False
except binascii.Error:
# Signed request had a corrupted payload.
return False
data = json.loads(data.decode("ascii"))
if data.get("algorithm", "").upper() != "HMAC-SHA256":
return False
# HMAC can only handle ascii (byte) strings
# https://bugs.python.org/issue5285
app_secret = app_secret.encode("ascii")
payload = payload.encode("ascii")
expected_sig = hmac.new(
app_secret, msg=payload, digestmod=hashlib.sha256
).digest()
if sig != expected_sig:
return False
return data | python | def parse_signed_request(signed_request, app_secret):
""" Return dictionary with signed request data.
We return a dictionary containing the information in the
signed_request. This includes a user_id if the user has authorised
your application, as well as any information requested.
If the signed_request is malformed or corrupted, False is returned.
"""
try:
encoded_sig, payload = map(str, signed_request.split(".", 1))
sig = base64.urlsafe_b64decode(
encoded_sig + "=" * ((4 - len(encoded_sig) % 4) % 4)
)
data = base64.urlsafe_b64decode(
payload + "=" * ((4 - len(payload) % 4) % 4)
)
except IndexError:
# Signed request was malformed.
return False
except TypeError:
# Signed request had a corrupted payload.
return False
except binascii.Error:
# Signed request had a corrupted payload.
return False
data = json.loads(data.decode("ascii"))
if data.get("algorithm", "").upper() != "HMAC-SHA256":
return False
# HMAC can only handle ascii (byte) strings
# https://bugs.python.org/issue5285
app_secret = app_secret.encode("ascii")
payload = payload.encode("ascii")
expected_sig = hmac.new(
app_secret, msg=payload, digestmod=hashlib.sha256
).digest()
if sig != expected_sig:
return False
return data | [
"def",
"parse_signed_request",
"(",
"signed_request",
",",
"app_secret",
")",
":",
"try",
":",
"encoded_sig",
",",
"payload",
"=",
"map",
"(",
"str",
",",
"signed_request",
".",
"split",
"(",
"\".\"",
",",
"1",
")",
")",
"sig",
"=",
"base64",
".",
"urlsafe_b64decode",
"(",
"encoded_sig",
"+",
"\"=\"",
"*",
"(",
"(",
"4",
"-",
"len",
"(",
"encoded_sig",
")",
"%",
"4",
")",
"%",
"4",
")",
")",
"data",
"=",
"base64",
".",
"urlsafe_b64decode",
"(",
"payload",
"+",
"\"=\"",
"*",
"(",
"(",
"4",
"-",
"len",
"(",
"payload",
")",
"%",
"4",
")",
"%",
"4",
")",
")",
"except",
"IndexError",
":",
"# Signed request was malformed.",
"return",
"False",
"except",
"TypeError",
":",
"# Signed request had a corrupted payload.",
"return",
"False",
"except",
"binascii",
".",
"Error",
":",
"# Signed request had a corrupted payload.",
"return",
"False",
"data",
"=",
"json",
".",
"loads",
"(",
"data",
".",
"decode",
"(",
"\"ascii\"",
")",
")",
"if",
"data",
".",
"get",
"(",
"\"algorithm\"",
",",
"\"\"",
")",
".",
"upper",
"(",
")",
"!=",
"\"HMAC-SHA256\"",
":",
"return",
"False",
"# HMAC can only handle ascii (byte) strings",
"# https://bugs.python.org/issue5285",
"app_secret",
"=",
"app_secret",
".",
"encode",
"(",
"\"ascii\"",
")",
"payload",
"=",
"payload",
".",
"encode",
"(",
"\"ascii\"",
")",
"expected_sig",
"=",
"hmac",
".",
"new",
"(",
"app_secret",
",",
"msg",
"=",
"payload",
",",
"digestmod",
"=",
"hashlib",
".",
"sha256",
")",
".",
"digest",
"(",
")",
"if",
"sig",
"!=",
"expected_sig",
":",
"return",
"False",
"return",
"data"
] | Return dictionary with signed request data.
We return a dictionary containing the information in the
signed_request. This includes a user_id if the user has authorised
your application, as well as any information requested.
If the signed_request is malformed or corrupted, False is returned. | [
"Return",
"dictionary",
"with",
"signed",
"request",
"data",
"."
] | 65ff582e77f7ed68b6e9643a7490e5dee2a1031b | https://github.com/mobolic/facebook-sdk/blob/65ff582e77f7ed68b6e9643a7490e5dee2a1031b/facebook/__init__.py#L475-L519 |
227,671 | mobolic/facebook-sdk | facebook/__init__.py | GraphAPI.get_permissions | def get_permissions(self, user_id):
"""Fetches the permissions object from the graph."""
response = self.request(
"{0}/{1}/permissions".format(self.version, user_id), {}
)["data"]
return {x["permission"] for x in response if x["status"] == "granted"} | python | def get_permissions(self, user_id):
"""Fetches the permissions object from the graph."""
response = self.request(
"{0}/{1}/permissions".format(self.version, user_id), {}
)["data"]
return {x["permission"] for x in response if x["status"] == "granted"} | [
"def",
"get_permissions",
"(",
"self",
",",
"user_id",
")",
":",
"response",
"=",
"self",
".",
"request",
"(",
"\"{0}/{1}/permissions\"",
".",
"format",
"(",
"self",
".",
"version",
",",
"user_id",
")",
",",
"{",
"}",
")",
"[",
"\"data\"",
"]",
"return",
"{",
"x",
"[",
"\"permission\"",
"]",
"for",
"x",
"in",
"response",
"if",
"x",
"[",
"\"status\"",
"]",
"==",
"\"granted\"",
"}"
] | Fetches the permissions object from the graph. | [
"Fetches",
"the",
"permissions",
"object",
"from",
"the",
"graph",
"."
] | 65ff582e77f7ed68b6e9643a7490e5dee2a1031b | https://github.com/mobolic/facebook-sdk/blob/65ff582e77f7ed68b6e9643a7490e5dee2a1031b/facebook/__init__.py#L126-L131 |
227,672 | mobolic/facebook-sdk | facebook/__init__.py | GraphAPI.get_object | def get_object(self, id, **args):
"""Fetches the given object from the graph."""
return self.request("{0}/{1}".format(self.version, id), args) | python | def get_object(self, id, **args):
"""Fetches the given object from the graph."""
return self.request("{0}/{1}".format(self.version, id), args) | [
"def",
"get_object",
"(",
"self",
",",
"id",
",",
"*",
"*",
"args",
")",
":",
"return",
"self",
".",
"request",
"(",
"\"{0}/{1}\"",
".",
"format",
"(",
"self",
".",
"version",
",",
"id",
")",
",",
"args",
")"
] | Fetches the given object from the graph. | [
"Fetches",
"the",
"given",
"object",
"from",
"the",
"graph",
"."
] | 65ff582e77f7ed68b6e9643a7490e5dee2a1031b | https://github.com/mobolic/facebook-sdk/blob/65ff582e77f7ed68b6e9643a7490e5dee2a1031b/facebook/__init__.py#L133-L135 |
227,673 | mobolic/facebook-sdk | facebook/__init__.py | GraphAPI.get_objects | def get_objects(self, ids, **args):
"""Fetches all of the given object from the graph.
We return a map from ID to object. If any of the IDs are
invalid, we raise an exception.
"""
args["ids"] = ",".join(ids)
return self.request(self.version + "/", args) | python | def get_objects(self, ids, **args):
"""Fetches all of the given object from the graph.
We return a map from ID to object. If any of the IDs are
invalid, we raise an exception.
"""
args["ids"] = ",".join(ids)
return self.request(self.version + "/", args) | [
"def",
"get_objects",
"(",
"self",
",",
"ids",
",",
"*",
"*",
"args",
")",
":",
"args",
"[",
"\"ids\"",
"]",
"=",
"\",\"",
".",
"join",
"(",
"ids",
")",
"return",
"self",
".",
"request",
"(",
"self",
".",
"version",
"+",
"\"/\"",
",",
"args",
")"
] | Fetches all of the given object from the graph.
We return a map from ID to object. If any of the IDs are
invalid, we raise an exception. | [
"Fetches",
"all",
"of",
"the",
"given",
"object",
"from",
"the",
"graph",
"."
] | 65ff582e77f7ed68b6e9643a7490e5dee2a1031b | https://github.com/mobolic/facebook-sdk/blob/65ff582e77f7ed68b6e9643a7490e5dee2a1031b/facebook/__init__.py#L137-L144 |
227,674 | mobolic/facebook-sdk | facebook/__init__.py | GraphAPI.get_connections | def get_connections(self, id, connection_name, **args):
"""Fetches the connections for given object."""
return self.request(
"{0}/{1}/{2}".format(self.version, id, connection_name), args
) | python | def get_connections(self, id, connection_name, **args):
"""Fetches the connections for given object."""
return self.request(
"{0}/{1}/{2}".format(self.version, id, connection_name), args
) | [
"def",
"get_connections",
"(",
"self",
",",
"id",
",",
"connection_name",
",",
"*",
"*",
"args",
")",
":",
"return",
"self",
".",
"request",
"(",
"\"{0}/{1}/{2}\"",
".",
"format",
"(",
"self",
".",
"version",
",",
"id",
",",
"connection_name",
")",
",",
"args",
")"
] | Fetches the connections for given object. | [
"Fetches",
"the",
"connections",
"for",
"given",
"object",
"."
] | 65ff582e77f7ed68b6e9643a7490e5dee2a1031b | https://github.com/mobolic/facebook-sdk/blob/65ff582e77f7ed68b6e9643a7490e5dee2a1031b/facebook/__init__.py#L156-L160 |
227,675 | mobolic/facebook-sdk | facebook/__init__.py | GraphAPI.get_all_connections | def get_all_connections(self, id, connection_name, **args):
"""Get all pages from a get_connections call
This will iterate over all pages returned by a get_connections call
and yield the individual items.
"""
while True:
page = self.get_connections(id, connection_name, **args)
for post in page["data"]:
yield post
next = page.get("paging", {}).get("next")
if not next:
return
args = parse_qs(urlparse(next).query)
del args["access_token"] | python | def get_all_connections(self, id, connection_name, **args):
"""Get all pages from a get_connections call
This will iterate over all pages returned by a get_connections call
and yield the individual items.
"""
while True:
page = self.get_connections(id, connection_name, **args)
for post in page["data"]:
yield post
next = page.get("paging", {}).get("next")
if not next:
return
args = parse_qs(urlparse(next).query)
del args["access_token"] | [
"def",
"get_all_connections",
"(",
"self",
",",
"id",
",",
"connection_name",
",",
"*",
"*",
"args",
")",
":",
"while",
"True",
":",
"page",
"=",
"self",
".",
"get_connections",
"(",
"id",
",",
"connection_name",
",",
"*",
"*",
"args",
")",
"for",
"post",
"in",
"page",
"[",
"\"data\"",
"]",
":",
"yield",
"post",
"next",
"=",
"page",
".",
"get",
"(",
"\"paging\"",
",",
"{",
"}",
")",
".",
"get",
"(",
"\"next\"",
")",
"if",
"not",
"next",
":",
"return",
"args",
"=",
"parse_qs",
"(",
"urlparse",
"(",
"next",
")",
".",
"query",
")",
"del",
"args",
"[",
"\"access_token\"",
"]"
] | Get all pages from a get_connections call
This will iterate over all pages returned by a get_connections call
and yield the individual items. | [
"Get",
"all",
"pages",
"from",
"a",
"get_connections",
"call"
] | 65ff582e77f7ed68b6e9643a7490e5dee2a1031b | https://github.com/mobolic/facebook-sdk/blob/65ff582e77f7ed68b6e9643a7490e5dee2a1031b/facebook/__init__.py#L162-L176 |
227,676 | mobolic/facebook-sdk | facebook/__init__.py | GraphAPI.put_object | def put_object(self, parent_object, connection_name, **data):
"""Writes the given object to the graph, connected to the given parent.
For example,
graph.put_object("me", "feed", message="Hello, world")
writes "Hello, world" to the active user's wall. Likewise, this
will comment on the first post of the active user's feed:
feed = graph.get_connections("me", "feed")
post = feed["data"][0]
graph.put_object(post["id"], "comments", message="First!")
Certain operations require extended permissions. See
https://developers.facebook.com/docs/facebook-login/permissions
for details about permissions.
"""
assert self.access_token, "Write operations require an access token"
return self.request(
"{0}/{1}/{2}".format(self.version, parent_object, connection_name),
post_args=data,
method="POST",
) | python | def put_object(self, parent_object, connection_name, **data):
"""Writes the given object to the graph, connected to the given parent.
For example,
graph.put_object("me", "feed", message="Hello, world")
writes "Hello, world" to the active user's wall. Likewise, this
will comment on the first post of the active user's feed:
feed = graph.get_connections("me", "feed")
post = feed["data"][0]
graph.put_object(post["id"], "comments", message="First!")
Certain operations require extended permissions. See
https://developers.facebook.com/docs/facebook-login/permissions
for details about permissions.
"""
assert self.access_token, "Write operations require an access token"
return self.request(
"{0}/{1}/{2}".format(self.version, parent_object, connection_name),
post_args=data,
method="POST",
) | [
"def",
"put_object",
"(",
"self",
",",
"parent_object",
",",
"connection_name",
",",
"*",
"*",
"data",
")",
":",
"assert",
"self",
".",
"access_token",
",",
"\"Write operations require an access token\"",
"return",
"self",
".",
"request",
"(",
"\"{0}/{1}/{2}\"",
".",
"format",
"(",
"self",
".",
"version",
",",
"parent_object",
",",
"connection_name",
")",
",",
"post_args",
"=",
"data",
",",
"method",
"=",
"\"POST\"",
",",
")"
] | Writes the given object to the graph, connected to the given parent.
For example,
graph.put_object("me", "feed", message="Hello, world")
writes "Hello, world" to the active user's wall. Likewise, this
will comment on the first post of the active user's feed:
feed = graph.get_connections("me", "feed")
post = feed["data"][0]
graph.put_object(post["id"], "comments", message="First!")
Certain operations require extended permissions. See
https://developers.facebook.com/docs/facebook-login/permissions
for details about permissions. | [
"Writes",
"the",
"given",
"object",
"to",
"the",
"graph",
"connected",
"to",
"the",
"given",
"parent",
"."
] | 65ff582e77f7ed68b6e9643a7490e5dee2a1031b | https://github.com/mobolic/facebook-sdk/blob/65ff582e77f7ed68b6e9643a7490e5dee2a1031b/facebook/__init__.py#L178-L202 |
227,677 | mobolic/facebook-sdk | facebook/__init__.py | GraphAPI.delete_request | def delete_request(self, user_id, request_id):
"""Deletes the Request with the given ID for the given user."""
return self.request(
"{0}_{1}".format(request_id, user_id), method="DELETE"
) | python | def delete_request(self, user_id, request_id):
"""Deletes the Request with the given ID for the given user."""
return self.request(
"{0}_{1}".format(request_id, user_id), method="DELETE"
) | [
"def",
"delete_request",
"(",
"self",
",",
"user_id",
",",
"request_id",
")",
":",
"return",
"self",
".",
"request",
"(",
"\"{0}_{1}\"",
".",
"format",
"(",
"request_id",
",",
"user_id",
")",
",",
"method",
"=",
"\"DELETE\"",
")"
] | Deletes the Request with the given ID for the given user. | [
"Deletes",
"the",
"Request",
"with",
"the",
"given",
"ID",
"for",
"the",
"given",
"user",
"."
] | 65ff582e77f7ed68b6e9643a7490e5dee2a1031b | https://github.com/mobolic/facebook-sdk/blob/65ff582e77f7ed68b6e9643a7490e5dee2a1031b/facebook/__init__.py#L218-L222 |
227,678 | mobolic/facebook-sdk | facebook/__init__.py | GraphAPI.get_version | def get_version(self):
"""Fetches the current version number of the Graph API being used."""
args = {"access_token": self.access_token}
try:
response = self.session.request(
"GET",
FACEBOOK_GRAPH_URL + self.version + "/me",
params=args,
timeout=self.timeout,
proxies=self.proxies,
)
except requests.HTTPError as e:
response = json.loads(e.read())
raise GraphAPIError(response)
try:
headers = response.headers
version = headers["facebook-api-version"].replace("v", "")
return str(version)
except Exception:
raise GraphAPIError("API version number not available") | python | def get_version(self):
"""Fetches the current version number of the Graph API being used."""
args = {"access_token": self.access_token}
try:
response = self.session.request(
"GET",
FACEBOOK_GRAPH_URL + self.version + "/me",
params=args,
timeout=self.timeout,
proxies=self.proxies,
)
except requests.HTTPError as e:
response = json.loads(e.read())
raise GraphAPIError(response)
try:
headers = response.headers
version = headers["facebook-api-version"].replace("v", "")
return str(version)
except Exception:
raise GraphAPIError("API version number not available") | [
"def",
"get_version",
"(",
"self",
")",
":",
"args",
"=",
"{",
"\"access_token\"",
":",
"self",
".",
"access_token",
"}",
"try",
":",
"response",
"=",
"self",
".",
"session",
".",
"request",
"(",
"\"GET\"",
",",
"FACEBOOK_GRAPH_URL",
"+",
"self",
".",
"version",
"+",
"\"/me\"",
",",
"params",
"=",
"args",
",",
"timeout",
"=",
"self",
".",
"timeout",
",",
"proxies",
"=",
"self",
".",
"proxies",
",",
")",
"except",
"requests",
".",
"HTTPError",
"as",
"e",
":",
"response",
"=",
"json",
".",
"loads",
"(",
"e",
".",
"read",
"(",
")",
")",
"raise",
"GraphAPIError",
"(",
"response",
")",
"try",
":",
"headers",
"=",
"response",
".",
"headers",
"version",
"=",
"headers",
"[",
"\"facebook-api-version\"",
"]",
".",
"replace",
"(",
"\"v\"",
",",
"\"\"",
")",
"return",
"str",
"(",
"version",
")",
"except",
"Exception",
":",
"raise",
"GraphAPIError",
"(",
"\"API version number not available\"",
")"
] | Fetches the current version number of the Graph API being used. | [
"Fetches",
"the",
"current",
"version",
"number",
"of",
"the",
"Graph",
"API",
"being",
"used",
"."
] | 65ff582e77f7ed68b6e9643a7490e5dee2a1031b | https://github.com/mobolic/facebook-sdk/blob/65ff582e77f7ed68b6e9643a7490e5dee2a1031b/facebook/__init__.py#L239-L259 |
227,679 | mobolic/facebook-sdk | facebook/__init__.py | GraphAPI.request | def request(
self, path, args=None, post_args=None, files=None, method=None
):
"""Fetches the given path in the Graph API.
We translate args to a valid query string. If post_args is
given, we send a POST request to the given path with the given
arguments.
"""
if args is None:
args = dict()
if post_args is not None:
method = "POST"
# Add `access_token` to post_args or args if it has not already been
# included.
if self.access_token:
# If post_args exists, we assume that args either does not exists
# or it does not need `access_token`.
if post_args and "access_token" not in post_args:
post_args["access_token"] = self.access_token
elif "access_token" not in args:
args["access_token"] = self.access_token
try:
response = self.session.request(
method or "GET",
FACEBOOK_GRAPH_URL + path,
timeout=self.timeout,
params=args,
data=post_args,
proxies=self.proxies,
files=files,
)
except requests.HTTPError as e:
response = json.loads(e.read())
raise GraphAPIError(response)
headers = response.headers
if "json" in headers["content-type"]:
result = response.json()
elif "image/" in headers["content-type"]:
mimetype = headers["content-type"]
result = {
"data": response.content,
"mime-type": mimetype,
"url": response.url,
}
elif "access_token" in parse_qs(response.text):
query_str = parse_qs(response.text)
if "access_token" in query_str:
result = {"access_token": query_str["access_token"][0]}
if "expires" in query_str:
result["expires"] = query_str["expires"][0]
else:
raise GraphAPIError(response.json())
else:
raise GraphAPIError("Maintype was not text, image, or querystring")
if result and isinstance(result, dict) and result.get("error"):
raise GraphAPIError(result)
return result | python | def request(
self, path, args=None, post_args=None, files=None, method=None
):
"""Fetches the given path in the Graph API.
We translate args to a valid query string. If post_args is
given, we send a POST request to the given path with the given
arguments.
"""
if args is None:
args = dict()
if post_args is not None:
method = "POST"
# Add `access_token` to post_args or args if it has not already been
# included.
if self.access_token:
# If post_args exists, we assume that args either does not exists
# or it does not need `access_token`.
if post_args and "access_token" not in post_args:
post_args["access_token"] = self.access_token
elif "access_token" not in args:
args["access_token"] = self.access_token
try:
response = self.session.request(
method or "GET",
FACEBOOK_GRAPH_URL + path,
timeout=self.timeout,
params=args,
data=post_args,
proxies=self.proxies,
files=files,
)
except requests.HTTPError as e:
response = json.loads(e.read())
raise GraphAPIError(response)
headers = response.headers
if "json" in headers["content-type"]:
result = response.json()
elif "image/" in headers["content-type"]:
mimetype = headers["content-type"]
result = {
"data": response.content,
"mime-type": mimetype,
"url": response.url,
}
elif "access_token" in parse_qs(response.text):
query_str = parse_qs(response.text)
if "access_token" in query_str:
result = {"access_token": query_str["access_token"][0]}
if "expires" in query_str:
result["expires"] = query_str["expires"][0]
else:
raise GraphAPIError(response.json())
else:
raise GraphAPIError("Maintype was not text, image, or querystring")
if result and isinstance(result, dict) and result.get("error"):
raise GraphAPIError(result)
return result | [
"def",
"request",
"(",
"self",
",",
"path",
",",
"args",
"=",
"None",
",",
"post_args",
"=",
"None",
",",
"files",
"=",
"None",
",",
"method",
"=",
"None",
")",
":",
"if",
"args",
"is",
"None",
":",
"args",
"=",
"dict",
"(",
")",
"if",
"post_args",
"is",
"not",
"None",
":",
"method",
"=",
"\"POST\"",
"# Add `access_token` to post_args or args if it has not already been",
"# included.",
"if",
"self",
".",
"access_token",
":",
"# If post_args exists, we assume that args either does not exists",
"# or it does not need `access_token`.",
"if",
"post_args",
"and",
"\"access_token\"",
"not",
"in",
"post_args",
":",
"post_args",
"[",
"\"access_token\"",
"]",
"=",
"self",
".",
"access_token",
"elif",
"\"access_token\"",
"not",
"in",
"args",
":",
"args",
"[",
"\"access_token\"",
"]",
"=",
"self",
".",
"access_token",
"try",
":",
"response",
"=",
"self",
".",
"session",
".",
"request",
"(",
"method",
"or",
"\"GET\"",
",",
"FACEBOOK_GRAPH_URL",
"+",
"path",
",",
"timeout",
"=",
"self",
".",
"timeout",
",",
"params",
"=",
"args",
",",
"data",
"=",
"post_args",
",",
"proxies",
"=",
"self",
".",
"proxies",
",",
"files",
"=",
"files",
",",
")",
"except",
"requests",
".",
"HTTPError",
"as",
"e",
":",
"response",
"=",
"json",
".",
"loads",
"(",
"e",
".",
"read",
"(",
")",
")",
"raise",
"GraphAPIError",
"(",
"response",
")",
"headers",
"=",
"response",
".",
"headers",
"if",
"\"json\"",
"in",
"headers",
"[",
"\"content-type\"",
"]",
":",
"result",
"=",
"response",
".",
"json",
"(",
")",
"elif",
"\"image/\"",
"in",
"headers",
"[",
"\"content-type\"",
"]",
":",
"mimetype",
"=",
"headers",
"[",
"\"content-type\"",
"]",
"result",
"=",
"{",
"\"data\"",
":",
"response",
".",
"content",
",",
"\"mime-type\"",
":",
"mimetype",
",",
"\"url\"",
":",
"response",
".",
"url",
",",
"}",
"elif",
"\"access_token\"",
"in",
"parse_qs",
"(",
"response",
".",
"text",
")",
":",
"query_str",
"=",
"parse_qs",
"(",
"response",
".",
"text",
")",
"if",
"\"access_token\"",
"in",
"query_str",
":",
"result",
"=",
"{",
"\"access_token\"",
":",
"query_str",
"[",
"\"access_token\"",
"]",
"[",
"0",
"]",
"}",
"if",
"\"expires\"",
"in",
"query_str",
":",
"result",
"[",
"\"expires\"",
"]",
"=",
"query_str",
"[",
"\"expires\"",
"]",
"[",
"0",
"]",
"else",
":",
"raise",
"GraphAPIError",
"(",
"response",
".",
"json",
"(",
")",
")",
"else",
":",
"raise",
"GraphAPIError",
"(",
"\"Maintype was not text, image, or querystring\"",
")",
"if",
"result",
"and",
"isinstance",
"(",
"result",
",",
"dict",
")",
"and",
"result",
".",
"get",
"(",
"\"error\"",
")",
":",
"raise",
"GraphAPIError",
"(",
"result",
")",
"return",
"result"
] | Fetches the given path in the Graph API.
We translate args to a valid query string. If post_args is
given, we send a POST request to the given path with the given
arguments. | [
"Fetches",
"the",
"given",
"path",
"in",
"the",
"Graph",
"API",
"."
] | 65ff582e77f7ed68b6e9643a7490e5dee2a1031b | https://github.com/mobolic/facebook-sdk/blob/65ff582e77f7ed68b6e9643a7490e5dee2a1031b/facebook/__init__.py#L261-L323 |
227,680 | mobolic/facebook-sdk | facebook/__init__.py | GraphAPI.get_access_token_from_code | def get_access_token_from_code(
self, code, redirect_uri, app_id, app_secret
):
"""Get an access token from the "code" returned from an OAuth dialog.
Returns a dict containing the user-specific access token and its
expiration date (if applicable).
"""
args = {
"code": code,
"redirect_uri": redirect_uri,
"client_id": app_id,
"client_secret": app_secret,
}
return self.request(
"{0}/oauth/access_token".format(self.version), args
) | python | def get_access_token_from_code(
self, code, redirect_uri, app_id, app_secret
):
"""Get an access token from the "code" returned from an OAuth dialog.
Returns a dict containing the user-specific access token and its
expiration date (if applicable).
"""
args = {
"code": code,
"redirect_uri": redirect_uri,
"client_id": app_id,
"client_secret": app_secret,
}
return self.request(
"{0}/oauth/access_token".format(self.version), args
) | [
"def",
"get_access_token_from_code",
"(",
"self",
",",
"code",
",",
"redirect_uri",
",",
"app_id",
",",
"app_secret",
")",
":",
"args",
"=",
"{",
"\"code\"",
":",
"code",
",",
"\"redirect_uri\"",
":",
"redirect_uri",
",",
"\"client_id\"",
":",
"app_id",
",",
"\"client_secret\"",
":",
"app_secret",
",",
"}",
"return",
"self",
".",
"request",
"(",
"\"{0}/oauth/access_token\"",
".",
"format",
"(",
"self",
".",
"version",
")",
",",
"args",
")"
] | Get an access token from the "code" returned from an OAuth dialog.
Returns a dict containing the user-specific access token and its
expiration date (if applicable). | [
"Get",
"an",
"access",
"token",
"from",
"the",
"code",
"returned",
"from",
"an",
"OAuth",
"dialog",
"."
] | 65ff582e77f7ed68b6e9643a7490e5dee2a1031b | https://github.com/mobolic/facebook-sdk/blob/65ff582e77f7ed68b6e9643a7490e5dee2a1031b/facebook/__init__.py#L346-L364 |
227,681 | mobolic/facebook-sdk | facebook/__init__.py | GraphAPI.get_auth_url | def get_auth_url(self, app_id, canvas_url, perms=None, **kwargs):
"""Build a URL to create an OAuth dialog."""
url = "{0}{1}/{2}".format(
FACEBOOK_WWW_URL, self.version, FACEBOOK_OAUTH_DIALOG_PATH
)
args = {"client_id": app_id, "redirect_uri": canvas_url}
if perms:
args["scope"] = ",".join(perms)
args.update(kwargs)
return url + urlencode(args) | python | def get_auth_url(self, app_id, canvas_url, perms=None, **kwargs):
"""Build a URL to create an OAuth dialog."""
url = "{0}{1}/{2}".format(
FACEBOOK_WWW_URL, self.version, FACEBOOK_OAUTH_DIALOG_PATH
)
args = {"client_id": app_id, "redirect_uri": canvas_url}
if perms:
args["scope"] = ",".join(perms)
args.update(kwargs)
return url + urlencode(args) | [
"def",
"get_auth_url",
"(",
"self",
",",
"app_id",
",",
"canvas_url",
",",
"perms",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"url",
"=",
"\"{0}{1}/{2}\"",
".",
"format",
"(",
"FACEBOOK_WWW_URL",
",",
"self",
".",
"version",
",",
"FACEBOOK_OAUTH_DIALOG_PATH",
")",
"args",
"=",
"{",
"\"client_id\"",
":",
"app_id",
",",
"\"redirect_uri\"",
":",
"canvas_url",
"}",
"if",
"perms",
":",
"args",
"[",
"\"scope\"",
"]",
"=",
"\",\"",
".",
"join",
"(",
"perms",
")",
"args",
".",
"update",
"(",
"kwargs",
")",
"return",
"url",
"+",
"urlencode",
"(",
"args",
")"
] | Build a URL to create an OAuth dialog. | [
"Build",
"a",
"URL",
"to",
"create",
"an",
"OAuth",
"dialog",
"."
] | 65ff582e77f7ed68b6e9643a7490e5dee2a1031b | https://github.com/mobolic/facebook-sdk/blob/65ff582e77f7ed68b6e9643a7490e5dee2a1031b/facebook/__init__.py#L401-L411 |
227,682 | mobolic/facebook-sdk | examples/flask/app/views.py | get_current_user | def get_current_user():
"""Set g.user to the currently logged in user.
Called before each request, get_current_user sets the global g.user
variable to the currently logged in user. A currently logged in user is
determined by seeing if it exists in Flask's session dictionary.
If it is the first time the user is logging into this application it will
create the user and insert it into the database. If the user is not logged
in, None will be set to g.user.
"""
# Set the user in the session dictionary as a global g.user and bail out
# of this function early.
if session.get("user"):
g.user = session.get("user")
return
# Attempt to get the short term access token for the current user.
result = get_user_from_cookie(
cookies=request.cookies, app_id=FB_APP_ID, app_secret=FB_APP_SECRET
)
# If there is no result, we assume the user is not logged in.
if result:
# Check to see if this user is already in our database.
user = User.query.filter(User.id == result["uid"]).first()
if not user:
# Not an existing user so get info
graph = GraphAPI(result["access_token"])
profile = graph.get_object("me")
if "link" not in profile:
profile["link"] = ""
# Create the user and insert it into the database
user = User(
id=str(profile["id"]),
name=profile["name"],
profile_url=profile["link"],
access_token=result["access_token"],
)
db.session.add(user)
elif user.access_token != result["access_token"]:
# If an existing user, update the access token
user.access_token = result["access_token"]
# Add the user to the current session
session["user"] = dict(
name=user.name,
profile_url=user.profile_url,
id=user.id,
access_token=user.access_token,
)
# Commit changes to the database and set the user as a global g.user
db.session.commit()
g.user = session.get("user", None) | python | def get_current_user():
"""Set g.user to the currently logged in user.
Called before each request, get_current_user sets the global g.user
variable to the currently logged in user. A currently logged in user is
determined by seeing if it exists in Flask's session dictionary.
If it is the first time the user is logging into this application it will
create the user and insert it into the database. If the user is not logged
in, None will be set to g.user.
"""
# Set the user in the session dictionary as a global g.user and bail out
# of this function early.
if session.get("user"):
g.user = session.get("user")
return
# Attempt to get the short term access token for the current user.
result = get_user_from_cookie(
cookies=request.cookies, app_id=FB_APP_ID, app_secret=FB_APP_SECRET
)
# If there is no result, we assume the user is not logged in.
if result:
# Check to see if this user is already in our database.
user = User.query.filter(User.id == result["uid"]).first()
if not user:
# Not an existing user so get info
graph = GraphAPI(result["access_token"])
profile = graph.get_object("me")
if "link" not in profile:
profile["link"] = ""
# Create the user and insert it into the database
user = User(
id=str(profile["id"]),
name=profile["name"],
profile_url=profile["link"],
access_token=result["access_token"],
)
db.session.add(user)
elif user.access_token != result["access_token"]:
# If an existing user, update the access token
user.access_token = result["access_token"]
# Add the user to the current session
session["user"] = dict(
name=user.name,
profile_url=user.profile_url,
id=user.id,
access_token=user.access_token,
)
# Commit changes to the database and set the user as a global g.user
db.session.commit()
g.user = session.get("user", None) | [
"def",
"get_current_user",
"(",
")",
":",
"# Set the user in the session dictionary as a global g.user and bail out",
"# of this function early.",
"if",
"session",
".",
"get",
"(",
"\"user\"",
")",
":",
"g",
".",
"user",
"=",
"session",
".",
"get",
"(",
"\"user\"",
")",
"return",
"# Attempt to get the short term access token for the current user.",
"result",
"=",
"get_user_from_cookie",
"(",
"cookies",
"=",
"request",
".",
"cookies",
",",
"app_id",
"=",
"FB_APP_ID",
",",
"app_secret",
"=",
"FB_APP_SECRET",
")",
"# If there is no result, we assume the user is not logged in.",
"if",
"result",
":",
"# Check to see if this user is already in our database.",
"user",
"=",
"User",
".",
"query",
".",
"filter",
"(",
"User",
".",
"id",
"==",
"result",
"[",
"\"uid\"",
"]",
")",
".",
"first",
"(",
")",
"if",
"not",
"user",
":",
"# Not an existing user so get info",
"graph",
"=",
"GraphAPI",
"(",
"result",
"[",
"\"access_token\"",
"]",
")",
"profile",
"=",
"graph",
".",
"get_object",
"(",
"\"me\"",
")",
"if",
"\"link\"",
"not",
"in",
"profile",
":",
"profile",
"[",
"\"link\"",
"]",
"=",
"\"\"",
"# Create the user and insert it into the database",
"user",
"=",
"User",
"(",
"id",
"=",
"str",
"(",
"profile",
"[",
"\"id\"",
"]",
")",
",",
"name",
"=",
"profile",
"[",
"\"name\"",
"]",
",",
"profile_url",
"=",
"profile",
"[",
"\"link\"",
"]",
",",
"access_token",
"=",
"result",
"[",
"\"access_token\"",
"]",
",",
")",
"db",
".",
"session",
".",
"add",
"(",
"user",
")",
"elif",
"user",
".",
"access_token",
"!=",
"result",
"[",
"\"access_token\"",
"]",
":",
"# If an existing user, update the access token",
"user",
".",
"access_token",
"=",
"result",
"[",
"\"access_token\"",
"]",
"# Add the user to the current session",
"session",
"[",
"\"user\"",
"]",
"=",
"dict",
"(",
"name",
"=",
"user",
".",
"name",
",",
"profile_url",
"=",
"user",
".",
"profile_url",
",",
"id",
"=",
"user",
".",
"id",
",",
"access_token",
"=",
"user",
".",
"access_token",
",",
")",
"# Commit changes to the database and set the user as a global g.user",
"db",
".",
"session",
".",
"commit",
"(",
")",
"g",
".",
"user",
"=",
"session",
".",
"get",
"(",
"\"user\"",
",",
"None",
")"
] | Set g.user to the currently logged in user.
Called before each request, get_current_user sets the global g.user
variable to the currently logged in user. A currently logged in user is
determined by seeing if it exists in Flask's session dictionary.
If it is the first time the user is logging into this application it will
create the user and insert it into the database. If the user is not logged
in, None will be set to g.user. | [
"Set",
"g",
".",
"user",
"to",
"the",
"currently",
"logged",
"in",
"user",
"."
] | 65ff582e77f7ed68b6e9643a7490e5dee2a1031b | https://github.com/mobolic/facebook-sdk/blob/65ff582e77f7ed68b6e9643a7490e5dee2a1031b/examples/flask/app/views.py#L38-L95 |
227,683 | NetEaseGame/ATX | atx/record/scene_detector.py | SceneDetector.build_tree | def build_tree(self, directory):
'''build scene tree from images'''
confile = os.path.join(directory, 'config.yml')
conf = {}
if os.path.exists(confile):
conf = yaml.load(open(confile).read())
class node(defaultdict):
name = ''
parent = None
tmpl = None
rect = None
mask = None
def __str__(self):
obj = self
names = []
while obj.parent is not None:
names.append(obj.name)
obj = obj.parent
return '-'.join(names[::-1])
def tree():
return node(tree)
root = tree()
for s in os.listdir(directory):
if not s.endswith('.png') or s.endswith('_mask.png'):
continue
obj = root
for i in s[:-4].split('-'):
obj[i].name = i
obj[i].parent = obj
obj = obj[i]
obj.tmpl = cv2.imread(os.path.join(directory, s))
obj.rect = conf.get(s[:-4], {}).get('rect')
maskimg = conf.get(s[:-4], {}).get('mask')
if maskimg is not None:
maskimg = os.path.join(directory, maskimg)
if os.path.exists(maskimg):
obj.mask = cv2.imread(maskimg)
self.tree = root
self.current_scene = []
self.confile = confile
self.conf = conf | python | def build_tree(self, directory):
'''build scene tree from images'''
confile = os.path.join(directory, 'config.yml')
conf = {}
if os.path.exists(confile):
conf = yaml.load(open(confile).read())
class node(defaultdict):
name = ''
parent = None
tmpl = None
rect = None
mask = None
def __str__(self):
obj = self
names = []
while obj.parent is not None:
names.append(obj.name)
obj = obj.parent
return '-'.join(names[::-1])
def tree():
return node(tree)
root = tree()
for s in os.listdir(directory):
if not s.endswith('.png') or s.endswith('_mask.png'):
continue
obj = root
for i in s[:-4].split('-'):
obj[i].name = i
obj[i].parent = obj
obj = obj[i]
obj.tmpl = cv2.imread(os.path.join(directory, s))
obj.rect = conf.get(s[:-4], {}).get('rect')
maskimg = conf.get(s[:-4], {}).get('mask')
if maskimg is not None:
maskimg = os.path.join(directory, maskimg)
if os.path.exists(maskimg):
obj.mask = cv2.imread(maskimg)
self.tree = root
self.current_scene = []
self.confile = confile
self.conf = conf | [
"def",
"build_tree",
"(",
"self",
",",
"directory",
")",
":",
"confile",
"=",
"os",
".",
"path",
".",
"join",
"(",
"directory",
",",
"'config.yml'",
")",
"conf",
"=",
"{",
"}",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"confile",
")",
":",
"conf",
"=",
"yaml",
".",
"load",
"(",
"open",
"(",
"confile",
")",
".",
"read",
"(",
")",
")",
"class",
"node",
"(",
"defaultdict",
")",
":",
"name",
"=",
"''",
"parent",
"=",
"None",
"tmpl",
"=",
"None",
"rect",
"=",
"None",
"mask",
"=",
"None",
"def",
"__str__",
"(",
"self",
")",
":",
"obj",
"=",
"self",
"names",
"=",
"[",
"]",
"while",
"obj",
".",
"parent",
"is",
"not",
"None",
":",
"names",
".",
"append",
"(",
"obj",
".",
"name",
")",
"obj",
"=",
"obj",
".",
"parent",
"return",
"'-'",
".",
"join",
"(",
"names",
"[",
":",
":",
"-",
"1",
"]",
")",
"def",
"tree",
"(",
")",
":",
"return",
"node",
"(",
"tree",
")",
"root",
"=",
"tree",
"(",
")",
"for",
"s",
"in",
"os",
".",
"listdir",
"(",
"directory",
")",
":",
"if",
"not",
"s",
".",
"endswith",
"(",
"'.png'",
")",
"or",
"s",
".",
"endswith",
"(",
"'_mask.png'",
")",
":",
"continue",
"obj",
"=",
"root",
"for",
"i",
"in",
"s",
"[",
":",
"-",
"4",
"]",
".",
"split",
"(",
"'-'",
")",
":",
"obj",
"[",
"i",
"]",
".",
"name",
"=",
"i",
"obj",
"[",
"i",
"]",
".",
"parent",
"=",
"obj",
"obj",
"=",
"obj",
"[",
"i",
"]",
"obj",
".",
"tmpl",
"=",
"cv2",
".",
"imread",
"(",
"os",
".",
"path",
".",
"join",
"(",
"directory",
",",
"s",
")",
")",
"obj",
".",
"rect",
"=",
"conf",
".",
"get",
"(",
"s",
"[",
":",
"-",
"4",
"]",
",",
"{",
"}",
")",
".",
"get",
"(",
"'rect'",
")",
"maskimg",
"=",
"conf",
".",
"get",
"(",
"s",
"[",
":",
"-",
"4",
"]",
",",
"{",
"}",
")",
".",
"get",
"(",
"'mask'",
")",
"if",
"maskimg",
"is",
"not",
"None",
":",
"maskimg",
"=",
"os",
".",
"path",
".",
"join",
"(",
"directory",
",",
"maskimg",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"maskimg",
")",
":",
"obj",
".",
"mask",
"=",
"cv2",
".",
"imread",
"(",
"maskimg",
")",
"self",
".",
"tree",
"=",
"root",
"self",
".",
"current_scene",
"=",
"[",
"]",
"self",
".",
"confile",
"=",
"confile",
"self",
".",
"conf",
"=",
"conf"
] | build scene tree from images | [
"build",
"scene",
"tree",
"from",
"images"
] | f4415c57b45cb0730e08899cbc92a2af1c047ffb | https://github.com/NetEaseGame/ATX/blob/f4415c57b45cb0730e08899cbc92a2af1c047ffb/atx/record/scene_detector.py#L81-L126 |
227,684 | NetEaseGame/ATX | atx/adbkit/openstf/service.py | pack | def pack(mtype, request, rid=None):
'''pack request to delimited data'''
envelope = wire.Envelope()
if rid is not None:
envelope.id = rid
envelope.type = mtype
envelope.message = request.SerializeToString()
data = envelope.SerializeToString()
data = encoder._VarintBytes(len(data)) + data
return data | python | def pack(mtype, request, rid=None):
'''pack request to delimited data'''
envelope = wire.Envelope()
if rid is not None:
envelope.id = rid
envelope.type = mtype
envelope.message = request.SerializeToString()
data = envelope.SerializeToString()
data = encoder._VarintBytes(len(data)) + data
return data | [
"def",
"pack",
"(",
"mtype",
",",
"request",
",",
"rid",
"=",
"None",
")",
":",
"envelope",
"=",
"wire",
".",
"Envelope",
"(",
")",
"if",
"rid",
"is",
"not",
"None",
":",
"envelope",
".",
"id",
"=",
"rid",
"envelope",
".",
"type",
"=",
"mtype",
"envelope",
".",
"message",
"=",
"request",
".",
"SerializeToString",
"(",
")",
"data",
"=",
"envelope",
".",
"SerializeToString",
"(",
")",
"data",
"=",
"encoder",
".",
"_VarintBytes",
"(",
"len",
"(",
"data",
")",
")",
"+",
"data",
"return",
"data"
] | pack request to delimited data | [
"pack",
"request",
"to",
"delimited",
"data"
] | f4415c57b45cb0730e08899cbc92a2af1c047ffb | https://github.com/NetEaseGame/ATX/blob/f4415c57b45cb0730e08899cbc92a2af1c047ffb/atx/adbkit/openstf/service.py#L75-L84 |
227,685 | NetEaseGame/ATX | atx/adbkit/openstf/service.py | unpack | def unpack(data):
'''unpack from delimited data'''
size, position = decoder._DecodeVarint(data, 0)
envelope = wire.Envelope()
envelope.ParseFromString(data[position:position+size])
return envelope | python | def unpack(data):
'''unpack from delimited data'''
size, position = decoder._DecodeVarint(data, 0)
envelope = wire.Envelope()
envelope.ParseFromString(data[position:position+size])
return envelope | [
"def",
"unpack",
"(",
"data",
")",
":",
"size",
",",
"position",
"=",
"decoder",
".",
"_DecodeVarint",
"(",
"data",
",",
"0",
")",
"envelope",
"=",
"wire",
".",
"Envelope",
"(",
")",
"envelope",
".",
"ParseFromString",
"(",
"data",
"[",
"position",
":",
"position",
"+",
"size",
"]",
")",
"return",
"envelope"
] | unpack from delimited data | [
"unpack",
"from",
"delimited",
"data"
] | f4415c57b45cb0730e08899cbc92a2af1c047ffb | https://github.com/NetEaseGame/ATX/blob/f4415c57b45cb0730e08899cbc92a2af1c047ffb/atx/adbkit/openstf/service.py#L86-L91 |
227,686 | NetEaseGame/ATX | atx/adbkit/openstf/service.py | check_stf_agent | def check_stf_agent(adbprefix=None, kill=False):
'''return True if agent is alive.'''
if adbprefix is None:
adbprefix = ['adb']
command = adbprefix + ['shell', 'ps']
out = subprocess.check_output(command).strip()
out = out.splitlines()
if len(out) > 1:
first, out = out[0], out[1:]
idx = first.split().index('PID')
pid = None
for line in out:
if 'stf.agent' in line:
pid = line.split()[idx]
print 'stf.agent is running, pid is', pid
break
if pid is not None:
if kill:
print 'killing', pid
command = adbprefix + ['shell', 'kill', '-9', pid]
subprocess.call(command)
return False
return True
return False | python | def check_stf_agent(adbprefix=None, kill=False):
'''return True if agent is alive.'''
if adbprefix is None:
adbprefix = ['adb']
command = adbprefix + ['shell', 'ps']
out = subprocess.check_output(command).strip()
out = out.splitlines()
if len(out) > 1:
first, out = out[0], out[1:]
idx = first.split().index('PID')
pid = None
for line in out:
if 'stf.agent' in line:
pid = line.split()[idx]
print 'stf.agent is running, pid is', pid
break
if pid is not None:
if kill:
print 'killing', pid
command = adbprefix + ['shell', 'kill', '-9', pid]
subprocess.call(command)
return False
return True
return False | [
"def",
"check_stf_agent",
"(",
"adbprefix",
"=",
"None",
",",
"kill",
"=",
"False",
")",
":",
"if",
"adbprefix",
"is",
"None",
":",
"adbprefix",
"=",
"[",
"'adb'",
"]",
"command",
"=",
"adbprefix",
"+",
"[",
"'shell'",
",",
"'ps'",
"]",
"out",
"=",
"subprocess",
".",
"check_output",
"(",
"command",
")",
".",
"strip",
"(",
")",
"out",
"=",
"out",
".",
"splitlines",
"(",
")",
"if",
"len",
"(",
"out",
")",
">",
"1",
":",
"first",
",",
"out",
"=",
"out",
"[",
"0",
"]",
",",
"out",
"[",
"1",
":",
"]",
"idx",
"=",
"first",
".",
"split",
"(",
")",
".",
"index",
"(",
"'PID'",
")",
"pid",
"=",
"None",
"for",
"line",
"in",
"out",
":",
"if",
"'stf.agent'",
"in",
"line",
":",
"pid",
"=",
"line",
".",
"split",
"(",
")",
"[",
"idx",
"]",
"print",
"'stf.agent is running, pid is'",
",",
"pid",
"break",
"if",
"pid",
"is",
"not",
"None",
":",
"if",
"kill",
":",
"print",
"'killing'",
",",
"pid",
"command",
"=",
"adbprefix",
"+",
"[",
"'shell'",
",",
"'kill'",
",",
"'-9'",
",",
"pid",
"]",
"subprocess",
".",
"call",
"(",
"command",
")",
"return",
"False",
"return",
"True",
"return",
"False"
] | return True if agent is alive. | [
"return",
"True",
"if",
"agent",
"is",
"alive",
"."
] | f4415c57b45cb0730e08899cbc92a2af1c047ffb | https://github.com/NetEaseGame/ATX/blob/f4415c57b45cb0730e08899cbc92a2af1c047ffb/atx/adbkit/openstf/service.py#L182-L205 |
227,687 | NetEaseGame/ATX | atx/cmds/tkgui.py | insert_code | def insert_code(filename, code, save=True, marker='# ATX CODE END'):
""" Auto append code """
content = ''
found = False
for line in open(filename, 'rb'):
if not found and line.strip() == marker:
found = True
cnt = line.find(marker)
content += line[:cnt] + code
content += line
if not found:
if not content.endswith('\n'):
content += '\n'
content += code + marker + '\n'
if save:
with open(filename, 'wb') as f:
f.write(content)
return content | python | def insert_code(filename, code, save=True, marker='# ATX CODE END'):
""" Auto append code """
content = ''
found = False
for line in open(filename, 'rb'):
if not found and line.strip() == marker:
found = True
cnt = line.find(marker)
content += line[:cnt] + code
content += line
if not found:
if not content.endswith('\n'):
content += '\n'
content += code + marker + '\n'
if save:
with open(filename, 'wb') as f:
f.write(content)
return content | [
"def",
"insert_code",
"(",
"filename",
",",
"code",
",",
"save",
"=",
"True",
",",
"marker",
"=",
"'# ATX CODE END'",
")",
":",
"content",
"=",
"''",
"found",
"=",
"False",
"for",
"line",
"in",
"open",
"(",
"filename",
",",
"'rb'",
")",
":",
"if",
"not",
"found",
"and",
"line",
".",
"strip",
"(",
")",
"==",
"marker",
":",
"found",
"=",
"True",
"cnt",
"=",
"line",
".",
"find",
"(",
"marker",
")",
"content",
"+=",
"line",
"[",
":",
"cnt",
"]",
"+",
"code",
"content",
"+=",
"line",
"if",
"not",
"found",
":",
"if",
"not",
"content",
".",
"endswith",
"(",
"'\\n'",
")",
":",
"content",
"+=",
"'\\n'",
"content",
"+=",
"code",
"+",
"marker",
"+",
"'\\n'",
"if",
"save",
":",
"with",
"open",
"(",
"filename",
",",
"'wb'",
")",
"as",
"f",
":",
"f",
".",
"write",
"(",
"content",
")",
"return",
"content"
] | Auto append code | [
"Auto",
"append",
"code"
] | f4415c57b45cb0730e08899cbc92a2af1c047ffb | https://github.com/NetEaseGame/ATX/blob/f4415c57b45cb0730e08899cbc92a2af1c047ffb/atx/cmds/tkgui.py#L41-L58 |
227,688 | NetEaseGame/ATX | scripts/image.py | find_image_position | def find_image_position(origin='origin.png', query='query.png', outfile=None):
'''
find all image positions
@return None if not found else a tuple: (origin.shape, query.shape, postions)
might raise Exception
'''
img1 = cv2.imread(query, 0) # query image(small)
img2 = cv2.imread(origin, 0) # train image(big)
# Initiate SIFT detector
sift = cv2.SIFT()
# find the keypoints and descriptors with SIFT
kp1, des1 = sift.detectAndCompute(img1,None)
kp2, des2 = sift.detectAndCompute(img2,None)
print len(kp1), len(kp2)
FLANN_INDEX_KDTREE = 0
index_params = dict(algorithm = FLANN_INDEX_KDTREE, trees = 5)
search_params = dict(checks = 50)
# flann
flann = cv2.FlannBasedMatcher(index_params, search_params)
matches = flann.knnMatch(des1, des2, k=2)
# store all the good matches as per Lowe's ratio test.
good = []
for m,n in matches:
if m.distance < 0.7*n.distance:
good.append(m)
print len(kp1), len(kp2), 'good cnt:', len(good)
if len(good)*1.0/len(kp1) < 0.5:
#if len(good)<MIN_MATCH_COUNT:
print "Not enough matches are found - %d/%d" % (len(good),MIN_MATCH_COUNT)
return img2.shape, img1.shape, []
queryPts = []
trainPts = []
for dm in good:
queryPts.append(kp1[dm.queryIdx])
trainPts.append(kp2[dm.trainIdx])
img3 = cv2.drawKeypoints(img1, queryPts)
cv2.imwrite('image/query.png', img3)
img3 = cv2.drawKeypoints(img2, trainPts)
point = _middlePoint(trainPts)
print 'position in', point
if outfile:
edge = 10
top_left = (point[0]-edge, point[1]-edge)
bottom_right = (point[0]+edge, point[1]+edge)
cv2.rectangle(img3, top_left, bottom_right, 255, 2)
cv2.imwrite(outfile, img3)
return img2.shape, img1.shape, [point] | python | def find_image_position(origin='origin.png', query='query.png', outfile=None):
'''
find all image positions
@return None if not found else a tuple: (origin.shape, query.shape, postions)
might raise Exception
'''
img1 = cv2.imread(query, 0) # query image(small)
img2 = cv2.imread(origin, 0) # train image(big)
# Initiate SIFT detector
sift = cv2.SIFT()
# find the keypoints and descriptors with SIFT
kp1, des1 = sift.detectAndCompute(img1,None)
kp2, des2 = sift.detectAndCompute(img2,None)
print len(kp1), len(kp2)
FLANN_INDEX_KDTREE = 0
index_params = dict(algorithm = FLANN_INDEX_KDTREE, trees = 5)
search_params = dict(checks = 50)
# flann
flann = cv2.FlannBasedMatcher(index_params, search_params)
matches = flann.knnMatch(des1, des2, k=2)
# store all the good matches as per Lowe's ratio test.
good = []
for m,n in matches:
if m.distance < 0.7*n.distance:
good.append(m)
print len(kp1), len(kp2), 'good cnt:', len(good)
if len(good)*1.0/len(kp1) < 0.5:
#if len(good)<MIN_MATCH_COUNT:
print "Not enough matches are found - %d/%d" % (len(good),MIN_MATCH_COUNT)
return img2.shape, img1.shape, []
queryPts = []
trainPts = []
for dm in good:
queryPts.append(kp1[dm.queryIdx])
trainPts.append(kp2[dm.trainIdx])
img3 = cv2.drawKeypoints(img1, queryPts)
cv2.imwrite('image/query.png', img3)
img3 = cv2.drawKeypoints(img2, trainPts)
point = _middlePoint(trainPts)
print 'position in', point
if outfile:
edge = 10
top_left = (point[0]-edge, point[1]-edge)
bottom_right = (point[0]+edge, point[1]+edge)
cv2.rectangle(img3, top_left, bottom_right, 255, 2)
cv2.imwrite(outfile, img3)
return img2.shape, img1.shape, [point] | [
"def",
"find_image_position",
"(",
"origin",
"=",
"'origin.png'",
",",
"query",
"=",
"'query.png'",
",",
"outfile",
"=",
"None",
")",
":",
"img1",
"=",
"cv2",
".",
"imread",
"(",
"query",
",",
"0",
")",
"# query image(small)",
"img2",
"=",
"cv2",
".",
"imread",
"(",
"origin",
",",
"0",
")",
"# train image(big)",
"# Initiate SIFT detector",
"sift",
"=",
"cv2",
".",
"SIFT",
"(",
")",
"# find the keypoints and descriptors with SIFT",
"kp1",
",",
"des1",
"=",
"sift",
".",
"detectAndCompute",
"(",
"img1",
",",
"None",
")",
"kp2",
",",
"des2",
"=",
"sift",
".",
"detectAndCompute",
"(",
"img2",
",",
"None",
")",
"print",
"len",
"(",
"kp1",
")",
",",
"len",
"(",
"kp2",
")",
"FLANN_INDEX_KDTREE",
"=",
"0",
"index_params",
"=",
"dict",
"(",
"algorithm",
"=",
"FLANN_INDEX_KDTREE",
",",
"trees",
"=",
"5",
")",
"search_params",
"=",
"dict",
"(",
"checks",
"=",
"50",
")",
"# flann",
"flann",
"=",
"cv2",
".",
"FlannBasedMatcher",
"(",
"index_params",
",",
"search_params",
")",
"matches",
"=",
"flann",
".",
"knnMatch",
"(",
"des1",
",",
"des2",
",",
"k",
"=",
"2",
")",
"# store all the good matches as per Lowe's ratio test.",
"good",
"=",
"[",
"]",
"for",
"m",
",",
"n",
"in",
"matches",
":",
"if",
"m",
".",
"distance",
"<",
"0.7",
"*",
"n",
".",
"distance",
":",
"good",
".",
"append",
"(",
"m",
")",
"print",
"len",
"(",
"kp1",
")",
",",
"len",
"(",
"kp2",
")",
",",
"'good cnt:'",
",",
"len",
"(",
"good",
")",
"if",
"len",
"(",
"good",
")",
"*",
"1.0",
"/",
"len",
"(",
"kp1",
")",
"<",
"0.5",
":",
"#if len(good)<MIN_MATCH_COUNT:",
"print",
"\"Not enough matches are found - %d/%d\"",
"%",
"(",
"len",
"(",
"good",
")",
",",
"MIN_MATCH_COUNT",
")",
"return",
"img2",
".",
"shape",
",",
"img1",
".",
"shape",
",",
"[",
"]",
"queryPts",
"=",
"[",
"]",
"trainPts",
"=",
"[",
"]",
"for",
"dm",
"in",
"good",
":",
"queryPts",
".",
"append",
"(",
"kp1",
"[",
"dm",
".",
"queryIdx",
"]",
")",
"trainPts",
".",
"append",
"(",
"kp2",
"[",
"dm",
".",
"trainIdx",
"]",
")",
"img3",
"=",
"cv2",
".",
"drawKeypoints",
"(",
"img1",
",",
"queryPts",
")",
"cv2",
".",
"imwrite",
"(",
"'image/query.png'",
",",
"img3",
")",
"img3",
"=",
"cv2",
".",
"drawKeypoints",
"(",
"img2",
",",
"trainPts",
")",
"point",
"=",
"_middlePoint",
"(",
"trainPts",
")",
"print",
"'position in'",
",",
"point",
"if",
"outfile",
":",
"edge",
"=",
"10",
"top_left",
"=",
"(",
"point",
"[",
"0",
"]",
"-",
"edge",
",",
"point",
"[",
"1",
"]",
"-",
"edge",
")",
"bottom_right",
"=",
"(",
"point",
"[",
"0",
"]",
"+",
"edge",
",",
"point",
"[",
"1",
"]",
"+",
"edge",
")",
"cv2",
".",
"rectangle",
"(",
"img3",
",",
"top_left",
",",
"bottom_right",
",",
"255",
",",
"2",
")",
"cv2",
".",
"imwrite",
"(",
"outfile",
",",
"img3",
")",
"return",
"img2",
".",
"shape",
",",
"img1",
".",
"shape",
",",
"[",
"point",
"]"
] | find all image positions
@return None if not found else a tuple: (origin.shape, query.shape, postions)
might raise Exception | [
"find",
"all",
"image",
"positions"
] | f4415c57b45cb0730e08899cbc92a2af1c047ffb | https://github.com/NetEaseGame/ATX/blob/f4415c57b45cb0730e08899cbc92a2af1c047ffb/scripts/image.py#L46-L102 |
227,689 | NetEaseGame/ATX | atx/taskqueue/__main__.py | TaskQueueHandler.get | def get(self, udid):
''' get new task '''
timeout = self.get_argument('timeout', 20.0)
if timeout is not None:
timeout = float(timeout)
que = self.ques[udid]
try:
item = yield que.get(timeout=time.time()+timeout) # timeout is a timestamp, strange
print 'get from queue:', item
self.write(item)
que.task_done()
except gen.TimeoutError:
print 'timeout'
self.write('')
finally:
self.finish() | python | def get(self, udid):
''' get new task '''
timeout = self.get_argument('timeout', 20.0)
if timeout is not None:
timeout = float(timeout)
que = self.ques[udid]
try:
item = yield que.get(timeout=time.time()+timeout) # timeout is a timestamp, strange
print 'get from queue:', item
self.write(item)
que.task_done()
except gen.TimeoutError:
print 'timeout'
self.write('')
finally:
self.finish() | [
"def",
"get",
"(",
"self",
",",
"udid",
")",
":",
"timeout",
"=",
"self",
".",
"get_argument",
"(",
"'timeout'",
",",
"20.0",
")",
"if",
"timeout",
"is",
"not",
"None",
":",
"timeout",
"=",
"float",
"(",
"timeout",
")",
"que",
"=",
"self",
".",
"ques",
"[",
"udid",
"]",
"try",
":",
"item",
"=",
"yield",
"que",
".",
"get",
"(",
"timeout",
"=",
"time",
".",
"time",
"(",
")",
"+",
"timeout",
")",
"# timeout is a timestamp, strange",
"print",
"'get from queue:'",
",",
"item",
"self",
".",
"write",
"(",
"item",
")",
"que",
".",
"task_done",
"(",
")",
"except",
"gen",
".",
"TimeoutError",
":",
"print",
"'timeout'",
"self",
".",
"write",
"(",
"''",
")",
"finally",
":",
"self",
".",
"finish",
"(",
")"
] | get new task | [
"get",
"new",
"task"
] | f4415c57b45cb0730e08899cbc92a2af1c047ffb | https://github.com/NetEaseGame/ATX/blob/f4415c57b45cb0730e08899cbc92a2af1c047ffb/atx/taskqueue/__main__.py#L42-L57 |
227,690 | NetEaseGame/ATX | atx/taskqueue/__main__.py | TaskQueueHandler.post | def post(self, udid):
''' add new task '''
que = self.ques[udid]
timeout = self.get_argument('timeout', 10.0)
if timeout is not None:
timeout = float(timeout)
data = tornado.escape.json_decode(self.request.body)
data = {'id': str(uuid.uuid1()), 'data': data}
yield que.put(data, timeout=time.time()+timeout)
print 'post, queue size:', que.qsize()
self.write({'id': data['id']})
self.finish() | python | def post(self, udid):
''' add new task '''
que = self.ques[udid]
timeout = self.get_argument('timeout', 10.0)
if timeout is not None:
timeout = float(timeout)
data = tornado.escape.json_decode(self.request.body)
data = {'id': str(uuid.uuid1()), 'data': data}
yield que.put(data, timeout=time.time()+timeout)
print 'post, queue size:', que.qsize()
self.write({'id': data['id']})
self.finish() | [
"def",
"post",
"(",
"self",
",",
"udid",
")",
":",
"que",
"=",
"self",
".",
"ques",
"[",
"udid",
"]",
"timeout",
"=",
"self",
".",
"get_argument",
"(",
"'timeout'",
",",
"10.0",
")",
"if",
"timeout",
"is",
"not",
"None",
":",
"timeout",
"=",
"float",
"(",
"timeout",
")",
"data",
"=",
"tornado",
".",
"escape",
".",
"json_decode",
"(",
"self",
".",
"request",
".",
"body",
")",
"data",
"=",
"{",
"'id'",
":",
"str",
"(",
"uuid",
".",
"uuid1",
"(",
")",
")",
",",
"'data'",
":",
"data",
"}",
"yield",
"que",
".",
"put",
"(",
"data",
",",
"timeout",
"=",
"time",
".",
"time",
"(",
")",
"+",
"timeout",
")",
"print",
"'post, queue size:'",
",",
"que",
".",
"qsize",
"(",
")",
"self",
".",
"write",
"(",
"{",
"'id'",
":",
"data",
"[",
"'id'",
"]",
"}",
")",
"self",
".",
"finish",
"(",
")"
] | add new task | [
"add",
"new",
"task"
] | f4415c57b45cb0730e08899cbc92a2af1c047ffb | https://github.com/NetEaseGame/ATX/blob/f4415c57b45cb0730e08899cbc92a2af1c047ffb/atx/taskqueue/__main__.py#L60-L71 |
227,691 | NetEaseGame/ATX | atx/record/android_hooks.py | InputParser._process_touch_batch | def _process_touch_batch(self):
'''a batch syncs in about 0.001 seconds.'''
if not self._touch_batch:
return
_time = self._temp_status_time
changed = False
for (_time, _device, _type, _code, _value) in self._touch_batch:
if _code == 'ABS_MT_TRACKING_ID':
if _value == 0xffffffff:
self._temp_status[self._curr_slot] = -INF
changed = True
else:
pass
elif _code == 'ABS_MT_SLOT':
self._curr_slot = _value
else:
if _code == 'ABS_MT_POSITION_X':
self._temp_status[self._curr_slot,_X] = _value
changed = True
elif _code == 'ABS_MT_POSITION_Y':
self._temp_status[self._curr_slot,_Y] = _value
changed = True
elif _code == 'ABS_MT_PRESSURE':
self._temp_status[self._curr_slot,_PR] = _value
elif _code == 'ABS_MT_TOUCH_MAJOR':
self._temp_status[self._curr_slot,_MJ] = _value
else:
print 'Unknown code', _code
self._temp_status_time = _time
self._touch_batch = []
if not changed:
return
# check differences, if position changes are big enough then emit events
diff = self._temp_status - self._status
dt = self._temp_status_time - self._status_time
emitted = False
for i in range(SLOT_NUM):
arr = self._temp_status[i]
oldarr = self._status[i]
dx, dy = diff[i,_X], diff[i,_Y]
if dx > INF or dy > INF:
# touch begin
event = TouchEvent(_time, HC.TOUCH_DOWN, i, arr[_X], arr[_Y], arr[_PR], arr[_MJ])
self.emit_touch_event(event)
emitted = True
elif dx < -INF or dy < -INF:
# touch end
event = TouchEvent(_time, HC.TOUCH_UP, i, oldarr[_X], oldarr[_Y], oldarr[_PR], oldarr[_MJ])
self.emit_touch_event(event)
emitted = True
else:
r, a = radang(float(dx), float(dy))
if r > self._move_radius:
v = r / dt
event = TouchEvent(_time, HC.TOUCH_MOVE, i, arr[_X], arr[_Y], arr[_PR], arr[_MJ], angle=a, velocity=v)
self.emit_touch_event(event)
emitted = True
if not emitted:
return
self._status = self._temp_status.copy()
self._status_time = self._temp_status_time | python | def _process_touch_batch(self):
'''a batch syncs in about 0.001 seconds.'''
if not self._touch_batch:
return
_time = self._temp_status_time
changed = False
for (_time, _device, _type, _code, _value) in self._touch_batch:
if _code == 'ABS_MT_TRACKING_ID':
if _value == 0xffffffff:
self._temp_status[self._curr_slot] = -INF
changed = True
else:
pass
elif _code == 'ABS_MT_SLOT':
self._curr_slot = _value
else:
if _code == 'ABS_MT_POSITION_X':
self._temp_status[self._curr_slot,_X] = _value
changed = True
elif _code == 'ABS_MT_POSITION_Y':
self._temp_status[self._curr_slot,_Y] = _value
changed = True
elif _code == 'ABS_MT_PRESSURE':
self._temp_status[self._curr_slot,_PR] = _value
elif _code == 'ABS_MT_TOUCH_MAJOR':
self._temp_status[self._curr_slot,_MJ] = _value
else:
print 'Unknown code', _code
self._temp_status_time = _time
self._touch_batch = []
if not changed:
return
# check differences, if position changes are big enough then emit events
diff = self._temp_status - self._status
dt = self._temp_status_time - self._status_time
emitted = False
for i in range(SLOT_NUM):
arr = self._temp_status[i]
oldarr = self._status[i]
dx, dy = diff[i,_X], diff[i,_Y]
if dx > INF or dy > INF:
# touch begin
event = TouchEvent(_time, HC.TOUCH_DOWN, i, arr[_X], arr[_Y], arr[_PR], arr[_MJ])
self.emit_touch_event(event)
emitted = True
elif dx < -INF or dy < -INF:
# touch end
event = TouchEvent(_time, HC.TOUCH_UP, i, oldarr[_X], oldarr[_Y], oldarr[_PR], oldarr[_MJ])
self.emit_touch_event(event)
emitted = True
else:
r, a = radang(float(dx), float(dy))
if r > self._move_radius:
v = r / dt
event = TouchEvent(_time, HC.TOUCH_MOVE, i, arr[_X], arr[_Y], arr[_PR], arr[_MJ], angle=a, velocity=v)
self.emit_touch_event(event)
emitted = True
if not emitted:
return
self._status = self._temp_status.copy()
self._status_time = self._temp_status_time | [
"def",
"_process_touch_batch",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_touch_batch",
":",
"return",
"_time",
"=",
"self",
".",
"_temp_status_time",
"changed",
"=",
"False",
"for",
"(",
"_time",
",",
"_device",
",",
"_type",
",",
"_code",
",",
"_value",
")",
"in",
"self",
".",
"_touch_batch",
":",
"if",
"_code",
"==",
"'ABS_MT_TRACKING_ID'",
":",
"if",
"_value",
"==",
"0xffffffff",
":",
"self",
".",
"_temp_status",
"[",
"self",
".",
"_curr_slot",
"]",
"=",
"-",
"INF",
"changed",
"=",
"True",
"else",
":",
"pass",
"elif",
"_code",
"==",
"'ABS_MT_SLOT'",
":",
"self",
".",
"_curr_slot",
"=",
"_value",
"else",
":",
"if",
"_code",
"==",
"'ABS_MT_POSITION_X'",
":",
"self",
".",
"_temp_status",
"[",
"self",
".",
"_curr_slot",
",",
"_X",
"]",
"=",
"_value",
"changed",
"=",
"True",
"elif",
"_code",
"==",
"'ABS_MT_POSITION_Y'",
":",
"self",
".",
"_temp_status",
"[",
"self",
".",
"_curr_slot",
",",
"_Y",
"]",
"=",
"_value",
"changed",
"=",
"True",
"elif",
"_code",
"==",
"'ABS_MT_PRESSURE'",
":",
"self",
".",
"_temp_status",
"[",
"self",
".",
"_curr_slot",
",",
"_PR",
"]",
"=",
"_value",
"elif",
"_code",
"==",
"'ABS_MT_TOUCH_MAJOR'",
":",
"self",
".",
"_temp_status",
"[",
"self",
".",
"_curr_slot",
",",
"_MJ",
"]",
"=",
"_value",
"else",
":",
"print",
"'Unknown code'",
",",
"_code",
"self",
".",
"_temp_status_time",
"=",
"_time",
"self",
".",
"_touch_batch",
"=",
"[",
"]",
"if",
"not",
"changed",
":",
"return",
"# check differences, if position changes are big enough then emit events\r",
"diff",
"=",
"self",
".",
"_temp_status",
"-",
"self",
".",
"_status",
"dt",
"=",
"self",
".",
"_temp_status_time",
"-",
"self",
".",
"_status_time",
"emitted",
"=",
"False",
"for",
"i",
"in",
"range",
"(",
"SLOT_NUM",
")",
":",
"arr",
"=",
"self",
".",
"_temp_status",
"[",
"i",
"]",
"oldarr",
"=",
"self",
".",
"_status",
"[",
"i",
"]",
"dx",
",",
"dy",
"=",
"diff",
"[",
"i",
",",
"_X",
"]",
",",
"diff",
"[",
"i",
",",
"_Y",
"]",
"if",
"dx",
">",
"INF",
"or",
"dy",
">",
"INF",
":",
"# touch begin\r",
"event",
"=",
"TouchEvent",
"(",
"_time",
",",
"HC",
".",
"TOUCH_DOWN",
",",
"i",
",",
"arr",
"[",
"_X",
"]",
",",
"arr",
"[",
"_Y",
"]",
",",
"arr",
"[",
"_PR",
"]",
",",
"arr",
"[",
"_MJ",
"]",
")",
"self",
".",
"emit_touch_event",
"(",
"event",
")",
"emitted",
"=",
"True",
"elif",
"dx",
"<",
"-",
"INF",
"or",
"dy",
"<",
"-",
"INF",
":",
"# touch end\r",
"event",
"=",
"TouchEvent",
"(",
"_time",
",",
"HC",
".",
"TOUCH_UP",
",",
"i",
",",
"oldarr",
"[",
"_X",
"]",
",",
"oldarr",
"[",
"_Y",
"]",
",",
"oldarr",
"[",
"_PR",
"]",
",",
"oldarr",
"[",
"_MJ",
"]",
")",
"self",
".",
"emit_touch_event",
"(",
"event",
")",
"emitted",
"=",
"True",
"else",
":",
"r",
",",
"a",
"=",
"radang",
"(",
"float",
"(",
"dx",
")",
",",
"float",
"(",
"dy",
")",
")",
"if",
"r",
">",
"self",
".",
"_move_radius",
":",
"v",
"=",
"r",
"/",
"dt",
"event",
"=",
"TouchEvent",
"(",
"_time",
",",
"HC",
".",
"TOUCH_MOVE",
",",
"i",
",",
"arr",
"[",
"_X",
"]",
",",
"arr",
"[",
"_Y",
"]",
",",
"arr",
"[",
"_PR",
"]",
",",
"arr",
"[",
"_MJ",
"]",
",",
"angle",
"=",
"a",
",",
"velocity",
"=",
"v",
")",
"self",
".",
"emit_touch_event",
"(",
"event",
")",
"emitted",
"=",
"True",
"if",
"not",
"emitted",
":",
"return",
"self",
".",
"_status",
"=",
"self",
".",
"_temp_status",
".",
"copy",
"(",
")",
"self",
".",
"_status_time",
"=",
"self",
".",
"_temp_status_time"
] | a batch syncs in about 0.001 seconds. | [
"a",
"batch",
"syncs",
"in",
"about",
"0",
".",
"001",
"seconds",
"."
] | f4415c57b45cb0730e08899cbc92a2af1c047ffb | https://github.com/NetEaseGame/ATX/blob/f4415c57b45cb0730e08899cbc92a2af1c047ffb/atx/record/android_hooks.py#L218-L283 |
227,692 | NetEaseGame/ATX | atx/record/android_hooks.py | GestureRecognizer.process | def process(self):
'''handle events and trigger time-related events'''
timediff = 0
while True:
try:
time.sleep(0.001)
event = self.queue.get_nowait()
self.handle_event(event)
if event.msg & HC.KEY_ANY:
continue
if timediff == 0:
timediff = time.time() - event.time
self.touches[event.slotid] = event
except Queue.Empty:
if not self.running:
break
now = time.time() - timediff
for i in range(SLOT_NUM):
e = self.touches[i]
if e is None:
continue
if e.msg == HC.TOUCH_DOWN and now - e.time > self.long_press_delay:
self.analyze_tracks(TouchTimeoutEvent(now, HC.TOUCH_PRESS_TIMEOUT, i))
self.touches[i] = None
elif e.msg == HC.TOUCH_UP and now - e.time > self.double_tap_delay:
self.analyze_tracks(TouchTimeoutEvent(now, HC.TOUCH_FOLLOW_TIMEOUT, i))
self.touches[i] = None
elif e.msg == HC.TOUCH_MOVE and now - e.time > self.move_stop_delay:
self.analyze_tracks(TouchTimeoutEvent(now, HC.TOUCH_MOVESTOP_TIMEOUT, i))
self.touches[i] = None
except:
traceback.print_exc()
print 'process done.' | python | def process(self):
'''handle events and trigger time-related events'''
timediff = 0
while True:
try:
time.sleep(0.001)
event = self.queue.get_nowait()
self.handle_event(event)
if event.msg & HC.KEY_ANY:
continue
if timediff == 0:
timediff = time.time() - event.time
self.touches[event.slotid] = event
except Queue.Empty:
if not self.running:
break
now = time.time() - timediff
for i in range(SLOT_NUM):
e = self.touches[i]
if e is None:
continue
if e.msg == HC.TOUCH_DOWN and now - e.time > self.long_press_delay:
self.analyze_tracks(TouchTimeoutEvent(now, HC.TOUCH_PRESS_TIMEOUT, i))
self.touches[i] = None
elif e.msg == HC.TOUCH_UP and now - e.time > self.double_tap_delay:
self.analyze_tracks(TouchTimeoutEvent(now, HC.TOUCH_FOLLOW_TIMEOUT, i))
self.touches[i] = None
elif e.msg == HC.TOUCH_MOVE and now - e.time > self.move_stop_delay:
self.analyze_tracks(TouchTimeoutEvent(now, HC.TOUCH_MOVESTOP_TIMEOUT, i))
self.touches[i] = None
except:
traceback.print_exc()
print 'process done.' | [
"def",
"process",
"(",
"self",
")",
":",
"timediff",
"=",
"0",
"while",
"True",
":",
"try",
":",
"time",
".",
"sleep",
"(",
"0.001",
")",
"event",
"=",
"self",
".",
"queue",
".",
"get_nowait",
"(",
")",
"self",
".",
"handle_event",
"(",
"event",
")",
"if",
"event",
".",
"msg",
"&",
"HC",
".",
"KEY_ANY",
":",
"continue",
"if",
"timediff",
"==",
"0",
":",
"timediff",
"=",
"time",
".",
"time",
"(",
")",
"-",
"event",
".",
"time",
"self",
".",
"touches",
"[",
"event",
".",
"slotid",
"]",
"=",
"event",
"except",
"Queue",
".",
"Empty",
":",
"if",
"not",
"self",
".",
"running",
":",
"break",
"now",
"=",
"time",
".",
"time",
"(",
")",
"-",
"timediff",
"for",
"i",
"in",
"range",
"(",
"SLOT_NUM",
")",
":",
"e",
"=",
"self",
".",
"touches",
"[",
"i",
"]",
"if",
"e",
"is",
"None",
":",
"continue",
"if",
"e",
".",
"msg",
"==",
"HC",
".",
"TOUCH_DOWN",
"and",
"now",
"-",
"e",
".",
"time",
">",
"self",
".",
"long_press_delay",
":",
"self",
".",
"analyze_tracks",
"(",
"TouchTimeoutEvent",
"(",
"now",
",",
"HC",
".",
"TOUCH_PRESS_TIMEOUT",
",",
"i",
")",
")",
"self",
".",
"touches",
"[",
"i",
"]",
"=",
"None",
"elif",
"e",
".",
"msg",
"==",
"HC",
".",
"TOUCH_UP",
"and",
"now",
"-",
"e",
".",
"time",
">",
"self",
".",
"double_tap_delay",
":",
"self",
".",
"analyze_tracks",
"(",
"TouchTimeoutEvent",
"(",
"now",
",",
"HC",
".",
"TOUCH_FOLLOW_TIMEOUT",
",",
"i",
")",
")",
"self",
".",
"touches",
"[",
"i",
"]",
"=",
"None",
"elif",
"e",
".",
"msg",
"==",
"HC",
".",
"TOUCH_MOVE",
"and",
"now",
"-",
"e",
".",
"time",
">",
"self",
".",
"move_stop_delay",
":",
"self",
".",
"analyze_tracks",
"(",
"TouchTimeoutEvent",
"(",
"now",
",",
"HC",
".",
"TOUCH_MOVESTOP_TIMEOUT",
",",
"i",
")",
")",
"self",
".",
"touches",
"[",
"i",
"]",
"=",
"None",
"except",
":",
"traceback",
".",
"print_exc",
"(",
")",
"print",
"'process done.'"
] | handle events and trigger time-related events | [
"handle",
"events",
"and",
"trigger",
"time",
"-",
"related",
"events"
] | f4415c57b45cb0730e08899cbc92a2af1c047ffb | https://github.com/NetEaseGame/ATX/blob/f4415c57b45cb0730e08899cbc92a2af1c047ffb/atx/record/android_hooks.py#L334-L367 |
227,693 | NetEaseGame/ATX | atx/drivers/mixin.py | DeviceMixin.exists | def exists(self, pattern, **match_kwargs):
"""Check if image exists in screen
Returns:
If exists, return FindPoint, or
return None if result.confidence < self.image_match_threshold
"""
ret = self.match(pattern, **match_kwargs)
if ret is None:
return None
if not ret.matched:
return None
return ret | python | def exists(self, pattern, **match_kwargs):
"""Check if image exists in screen
Returns:
If exists, return FindPoint, or
return None if result.confidence < self.image_match_threshold
"""
ret = self.match(pattern, **match_kwargs)
if ret is None:
return None
if not ret.matched:
return None
return ret | [
"def",
"exists",
"(",
"self",
",",
"pattern",
",",
"*",
"*",
"match_kwargs",
")",
":",
"ret",
"=",
"self",
".",
"match",
"(",
"pattern",
",",
"*",
"*",
"match_kwargs",
")",
"if",
"ret",
"is",
"None",
":",
"return",
"None",
"if",
"not",
"ret",
".",
"matched",
":",
"return",
"None",
"return",
"ret"
] | Check if image exists in screen
Returns:
If exists, return FindPoint, or
return None if result.confidence < self.image_match_threshold | [
"Check",
"if",
"image",
"exists",
"in",
"screen"
] | f4415c57b45cb0730e08899cbc92a2af1c047ffb | https://github.com/NetEaseGame/ATX/blob/f4415c57b45cb0730e08899cbc92a2af1c047ffb/atx/drivers/mixin.py#L143-L155 |
227,694 | NetEaseGame/ATX | atx/drivers/mixin.py | DeviceMixin._match_auto | def _match_auto(self, screen, search_img, threshold):
"""Maybe not a good idea
"""
# 1. try template first
ret = ac.find_template(screen, search_img)
if ret and ret['confidence'] > threshold:
return FindPoint(ret['result'], ret['confidence'], consts.IMAGE_MATCH_METHOD_TMPL, matched=True)
# 2. try sift
ret = ac.find_sift(screen, search_img, min_match_count=10)
if ret is None:
return None
matches, total = ret['confidence']
if 1.0*matches/total > 0.5: # FIXME(ssx): sift just write here
return FindPoint(ret['result'], ret['confidence'], consts.IMAGE_MATCH_METHOD_SIFT, matched=True)
return None | python | def _match_auto(self, screen, search_img, threshold):
"""Maybe not a good idea
"""
# 1. try template first
ret = ac.find_template(screen, search_img)
if ret and ret['confidence'] > threshold:
return FindPoint(ret['result'], ret['confidence'], consts.IMAGE_MATCH_METHOD_TMPL, matched=True)
# 2. try sift
ret = ac.find_sift(screen, search_img, min_match_count=10)
if ret is None:
return None
matches, total = ret['confidence']
if 1.0*matches/total > 0.5: # FIXME(ssx): sift just write here
return FindPoint(ret['result'], ret['confidence'], consts.IMAGE_MATCH_METHOD_SIFT, matched=True)
return None | [
"def",
"_match_auto",
"(",
"self",
",",
"screen",
",",
"search_img",
",",
"threshold",
")",
":",
"# 1. try template first",
"ret",
"=",
"ac",
".",
"find_template",
"(",
"screen",
",",
"search_img",
")",
"if",
"ret",
"and",
"ret",
"[",
"'confidence'",
"]",
">",
"threshold",
":",
"return",
"FindPoint",
"(",
"ret",
"[",
"'result'",
"]",
",",
"ret",
"[",
"'confidence'",
"]",
",",
"consts",
".",
"IMAGE_MATCH_METHOD_TMPL",
",",
"matched",
"=",
"True",
")",
"# 2. try sift",
"ret",
"=",
"ac",
".",
"find_sift",
"(",
"screen",
",",
"search_img",
",",
"min_match_count",
"=",
"10",
")",
"if",
"ret",
"is",
"None",
":",
"return",
"None",
"matches",
",",
"total",
"=",
"ret",
"[",
"'confidence'",
"]",
"if",
"1.0",
"*",
"matches",
"/",
"total",
">",
"0.5",
":",
"# FIXME(ssx): sift just write here",
"return",
"FindPoint",
"(",
"ret",
"[",
"'result'",
"]",
",",
"ret",
"[",
"'confidence'",
"]",
",",
"consts",
".",
"IMAGE_MATCH_METHOD_SIFT",
",",
"matched",
"=",
"True",
")",
"return",
"None"
] | Maybe not a good idea | [
"Maybe",
"not",
"a",
"good",
"idea"
] | f4415c57b45cb0730e08899cbc92a2af1c047ffb | https://github.com/NetEaseGame/ATX/blob/f4415c57b45cb0730e08899cbc92a2af1c047ffb/atx/drivers/mixin.py#L217-L233 |
227,695 | NetEaseGame/ATX | atx/drivers/mixin.py | DeviceMixin.match_all | def match_all(self, pattern):
"""
Test method, not suggested to use
"""
pattern = self.pattern_open(pattern)
search_img = pattern.image
screen = self.region_screenshot()
screen = imutils.from_pillow(screen)
points = ac.find_all_template(screen, search_img, maxcnt=10)
return points | python | def match_all(self, pattern):
"""
Test method, not suggested to use
"""
pattern = self.pattern_open(pattern)
search_img = pattern.image
screen = self.region_screenshot()
screen = imutils.from_pillow(screen)
points = ac.find_all_template(screen, search_img, maxcnt=10)
return points | [
"def",
"match_all",
"(",
"self",
",",
"pattern",
")",
":",
"pattern",
"=",
"self",
".",
"pattern_open",
"(",
"pattern",
")",
"search_img",
"=",
"pattern",
".",
"image",
"screen",
"=",
"self",
".",
"region_screenshot",
"(",
")",
"screen",
"=",
"imutils",
".",
"from_pillow",
"(",
"screen",
")",
"points",
"=",
"ac",
".",
"find_all_template",
"(",
"screen",
",",
"search_img",
",",
"maxcnt",
"=",
"10",
")",
"return",
"points"
] | Test method, not suggested to use | [
"Test",
"method",
"not",
"suggested",
"to",
"use"
] | f4415c57b45cb0730e08899cbc92a2af1c047ffb | https://github.com/NetEaseGame/ATX/blob/f4415c57b45cb0730e08899cbc92a2af1c047ffb/atx/drivers/mixin.py#L235-L244 |
227,696 | NetEaseGame/ATX | atx/drivers/mixin.py | DeviceMixin.region_screenshot | def region_screenshot(self, filename=None):
"""Deprecated
Take part of the screenshot
"""
# warnings.warn("deprecated, use screenshot().crop(bounds) instead", DeprecationWarning)
screen = self.__last_screen if self.__keep_screen else self.screenshot()
if self.bounds:
screen = screen.crop(self.bounds)
if filename:
screen.save(filename)
return screen | python | def region_screenshot(self, filename=None):
"""Deprecated
Take part of the screenshot
"""
# warnings.warn("deprecated, use screenshot().crop(bounds) instead", DeprecationWarning)
screen = self.__last_screen if self.__keep_screen else self.screenshot()
if self.bounds:
screen = screen.crop(self.bounds)
if filename:
screen.save(filename)
return screen | [
"def",
"region_screenshot",
"(",
"self",
",",
"filename",
"=",
"None",
")",
":",
"# warnings.warn(\"deprecated, use screenshot().crop(bounds) instead\", DeprecationWarning)",
"screen",
"=",
"self",
".",
"__last_screen",
"if",
"self",
".",
"__keep_screen",
"else",
"self",
".",
"screenshot",
"(",
")",
"if",
"self",
".",
"bounds",
":",
"screen",
"=",
"screen",
".",
"crop",
"(",
"self",
".",
"bounds",
")",
"if",
"filename",
":",
"screen",
".",
"save",
"(",
"filename",
")",
"return",
"screen"
] | Deprecated
Take part of the screenshot | [
"Deprecated",
"Take",
"part",
"of",
"the",
"screenshot"
] | f4415c57b45cb0730e08899cbc92a2af1c047ffb | https://github.com/NetEaseGame/ATX/blob/f4415c57b45cb0730e08899cbc92a2af1c047ffb/atx/drivers/mixin.py#L375-L385 |
227,697 | NetEaseGame/ATX | atx/drivers/mixin.py | DeviceMixin.screenshot | def screenshot(self, filename=None):
"""
Take screen snapshot
Args:
- filename: filename where save to, optional
Returns:
PIL.Image object
Raises:
TypeError, IOError
"""
if self.__keep_screen:
return self.__last_screen
try:
screen = self._take_screenshot()
except IOError:
# try taks screenshot again
log.warn("warning, screenshot failed [2/1], retry again")
screen = self._take_screenshot()
self.__last_screen = screen
if filename:
save_dir = os.path.dirname(filename) or '.'
if not os.path.exists(save_dir):
os.makedirs(save_dir)
screen.save(filename)
return screen | python | def screenshot(self, filename=None):
"""
Take screen snapshot
Args:
- filename: filename where save to, optional
Returns:
PIL.Image object
Raises:
TypeError, IOError
"""
if self.__keep_screen:
return self.__last_screen
try:
screen = self._take_screenshot()
except IOError:
# try taks screenshot again
log.warn("warning, screenshot failed [2/1], retry again")
screen = self._take_screenshot()
self.__last_screen = screen
if filename:
save_dir = os.path.dirname(filename) or '.'
if not os.path.exists(save_dir):
os.makedirs(save_dir)
screen.save(filename)
return screen | [
"def",
"screenshot",
"(",
"self",
",",
"filename",
"=",
"None",
")",
":",
"if",
"self",
".",
"__keep_screen",
":",
"return",
"self",
".",
"__last_screen",
"try",
":",
"screen",
"=",
"self",
".",
"_take_screenshot",
"(",
")",
"except",
"IOError",
":",
"# try taks screenshot again",
"log",
".",
"warn",
"(",
"\"warning, screenshot failed [2/1], retry again\"",
")",
"screen",
"=",
"self",
".",
"_take_screenshot",
"(",
")",
"self",
".",
"__last_screen",
"=",
"screen",
"if",
"filename",
":",
"save_dir",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"filename",
")",
"or",
"'.'",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"save_dir",
")",
":",
"os",
".",
"makedirs",
"(",
"save_dir",
")",
"screen",
".",
"save",
"(",
"filename",
")",
"return",
"screen"
] | Take screen snapshot
Args:
- filename: filename where save to, optional
Returns:
PIL.Image object
Raises:
TypeError, IOError | [
"Take",
"screen",
"snapshot"
] | f4415c57b45cb0730e08899cbc92a2af1c047ffb | https://github.com/NetEaseGame/ATX/blob/f4415c57b45cb0730e08899cbc92a2af1c047ffb/atx/drivers/mixin.py#L388-L415 |
227,698 | NetEaseGame/ATX | atx/drivers/mixin.py | DeviceMixin.click_nowait | def click_nowait(self, pattern, action='click', desc=None, **match_kwargs):
""" Return immediately if no image found
Args:
- pattern (str or Pattern): filename or an opencv image object.
- action (str): click or long_click
Returns:
Click point or None
"""
point = self.match(pattern, **match_kwargs)
if not point or not point.matched:
return None
func = getattr(self, action)
func(*point.pos)
return point | python | def click_nowait(self, pattern, action='click', desc=None, **match_kwargs):
""" Return immediately if no image found
Args:
- pattern (str or Pattern): filename or an opencv image object.
- action (str): click or long_click
Returns:
Click point or None
"""
point = self.match(pattern, **match_kwargs)
if not point or not point.matched:
return None
func = getattr(self, action)
func(*point.pos)
return point | [
"def",
"click_nowait",
"(",
"self",
",",
"pattern",
",",
"action",
"=",
"'click'",
",",
"desc",
"=",
"None",
",",
"*",
"*",
"match_kwargs",
")",
":",
"point",
"=",
"self",
".",
"match",
"(",
"pattern",
",",
"*",
"*",
"match_kwargs",
")",
"if",
"not",
"point",
"or",
"not",
"point",
".",
"matched",
":",
"return",
"None",
"func",
"=",
"getattr",
"(",
"self",
",",
"action",
")",
"func",
"(",
"*",
"point",
".",
"pos",
")",
"return",
"point"
] | Return immediately if no image found
Args:
- pattern (str or Pattern): filename or an opencv image object.
- action (str): click or long_click
Returns:
Click point or None | [
"Return",
"immediately",
"if",
"no",
"image",
"found"
] | f4415c57b45cb0730e08899cbc92a2af1c047ffb | https://github.com/NetEaseGame/ATX/blob/f4415c57b45cb0730e08899cbc92a2af1c047ffb/atx/drivers/mixin.py#L471-L487 |
227,699 | NetEaseGame/ATX | atx/drivers/mixin.py | DeviceMixin.click_image | def click_image(self, pattern, timeout=20.0, action='click', safe=False, desc=None, delay=None, **match_kwargs):
"""Simulate click according image position
Args:
- pattern (str or Pattern): filename or an opencv image object.
- timeout (float): if image not found during this time, ImageNotFoundError will raise.
- action (str): click or long_click
- safe (bool): if safe is True, Exception will not raise and return None instead.
- method (str): image match method, choice of <template|sift>
- delay (float): wait for a moment then perform click
Returns:
None
Raises:
ImageNotFoundError: An error occured when img not found in current screen.
"""
pattern = self.pattern_open(pattern)
log.info('click image:%s %s', desc or '', pattern)
start_time = time.time()
found = False
point = None
while time.time() - start_time < timeout:
point = self.match(pattern, **match_kwargs)
if point is None:
sys.stdout.write('.')
sys.stdout.flush()
continue
log.debug('confidence: %s', point.confidence)
if not point.matched:
log.info('Ignore confidence: %s', point.confidence)
continue
# wait for program ready
if delay and delay > 0:
self.delay(delay)
func = getattr(self, action)
func(*point.pos)
found = True
break
sys.stdout.write('\n')
if not found:
if safe:
log.info("Image(%s) not found, safe=True, skip", pattern)
return None
raise errors.ImageNotFoundError('Not found image %s' % pattern, point)
# FIXME(ssx): maybe this function is too complex
return point | python | def click_image(self, pattern, timeout=20.0, action='click', safe=False, desc=None, delay=None, **match_kwargs):
"""Simulate click according image position
Args:
- pattern (str or Pattern): filename or an opencv image object.
- timeout (float): if image not found during this time, ImageNotFoundError will raise.
- action (str): click or long_click
- safe (bool): if safe is True, Exception will not raise and return None instead.
- method (str): image match method, choice of <template|sift>
- delay (float): wait for a moment then perform click
Returns:
None
Raises:
ImageNotFoundError: An error occured when img not found in current screen.
"""
pattern = self.pattern_open(pattern)
log.info('click image:%s %s', desc or '', pattern)
start_time = time.time()
found = False
point = None
while time.time() - start_time < timeout:
point = self.match(pattern, **match_kwargs)
if point is None:
sys.stdout.write('.')
sys.stdout.flush()
continue
log.debug('confidence: %s', point.confidence)
if not point.matched:
log.info('Ignore confidence: %s', point.confidence)
continue
# wait for program ready
if delay and delay > 0:
self.delay(delay)
func = getattr(self, action)
func(*point.pos)
found = True
break
sys.stdout.write('\n')
if not found:
if safe:
log.info("Image(%s) not found, safe=True, skip", pattern)
return None
raise errors.ImageNotFoundError('Not found image %s' % pattern, point)
# FIXME(ssx): maybe this function is too complex
return point | [
"def",
"click_image",
"(",
"self",
",",
"pattern",
",",
"timeout",
"=",
"20.0",
",",
"action",
"=",
"'click'",
",",
"safe",
"=",
"False",
",",
"desc",
"=",
"None",
",",
"delay",
"=",
"None",
",",
"*",
"*",
"match_kwargs",
")",
":",
"pattern",
"=",
"self",
".",
"pattern_open",
"(",
"pattern",
")",
"log",
".",
"info",
"(",
"'click image:%s %s'",
",",
"desc",
"or",
"''",
",",
"pattern",
")",
"start_time",
"=",
"time",
".",
"time",
"(",
")",
"found",
"=",
"False",
"point",
"=",
"None",
"while",
"time",
".",
"time",
"(",
")",
"-",
"start_time",
"<",
"timeout",
":",
"point",
"=",
"self",
".",
"match",
"(",
"pattern",
",",
"*",
"*",
"match_kwargs",
")",
"if",
"point",
"is",
"None",
":",
"sys",
".",
"stdout",
".",
"write",
"(",
"'.'",
")",
"sys",
".",
"stdout",
".",
"flush",
"(",
")",
"continue",
"log",
".",
"debug",
"(",
"'confidence: %s'",
",",
"point",
".",
"confidence",
")",
"if",
"not",
"point",
".",
"matched",
":",
"log",
".",
"info",
"(",
"'Ignore confidence: %s'",
",",
"point",
".",
"confidence",
")",
"continue",
"# wait for program ready",
"if",
"delay",
"and",
"delay",
">",
"0",
":",
"self",
".",
"delay",
"(",
"delay",
")",
"func",
"=",
"getattr",
"(",
"self",
",",
"action",
")",
"func",
"(",
"*",
"point",
".",
"pos",
")",
"found",
"=",
"True",
"break",
"sys",
".",
"stdout",
".",
"write",
"(",
"'\\n'",
")",
"if",
"not",
"found",
":",
"if",
"safe",
":",
"log",
".",
"info",
"(",
"\"Image(%s) not found, safe=True, skip\"",
",",
"pattern",
")",
"return",
"None",
"raise",
"errors",
".",
"ImageNotFoundError",
"(",
"'Not found image %s'",
"%",
"pattern",
",",
"point",
")",
"# FIXME(ssx): maybe this function is too complex",
"return",
"point"
] | Simulate click according image position
Args:
- pattern (str or Pattern): filename or an opencv image object.
- timeout (float): if image not found during this time, ImageNotFoundError will raise.
- action (str): click or long_click
- safe (bool): if safe is True, Exception will not raise and return None instead.
- method (str): image match method, choice of <template|sift>
- delay (float): wait for a moment then perform click
Returns:
None
Raises:
ImageNotFoundError: An error occured when img not found in current screen. | [
"Simulate",
"click",
"according",
"image",
"position"
] | f4415c57b45cb0730e08899cbc92a2af1c047ffb | https://github.com/NetEaseGame/ATX/blob/f4415c57b45cb0730e08899cbc92a2af1c047ffb/atx/drivers/mixin.py#L503-L555 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.